Completed
Branch master (16f63d)
by
unknown
05:48
created
modules/ticket_selector_caff/EED_Ticket_Selector_Caff.module.php 2 patches
Indentation   +383 added lines, -383 removed lines patch added patch discarded remove patch
@@ -16,408 +16,408 @@
 block discarded – undo
16 16
  */
17 17
 class EED_Ticket_Selector_Caff extends EED_Ticket_Selector
18 18
 {
19
-    /**
20
-     * @return EED_Module|EED_Ticket_Selector_Caff
21
-     * @throws EE_Error
22
-     * @throws ReflectionException
23
-     */
24
-    public static function instance()
25
-    {
26
-        return EED_Module::get_instance(__CLASS__);
27
-    }
19
+	/**
20
+	 * @return EED_Module|EED_Ticket_Selector_Caff
21
+	 * @throws EE_Error
22
+	 * @throws ReflectionException
23
+	 */
24
+	public static function instance()
25
+	{
26
+		return EED_Module::get_instance(__CLASS__);
27
+	}
28 28
 
29 29
 
30
-    /**
31
-     *    set_hooks - for hooking into EE Core, other modules, etc
32
-     *
33
-     * @access    public
34
-     * @return    void
35
-     */
36
-    public static function set_hooks()
37
-    {
38
-        add_action(
39
-            'AHEE__ticket_selector_chart_template__ticket_details__after_description',
40
-            ['EED_Ticket_Selector_Caff', 'ticket_price_details'],
41
-            10,
42
-            3
43
-        );
44
-    }
30
+	/**
31
+	 *    set_hooks - for hooking into EE Core, other modules, etc
32
+	 *
33
+	 * @access    public
34
+	 * @return    void
35
+	 */
36
+	public static function set_hooks()
37
+	{
38
+		add_action(
39
+			'AHEE__ticket_selector_chart_template__ticket_details__after_description',
40
+			['EED_Ticket_Selector_Caff', 'ticket_price_details'],
41
+			10,
42
+			3
43
+		);
44
+	}
45 45
 
46 46
 
47
-    /**
48
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
49
-     *
50
-     * @access    public
51
-     * @return    void
52
-     */
53
-    public static function set_hooks_admin()
54
-    {
55
-        define(
56
-            'TICKET_SELECTOR_CAFF_TEMPLATES_PATH',
57
-            str_replace('\\', '/', plugin_dir_path(__FILE__)) . 'templates/'
58
-        );
59
-        add_action(
60
-            'AHEE__template_settings__template__before_settings_form',
61
-            ['EED_Ticket_Selector_Caff', 'template_settings_form']
62
-        );
63
-        add_filter(
64
-            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
65
-            ['EED_Ticket_Selector_Caff', 'update_template_settings'],
66
-            10,
67
-            2
68
-        );
69
-    }
47
+	/**
48
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
49
+	 *
50
+	 * @access    public
51
+	 * @return    void
52
+	 */
53
+	public static function set_hooks_admin()
54
+	{
55
+		define(
56
+			'TICKET_SELECTOR_CAFF_TEMPLATES_PATH',
57
+			str_replace('\\', '/', plugin_dir_path(__FILE__)) . 'templates/'
58
+		);
59
+		add_action(
60
+			'AHEE__template_settings__template__before_settings_form',
61
+			['EED_Ticket_Selector_Caff', 'template_settings_form']
62
+		);
63
+		add_filter(
64
+			'FHEE__General_Settings_Admin_Page__update_template_settings__data',
65
+			['EED_Ticket_Selector_Caff', 'update_template_settings'],
66
+			10,
67
+			2
68
+		);
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * @param WP $WP
74
-     */
75
-    public function run($WP)
76
-    {
77
-        $this->set_config();
78
-    }
72
+	/**
73
+	 * @param WP $WP
74
+	 */
75
+	public function run($WP)
76
+	{
77
+		$this->set_config();
78
+	}
79 79
 
80 80
 
81
-    /**
82
-     * @static
83
-     * @return void
84
-     * @throws EE_Error
85
-     * @throws ReflectionException
86
-     */
87
-    public static function template_settings_form()
88
-    {
89
-        echo EED_Ticket_Selector_Caff::_ticket_selector_settings_form()->get_html();
90
-    }
81
+	/**
82
+	 * @static
83
+	 * @return void
84
+	 * @throws EE_Error
85
+	 * @throws ReflectionException
86
+	 */
87
+	public static function template_settings_form()
88
+	{
89
+		echo EED_Ticket_Selector_Caff::_ticket_selector_settings_form()->get_html();
90
+	}
91 91
 
92 92
 
93
-    /**
94
-     * @return EE_Form_Section_Proper
95
-     * @throws EE_Error
96
-     * @throws ReflectionException
97
-     */
98
-    public static function _ticket_selector_settings_form(): EE_Form_Section_Proper
99
-    {
100
-        return new EE_Form_Section_Proper(
101
-            [
102
-                'name'            => 'ticket_selector_settings_form',
103
-                'html_id'         => 'ticket_selector_settings_form',
104
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
105
-                'subsections'     => apply_filters(
106
-                    'FHEE__EED_Ticket_Selector_Caff___ticket_selector_settings_form__form_subsections',
107
-                    [
108
-                        'appearance_settings_hdr' => new EE_Form_Section_HTML(
109
-                            EEH_HTML::br(2) .
110
-                            EEH_HTML::h2(esc_html__('Ticket Selector Template Settings', 'event_espresso'))
111
-                        ),
112
-                        'appearance_settings'     => EED_Ticket_Selector_Caff::_ticket_selector_appearance_settings(),
113
-                    ]
114
-                ),
115
-            ]
116
-        );
117
-    }
93
+	/**
94
+	 * @return EE_Form_Section_Proper
95
+	 * @throws EE_Error
96
+	 * @throws ReflectionException
97
+	 */
98
+	public static function _ticket_selector_settings_form(): EE_Form_Section_Proper
99
+	{
100
+		return new EE_Form_Section_Proper(
101
+			[
102
+				'name'            => 'ticket_selector_settings_form',
103
+				'html_id'         => 'ticket_selector_settings_form',
104
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
105
+				'subsections'     => apply_filters(
106
+					'FHEE__EED_Ticket_Selector_Caff___ticket_selector_settings_form__form_subsections',
107
+					[
108
+						'appearance_settings_hdr' => new EE_Form_Section_HTML(
109
+							EEH_HTML::br(2) .
110
+							EEH_HTML::h2(esc_html__('Ticket Selector Template Settings', 'event_espresso'))
111
+						),
112
+						'appearance_settings'     => EED_Ticket_Selector_Caff::_ticket_selector_appearance_settings(),
113
+					]
114
+				),
115
+			]
116
+		);
117
+	}
118 118
 
119 119
 
120
-    /**
121
-     * @return EE_Form_Section_Proper
122
-     * @throws EE_Error
123
-     * @throws ReflectionException
124
-     */
125
-    public static function _ticket_selector_appearance_settings(): EE_Form_Section_Proper
126
-    {
127
-        if (
128
-            ! EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config
129
-        ) {
130
-            EED_Ticket_Selector::instance()->set_config();
131
-            EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector = EED_Ticket_Selector::instance()
132
-                                                                                                      ->config();
133
-        }
134
-        $EE_Ticket_Selector_Config = EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector;
135
-        // get option for whether to show datetime selector in TS
136
-        $show_datetime_selector = $EE_Ticket_Selector_Config->getShowDatetimeSelector();
137
-        // and option for how may datetimes must exist if display is conditional
138
-        $datetime_selector_threshold = $EE_Ticket_Selector_Config->getDatetimeSelectorThreshold();
120
+	/**
121
+	 * @return EE_Form_Section_Proper
122
+	 * @throws EE_Error
123
+	 * @throws ReflectionException
124
+	 */
125
+	public static function _ticket_selector_appearance_settings(): EE_Form_Section_Proper
126
+	{
127
+		if (
128
+			! EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config
129
+		) {
130
+			EED_Ticket_Selector::instance()->set_config();
131
+			EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector = EED_Ticket_Selector::instance()
132
+																									  ->config();
133
+		}
134
+		$EE_Ticket_Selector_Config = EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector;
135
+		// get option for whether to show datetime selector in TS
136
+		$show_datetime_selector = $EE_Ticket_Selector_Config->getShowDatetimeSelector();
137
+		// and option for how may datetimes must exist if display is conditional
138
+		$datetime_selector_threshold = $EE_Ticket_Selector_Config->getDatetimeSelectorThreshold();
139 139
 
140
-        return new EE_Form_Section_Proper(
141
-            [
142
-                'name'            => 'ticket_selector_settings_tbl',
143
-                'html_id'         => 'ticket_selector_settings_tbl',
144
-                'html_class'      => 'form-table',
145
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
146
-                'subsections'     => apply_filters(
147
-                    'FHEE__EED_Ticket_Selector_Caff___ticket_selector_appearance_settings__form_subsections',
148
-                    [
149
-                        'use_new_checkbox_selector' => new EE_Switch_Input(
150
-                            [
151
-                                'html_label_text' => esc_html__('Use New Checkbox Selector', 'event_espresso'),
152
-                                'default'        => $EE_Ticket_Selector_Config->useNewCheckboxSelector()
153
-                                    ? EE_Switch_Input::OPTION_ON
154
-                                    : EE_Switch_Input::OPTION_OFF,
155
-                                'html_name'      => 'use_new_checkbox_selector',
156
-                                'html_help_text' => esc_html__(
157
-                                    'Whether to display a a checkbox in the ticket selector when the max qty for a ticket is set to 1, meaning only one of that ticket can be purchased at a time. Defaults to off.',
158
-                                    'event_espresso'
159
-                                ),
160
-                                'layout_container_class' => 'ee-feature-highlight-2024',
161
-                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
162
-                            ],
163
-                            [
164
-                                EE_Switch_Input::OPTION_OFF => esc_html__(
165
-                                    esc_html__('new checkbox selector will NOT be used', 'event_espresso'),
166
-                                    'event_espresso'
167
-                                ),
168
-                                EE_Switch_Input::OPTION_ON  => esc_html__(
169
-                                    esc_html__('new checkbox selector WILL be used', 'event_espresso'),
170
-                                    'event_espresso'
171
-                                ),
172
-                            ]
173
-                        ),
174
-                        'use_new_form_styles' => new EE_Switch_Input(
175
-                            [
176
-                                'html_label_text' => esc_html__('Use New Ticket Selector Form Styles', 'event_espresso'),
177
-                                'default'        => $EE_Ticket_Selector_Config->useNewFormStyles()
178
-                                    ? EE_Switch_Input::OPTION_ON
179
-                                    : EE_Switch_Input::OPTION_OFF,
180
-                                'html_name'      => 'use_new_form_styles',
181
-                                'html_help_text' => esc_html__(
182
-                                    'Whether to use new form styles for the ticket selector inputs and submit button. Defaults to off.',
183
-                                    'event_espresso'
184
-                                ),
185
-                                'layout_container_class' => 'ee-feature-highlight-2024',
186
-                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
187
-                            ],
188
-                            [
189
-                                EE_Switch_Input::OPTION_OFF => esc_html__(
190
-                                    esc_html__('new form styles will NOT be used', 'event_espresso'),
191
-                                    'event_espresso'
192
-                                ),
193
-                                EE_Switch_Input::OPTION_ON  => esc_html__(
194
-                                    esc_html__('new form styles WILL be used', 'event_espresso'),
195
-                                    'event_espresso'
196
-                                ),
197
-                            ]
198
-                        ),
199
-                        'accent_color' => new EE_Text_Input(
200
-                            [
201
-                                'html_label_text' => esc_html__('Accent Color', 'event_espresso'),
202
-                                'html_help_text'  => sprintf(
203
-                                    esc_html__(
204
-                                        'Enter a hex color code to use as the accent color for the ticket selector form. Defaults to a bright blue.%1$sPRO TIP: choosing colors nearest the top right corner of the color picker tool will work best!%2$s',
205
-                                        'event_espresso'
206
-                                    ),
207
-                                    '<br><strong>',
208
-                                    '</strong>'
209
-                                ),
210
-                                'html_name'       => 'accent_color',
211
-                                'html_class'      => 'ee-input-width--tiny',
212
-                                'default'         => $EE_Ticket_Selector_Config->accentColorAsHex(),
213
-                                'layout_container_class' => 'ee-feature-highlight-2024',
214
-                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
215
-                            ],
216
-                            'color'
217
-                        ),
218
-                        'show_ticket_details'           => new EE_Yes_No_Input(
219
-                            [
220
-                                'html_label_text'         => esc_html__(
221
-                                    'Show Ticket Details?',
222
-                                    'event_espresso'
223
-                                ),
224
-                                'html_help_text'          => esc_html__(
225
-                                    'This lets you choose whether the extra ticket details section is displayed with the ticket selector.',
226
-                                    'event_espresso'
227
-                                ),
228
-                                'default'                 => $EE_Ticket_Selector_Config->show_ticket_details ?? true,
229
-                                'display_html_label_text' => false,
230
-                            ]
231
-                        ),
232
-                        'show_ticket_sale_columns'      => new EE_Yes_No_Input(
233
-                            [
234
-                                'html_label_text'         => esc_html__(
235
-                                    'Show Ticket Sale Info?',
236
-                                    'event_espresso'
237
-                                ),
238
-                                'html_help_text'          => esc_html__(
239
-                                    'This lets you indicate whether information about ticket sales is shown with ticket details in the ticket selector.',
240
-                                    'event_espresso'
241
-                                ),
242
-                                'default'                 => $EE_Ticket_Selector_Config->show_ticket_sale_columns ?? true,
243
-                                'display_html_label_text' => false,
244
-                            ]
245
-                        ),
246
-                        'show_expired_tickets'          => new EE_Yes_No_Input(
247
-                            [
248
-                                'html_label_text'         => esc_html__(
249
-                                    'Show Expired Tickets?',
250
-                                    'event_espresso'
251
-                                ),
252
-                                'html_help_text'          => esc_html__(
253
-                                    'Indicate whether to show expired tickets in the ticket selector',
254
-                                    'event_espresso'
255
-                                ),
256
-                                'default'                 => $EE_Ticket_Selector_Config->show_expired_tickets ?? true,
257
-                                'display_html_label_text' => false,
258
-                            ]
259
-                        ),
260
-                        'show_datetime_selector'        => new EE_Select_Input(
261
-                            $EE_Ticket_Selector_Config->getShowDatetimeSelectorOptions(false),
262
-                            [
263
-                                'html_label_text'         => esc_html__(
264
-                                    'Show Date & Time Filter?',
265
-                                    'event_espresso'
266
-                                ),
267
-                                'html_help_text'          => sprintf(
268
-                                    esc_html__(
269
-                                        'Indicates whether or not to display a dropdown select box above each ticket selector that displays dates and times for the available tickets. Ticket options can be unselected, which removes (hides) them from the list of tickets being displayed.%1$sOptions include:%1$s &bull; %2$sdo not show date & time filter%3$s%1$s &nbsp; this option will NEVER display a date filter, regardless of how many dates exist.%1$s &bull; %2$smaybe show date & time filter%3$s%1$s &nbsp; this option will conditionally display the date filter when the number of dates for the event matches the value set for "Date Filter Threshold".',
270
-                                        'event_espresso'
271
-                                    ),
272
-                                    '<br>',
273
-                                    '<strong>',
274
-                                    '</strong>'
275
-                                ),
276
-                                'default'                 => ! empty($show_datetime_selector)
277
-                                    ? $show_datetime_selector
278
-                                    : EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
279
-                                'display_html_label_text' => false,
280
-                                'html_class'              => 'ee-input-width--reg',
281
-                            ]
282
-                        ),
283
-                        'datetime_selector_threshold'   => new EE_Select_Input(
284
-                            array_combine($r = range(1, 10), $r),
285
-                            [
286
-                                'html_label_text'         => esc_html__(
287
-                                    'Date & Time Filter Threshold',
288
-                                    'event_espresso'
289
-                                ),
290
-                                'html_help_text'          => esc_html__(
291
-                                    'The number of unique dates an event has to have before conditionally displaying a date & time filter',
292
-                                    'event_espresso'
293
-                                ),
294
-                                'default'                 => ! empty($datetime_selector_threshold)
295
-                                    ? $datetime_selector_threshold
296
-                                    : 3,
297
-                                'display_html_label_text' => false,
298
-                                'html_class'              => 'ee-input-width--tiny',
299
-                            ]
300
-                        ),
301
-                        'datetime_selector_max_checked' => new EE_Integer_Input(
302
-                            [
303
-                                'html_label_text'         => esc_html__(
304
-                                    'Date & Time Filter Max Checked',
305
-                                    'event_espresso'
306
-                                ),
307
-                                'html_help_text'          => sprintf(
308
-                                    esc_html__(
309
-                                        'Determines the maximum number of dates that will be checked upon initial loading for a Date and Time Filter.%1$sIf set to zero or left blank, then ALL dates will be checked upon initial loading.',
310
-                                        'event_espresso'
311
-                                    ),
312
-                                    '<br>'
313
-                                ),
314
-                                'default'                 => $EE_Ticket_Selector_Config->getDatetimeSelectorMaxChecked(
315
-                                ),
316
-                                'display_html_label_text' => false,
317
-                                'min_value'               => 0,
318
-                                'html_class'              => 'ee-input-width--tiny',
319
-                            ]
320
-                        ),
321
-                    ]
322
-                ),
323
-            ]
324
-        );
325
-    }
140
+		return new EE_Form_Section_Proper(
141
+			[
142
+				'name'            => 'ticket_selector_settings_tbl',
143
+				'html_id'         => 'ticket_selector_settings_tbl',
144
+				'html_class'      => 'form-table',
145
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
146
+				'subsections'     => apply_filters(
147
+					'FHEE__EED_Ticket_Selector_Caff___ticket_selector_appearance_settings__form_subsections',
148
+					[
149
+						'use_new_checkbox_selector' => new EE_Switch_Input(
150
+							[
151
+								'html_label_text' => esc_html__('Use New Checkbox Selector', 'event_espresso'),
152
+								'default'        => $EE_Ticket_Selector_Config->useNewCheckboxSelector()
153
+									? EE_Switch_Input::OPTION_ON
154
+									: EE_Switch_Input::OPTION_OFF,
155
+								'html_name'      => 'use_new_checkbox_selector',
156
+								'html_help_text' => esc_html__(
157
+									'Whether to display a a checkbox in the ticket selector when the max qty for a ticket is set to 1, meaning only one of that ticket can be purchased at a time. Defaults to off.',
158
+									'event_espresso'
159
+								),
160
+								'layout_container_class' => 'ee-feature-highlight-2024',
161
+								'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
162
+							],
163
+							[
164
+								EE_Switch_Input::OPTION_OFF => esc_html__(
165
+									esc_html__('new checkbox selector will NOT be used', 'event_espresso'),
166
+									'event_espresso'
167
+								),
168
+								EE_Switch_Input::OPTION_ON  => esc_html__(
169
+									esc_html__('new checkbox selector WILL be used', 'event_espresso'),
170
+									'event_espresso'
171
+								),
172
+							]
173
+						),
174
+						'use_new_form_styles' => new EE_Switch_Input(
175
+							[
176
+								'html_label_text' => esc_html__('Use New Ticket Selector Form Styles', 'event_espresso'),
177
+								'default'        => $EE_Ticket_Selector_Config->useNewFormStyles()
178
+									? EE_Switch_Input::OPTION_ON
179
+									: EE_Switch_Input::OPTION_OFF,
180
+								'html_name'      => 'use_new_form_styles',
181
+								'html_help_text' => esc_html__(
182
+									'Whether to use new form styles for the ticket selector inputs and submit button. Defaults to off.',
183
+									'event_espresso'
184
+								),
185
+								'layout_container_class' => 'ee-feature-highlight-2024',
186
+								'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
187
+							],
188
+							[
189
+								EE_Switch_Input::OPTION_OFF => esc_html__(
190
+									esc_html__('new form styles will NOT be used', 'event_espresso'),
191
+									'event_espresso'
192
+								),
193
+								EE_Switch_Input::OPTION_ON  => esc_html__(
194
+									esc_html__('new form styles WILL be used', 'event_espresso'),
195
+									'event_espresso'
196
+								),
197
+							]
198
+						),
199
+						'accent_color' => new EE_Text_Input(
200
+							[
201
+								'html_label_text' => esc_html__('Accent Color', 'event_espresso'),
202
+								'html_help_text'  => sprintf(
203
+									esc_html__(
204
+										'Enter a hex color code to use as the accent color for the ticket selector form. Defaults to a bright blue.%1$sPRO TIP: choosing colors nearest the top right corner of the color picker tool will work best!%2$s',
205
+										'event_espresso'
206
+									),
207
+									'<br><strong>',
208
+									'</strong>'
209
+								),
210
+								'html_name'       => 'accent_color',
211
+								'html_class'      => 'ee-input-width--tiny',
212
+								'default'         => $EE_Ticket_Selector_Config->accentColorAsHex(),
213
+								'layout_container_class' => 'ee-feature-highlight-2024',
214
+								'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
215
+							],
216
+							'color'
217
+						),
218
+						'show_ticket_details'           => new EE_Yes_No_Input(
219
+							[
220
+								'html_label_text'         => esc_html__(
221
+									'Show Ticket Details?',
222
+									'event_espresso'
223
+								),
224
+								'html_help_text'          => esc_html__(
225
+									'This lets you choose whether the extra ticket details section is displayed with the ticket selector.',
226
+									'event_espresso'
227
+								),
228
+								'default'                 => $EE_Ticket_Selector_Config->show_ticket_details ?? true,
229
+								'display_html_label_text' => false,
230
+							]
231
+						),
232
+						'show_ticket_sale_columns'      => new EE_Yes_No_Input(
233
+							[
234
+								'html_label_text'         => esc_html__(
235
+									'Show Ticket Sale Info?',
236
+									'event_espresso'
237
+								),
238
+								'html_help_text'          => esc_html__(
239
+									'This lets you indicate whether information about ticket sales is shown with ticket details in the ticket selector.',
240
+									'event_espresso'
241
+								),
242
+								'default'                 => $EE_Ticket_Selector_Config->show_ticket_sale_columns ?? true,
243
+								'display_html_label_text' => false,
244
+							]
245
+						),
246
+						'show_expired_tickets'          => new EE_Yes_No_Input(
247
+							[
248
+								'html_label_text'         => esc_html__(
249
+									'Show Expired Tickets?',
250
+									'event_espresso'
251
+								),
252
+								'html_help_text'          => esc_html__(
253
+									'Indicate whether to show expired tickets in the ticket selector',
254
+									'event_espresso'
255
+								),
256
+								'default'                 => $EE_Ticket_Selector_Config->show_expired_tickets ?? true,
257
+								'display_html_label_text' => false,
258
+							]
259
+						),
260
+						'show_datetime_selector'        => new EE_Select_Input(
261
+							$EE_Ticket_Selector_Config->getShowDatetimeSelectorOptions(false),
262
+							[
263
+								'html_label_text'         => esc_html__(
264
+									'Show Date & Time Filter?',
265
+									'event_espresso'
266
+								),
267
+								'html_help_text'          => sprintf(
268
+									esc_html__(
269
+										'Indicates whether or not to display a dropdown select box above each ticket selector that displays dates and times for the available tickets. Ticket options can be unselected, which removes (hides) them from the list of tickets being displayed.%1$sOptions include:%1$s &bull; %2$sdo not show date & time filter%3$s%1$s &nbsp; this option will NEVER display a date filter, regardless of how many dates exist.%1$s &bull; %2$smaybe show date & time filter%3$s%1$s &nbsp; this option will conditionally display the date filter when the number of dates for the event matches the value set for "Date Filter Threshold".',
270
+										'event_espresso'
271
+									),
272
+									'<br>',
273
+									'<strong>',
274
+									'</strong>'
275
+								),
276
+								'default'                 => ! empty($show_datetime_selector)
277
+									? $show_datetime_selector
278
+									: EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
279
+								'display_html_label_text' => false,
280
+								'html_class'              => 'ee-input-width--reg',
281
+							]
282
+						),
283
+						'datetime_selector_threshold'   => new EE_Select_Input(
284
+							array_combine($r = range(1, 10), $r),
285
+							[
286
+								'html_label_text'         => esc_html__(
287
+									'Date & Time Filter Threshold',
288
+									'event_espresso'
289
+								),
290
+								'html_help_text'          => esc_html__(
291
+									'The number of unique dates an event has to have before conditionally displaying a date & time filter',
292
+									'event_espresso'
293
+								),
294
+								'default'                 => ! empty($datetime_selector_threshold)
295
+									? $datetime_selector_threshold
296
+									: 3,
297
+								'display_html_label_text' => false,
298
+								'html_class'              => 'ee-input-width--tiny',
299
+							]
300
+						),
301
+						'datetime_selector_max_checked' => new EE_Integer_Input(
302
+							[
303
+								'html_label_text'         => esc_html__(
304
+									'Date & Time Filter Max Checked',
305
+									'event_espresso'
306
+								),
307
+								'html_help_text'          => sprintf(
308
+									esc_html__(
309
+										'Determines the maximum number of dates that will be checked upon initial loading for a Date and Time Filter.%1$sIf set to zero or left blank, then ALL dates will be checked upon initial loading.',
310
+										'event_espresso'
311
+									),
312
+									'<br>'
313
+								),
314
+								'default'                 => $EE_Ticket_Selector_Config->getDatetimeSelectorMaxChecked(
315
+								),
316
+								'display_html_label_text' => false,
317
+								'min_value'               => 0,
318
+								'html_class'              => 'ee-input-width--tiny',
319
+							]
320
+						),
321
+					]
322
+				),
323
+			]
324
+		);
325
+	}
326 326
 
327 327
 
328
-    /**
329
-     * callback for updating template settings
330
-     *
331
-     * @param EE_Template_Config $CFG
332
-     * @param array              $REQ incoming request
333
-     * @return EE_Template_Config
334
-     * @throws EE_Error
335
-     * @throws InvalidArgumentException
336
-     * @throws ReflectionException
337
-     * @throws InvalidDataTypeException
338
-     * @throws InvalidInterfaceException
339
-     * @since 4.6.18.rc.006
340
-     */
341
-    public static function update_template_settings(EE_Template_Config $CFG, array $REQ): EE_Template_Config
342
-    {
343
-        /** @var EE_Capabilities $capabilities */
344
-        $capabilities = LoaderFactory::getLoader()->getShared(EE_Capabilities::class);
345
-        if (! $capabilities->current_user_can('ee_edit_events', 'edit-event-template-settings')) {
346
-            wp_die(esc_html__('You do not have the required privileges to perform this action', 'event_espresso'));
347
-        }
348
-        if (! $CFG->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config) {
349
-            EED_Ticket_Selector::instance()->set_config();
350
-            $CFG->EED_Ticket_Selector = EED_Ticket_Selector::instance()->config();
351
-        }
352
-        try {
353
-            $ticket_selector_form = EED_Ticket_Selector_Caff::_ticket_selector_settings_form();
328
+	/**
329
+	 * callback for updating template settings
330
+	 *
331
+	 * @param EE_Template_Config $CFG
332
+	 * @param array              $REQ incoming request
333
+	 * @return EE_Template_Config
334
+	 * @throws EE_Error
335
+	 * @throws InvalidArgumentException
336
+	 * @throws ReflectionException
337
+	 * @throws InvalidDataTypeException
338
+	 * @throws InvalidInterfaceException
339
+	 * @since 4.6.18.rc.006
340
+	 */
341
+	public static function update_template_settings(EE_Template_Config $CFG, array $REQ): EE_Template_Config
342
+	{
343
+		/** @var EE_Capabilities $capabilities */
344
+		$capabilities = LoaderFactory::getLoader()->getShared(EE_Capabilities::class);
345
+		if (! $capabilities->current_user_can('ee_edit_events', 'edit-event-template-settings')) {
346
+			wp_die(esc_html__('You do not have the required privileges to perform this action', 'event_espresso'));
347
+		}
348
+		if (! $CFG->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config) {
349
+			EED_Ticket_Selector::instance()->set_config();
350
+			$CFG->EED_Ticket_Selector = EED_Ticket_Selector::instance()->config();
351
+		}
352
+		try {
353
+			$ticket_selector_form = EED_Ticket_Selector_Caff::_ticket_selector_settings_form();
354 354
 
355
-            // check for form submission
356
-            if ($ticket_selector_form->was_submitted()) {
357
-                // capture form data
358
-                $ticket_selector_form->receive_form_submission();
355
+			// check for form submission
356
+			if ($ticket_selector_form->was_submitted()) {
357
+				// capture form data
358
+				$ticket_selector_form->receive_form_submission();
359 359
 
360
-                // validate form data
361
-                if ($ticket_selector_form->is_valid()) {
362
-                    // grab validated data from form
363
-                    $valid_data = $ticket_selector_form->valid_data();
360
+				// validate form data
361
+				if ($ticket_selector_form->is_valid()) {
362
+					// grab validated data from form
363
+					$valid_data = $ticket_selector_form->valid_data();
364 364
 
365
-                    // set data on config
366
-                    $CFG->EED_Ticket_Selector->show_ticket_sale_columns =
367
-                        $valid_data['appearance_settings']['show_ticket_sale_columns'] ?? false;
368
-                    $CFG->EED_Ticket_Selector->show_ticket_details      =
369
-                        $valid_data['appearance_settings']['show_ticket_details'] ?? false;
370
-                    $CFG->EED_Ticket_Selector->show_expired_tickets     =
371
-                        $valid_data['appearance_settings']['show_expired_tickets'] ?? false;
372
-                    $CFG->EED_Ticket_Selector->setShowDatetimeSelector(
373
-                        $valid_data['appearance_settings']['show_datetime_selector']
374
-                            ?? EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
375
-                    );
376
-                    $CFG->EED_Ticket_Selector->setDatetimeSelectorThreshold(
377
-                        $valid_data['appearance_settings']['datetime_selector_threshold'] ?? 3
378
-                    );
379
-                    $CFG->EED_Ticket_Selector->setDatetimeSelectorMaxChecked(
380
-                        $valid_data['appearance_settings']['datetime_selector_max_checked'] ?? 10
381
-                    );
382
-                    $CFG->EED_Ticket_Selector->setUseNewCheckboxSelector(
383
-                        $valid_data['appearance_settings']['use_new_checkbox_selector'] ?? false
384
-                    );
385
-                    $CFG->EED_Ticket_Selector->setUseNewFormStyles(
386
-                        $valid_data['appearance_settings']['use_new_form_styles'] ?? false
387
-                    );
388
-                    $CFG->EED_Ticket_Selector->setAccentColorHex(
389
-                        $valid_data['appearance_settings']['accent_color'] ?? '#0080FF'
390
-                    );
391
-                } else {
392
-                    if ($ticket_selector_form->submission_error_message() !== '') {
393
-                        EE_Error::add_error(
394
-                            $ticket_selector_form->submission_error_message(),
395
-                            __FILE__,
396
-                            __FUNCTION__,
397
-                            __LINE__
398
-                        );
399
-                    }
400
-                }
401
-            }
402
-        } catch (EE_Error $e) {
403
-            $e->get_error();
404
-        }
365
+					// set data on config
366
+					$CFG->EED_Ticket_Selector->show_ticket_sale_columns =
367
+						$valid_data['appearance_settings']['show_ticket_sale_columns'] ?? false;
368
+					$CFG->EED_Ticket_Selector->show_ticket_details      =
369
+						$valid_data['appearance_settings']['show_ticket_details'] ?? false;
370
+					$CFG->EED_Ticket_Selector->show_expired_tickets     =
371
+						$valid_data['appearance_settings']['show_expired_tickets'] ?? false;
372
+					$CFG->EED_Ticket_Selector->setShowDatetimeSelector(
373
+						$valid_data['appearance_settings']['show_datetime_selector']
374
+							?? EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
375
+					);
376
+					$CFG->EED_Ticket_Selector->setDatetimeSelectorThreshold(
377
+						$valid_data['appearance_settings']['datetime_selector_threshold'] ?? 3
378
+					);
379
+					$CFG->EED_Ticket_Selector->setDatetimeSelectorMaxChecked(
380
+						$valid_data['appearance_settings']['datetime_selector_max_checked'] ?? 10
381
+					);
382
+					$CFG->EED_Ticket_Selector->setUseNewCheckboxSelector(
383
+						$valid_data['appearance_settings']['use_new_checkbox_selector'] ?? false
384
+					);
385
+					$CFG->EED_Ticket_Selector->setUseNewFormStyles(
386
+						$valid_data['appearance_settings']['use_new_form_styles'] ?? false
387
+					);
388
+					$CFG->EED_Ticket_Selector->setAccentColorHex(
389
+						$valid_data['appearance_settings']['accent_color'] ?? '#0080FF'
390
+					);
391
+				} else {
392
+					if ($ticket_selector_form->submission_error_message() !== '') {
393
+						EE_Error::add_error(
394
+							$ticket_selector_form->submission_error_message(),
395
+							__FILE__,
396
+							__FUNCTION__,
397
+							__LINE__
398
+						);
399
+					}
400
+				}
401
+			}
402
+		} catch (EE_Error $e) {
403
+			$e->get_error();
404
+		}
405 405
 
406
-        return $CFG;
407
-    }
406
+		return $CFG;
407
+	}
408 408
 
409 409
 
410
-    /**
411
-     * @param EE_Ticket $ticket
412
-     * @param float     $ticket_price
413
-     * @param bool      $display_ticket_price
414
-     */
415
-    public static function ticket_price_details(
416
-        EE_Ticket $ticket,
417
-        float $ticket_price = 0.0,
418
-        bool $display_ticket_price = false
419
-    ) {
420
-        require str_replace('\\', '/', plugin_dir_path(__FILE__))
421
-            . 'templates/ticket_selector_price_details.template.php';
422
-    }
410
+	/**
411
+	 * @param EE_Ticket $ticket
412
+	 * @param float     $ticket_price
413
+	 * @param bool      $display_ticket_price
414
+	 */
415
+	public static function ticket_price_details(
416
+		EE_Ticket $ticket,
417
+		float $ticket_price = 0.0,
418
+		bool $display_ticket_price = false
419
+	) {
420
+		require str_replace('\\', '/', plugin_dir_path(__FILE__))
421
+			. 'templates/ticket_selector_price_details.template.php';
422
+	}
423 423
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
     {
55 55
         define(
56 56
             'TICKET_SELECTOR_CAFF_TEMPLATES_PATH',
57
-            str_replace('\\', '/', plugin_dir_path(__FILE__)) . 'templates/'
57
+            str_replace('\\', '/', plugin_dir_path(__FILE__)).'templates/'
58 58
         );
59 59
         add_action(
60 60
             'AHEE__template_settings__template__before_settings_form',
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
                     'FHEE__EED_Ticket_Selector_Caff___ticket_selector_settings_form__form_subsections',
107 107
                     [
108 108
                         'appearance_settings_hdr' => new EE_Form_Section_HTML(
109
-                            EEH_HTML::br(2) .
109
+                            EEH_HTML::br(2).
110 110
                             EEH_HTML::h2(esc_html__('Ticket Selector Template Settings', 'event_espresso'))
111 111
                         ),
112 112
                         'appearance_settings'     => EED_Ticket_Selector_Caff::_ticket_selector_appearance_settings(),
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
                                     'event_espresso'
159 159
                                 ),
160 160
                                 'layout_container_class' => 'ee-feature-highlight-2024',
161
-                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
161
+                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ '.esc_html__('NEW', 'event_espresso').'</span>',
162 162
                             ],
163 163
                             [
164 164
                                 EE_Switch_Input::OPTION_OFF => esc_html__(
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
                                     'event_espresso'
184 184
                                 ),
185 185
                                 'layout_container_class' => 'ee-feature-highlight-2024',
186
-                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
186
+                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ '.esc_html__('NEW', 'event_espresso').'</span>',
187 187
                             ],
188 188
                             [
189 189
                                 EE_Switch_Input::OPTION_OFF => esc_html__(
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
                                 'html_class'      => 'ee-input-width--tiny',
212 212
                                 'default'         => $EE_Ticket_Selector_Config->accentColorAsHex(),
213 213
                                 'layout_container_class' => 'ee-feature-highlight-2024',
214
-                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ ' . esc_html__('NEW','event_espresso') . '</span>',
214
+                                'extra_container_html' => '<span class="ee-feature-highlight-2024-notice">✨ '.esc_html__('NEW', 'event_espresso').'</span>',
215 215
                             ],
216 216
                             'color'
217 217
                         ),
@@ -342,10 +342,10 @@  discard block
 block discarded – undo
342 342
     {
343 343
         /** @var EE_Capabilities $capabilities */
344 344
         $capabilities = LoaderFactory::getLoader()->getShared(EE_Capabilities::class);
345
-        if (! $capabilities->current_user_can('ee_edit_events', 'edit-event-template-settings')) {
345
+        if ( ! $capabilities->current_user_can('ee_edit_events', 'edit-event-template-settings')) {
346 346
             wp_die(esc_html__('You do not have the required privileges to perform this action', 'event_espresso'));
347 347
         }
348
-        if (! $CFG->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config) {
348
+        if ( ! $CFG->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config) {
349 349
             EED_Ticket_Selector::instance()->set_config();
350 350
             $CFG->EED_Ticket_Selector = EED_Ticket_Selector::instance()->config();
351 351
         }
Please login to merge, or discard this patch.
caffeinated/core/domain/services/pue/StatsGatherer.php 1 patch
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -19,288 +19,288 @@
 block discarded – undo
19 19
  */
20 20
 class StatsGatherer
21 21
 {
22
-    public const COUNT_ALL_EVENTS                 = 'event';
22
+	public const COUNT_ALL_EVENTS                 = 'event';
23 23
 
24
-    public const COUNT_ACTIVE_EVENTS              = 'active_event';
24
+	public const COUNT_ACTIVE_EVENTS              = 'active_event';
25 25
 
26
-    public const COUNT_DATETIMES                  = 'datetime';
26
+	public const COUNT_DATETIMES                  = 'datetime';
27 27
 
28
-    public const COUNT_TICKETS                    = 'ticket';
28
+	public const COUNT_TICKETS                    = 'ticket';
29 29
 
30
-    public const COUNT_DATETIMES_SOLD             = 'datetime_sold';
30
+	public const COUNT_DATETIMES_SOLD             = 'datetime_sold';
31 31
 
32
-    public const COUNT_TICKETS_FREE               = 'free_ticket';
32
+	public const COUNT_TICKETS_FREE               = 'free_ticket';
33 33
 
34
-    public const COUNT_TICKETS_PAID               = 'paid_ticket';
34
+	public const COUNT_TICKETS_PAID               = 'paid_ticket';
35 35
 
36
-    public const COUNT_TICKETS_SOLD               = 'ticket_sold';
36
+	public const COUNT_TICKETS_SOLD               = 'ticket_sold';
37 37
 
38
-    public const COUNT_REGISTRATIONS_APPROVED     = 'registrations_approved';
38
+	public const COUNT_REGISTRATIONS_APPROVED     = 'registrations_approved';
39 39
 
40
-    public const COUNT_REGISTRATIONS_NOT_APPROVED = 'registrations_not_approved';
40
+	public const COUNT_REGISTRATIONS_NOT_APPROVED = 'registrations_not_approved';
41 41
 
42
-    public const COUNT_REGISTRATIONS_PENDING      = 'registrations_pending';
42
+	public const COUNT_REGISTRATIONS_PENDING      = 'registrations_pending';
43 43
 
44
-    public const COUNT_REGISTRATIONS_INCOMPLETE   = 'registrations_incomplete';
44
+	public const COUNT_REGISTRATIONS_INCOMPLETE   = 'registrations_incomplete';
45 45
 
46
-    public const COUNT_REGISTRATIONS_ALL          = 'registrations_all';
46
+	public const COUNT_REGISTRATIONS_ALL          = 'registrations_all';
47 47
 
48
-    public const COUNT_REGISTRATIONS_CANCELLED    = 'registrations_cancelled';
48
+	public const COUNT_REGISTRATIONS_CANCELLED    = 'registrations_cancelled';
49 49
 
50
-    public const COUNT_REGISTRATIONS_DECLINED     = 'registrations_declined';
50
+	public const COUNT_REGISTRATIONS_DECLINED     = 'registrations_declined';
51 51
 
52
-    public const SUM_TRANSACTIONS_COMPLETE_TOTAL  = 'transactions_complete_total_sum';
52
+	public const SUM_TRANSACTIONS_COMPLETE_TOTAL  = 'transactions_complete_total_sum';
53 53
 
54
-    public const SUM_TRANSACTIONS_ALL_PAID        = 'transactions_all_paid';
54
+	public const SUM_TRANSACTIONS_ALL_PAID        = 'transactions_all_paid';
55 55
 
56
-    public const INFO_SITE_CURRENCY               = 'site_currency';
56
+	public const INFO_SITE_CURRENCY               = 'site_currency';
57 57
 
58 58
 
59
-    /**
60
-     * @var EEM_Payment_Method
61
-     */
62
-    private $payment_method_model;
63
-
64
-
65
-    /**
66
-     * @var EEM_Event
67
-     */
68
-    private $event_model;
69
-
70
-    /**
71
-     * @var EEM_Datetime
72
-     */
73
-    private $datetime_model;
74
-
75
-
76
-    /**
77
-     * @var EEM_Ticket
78
-     */
79
-    private $ticket_model;
80
-
81
-
82
-    /**
83
-     * @var EEM_Registration
84
-     */
85
-    private $registration_model;
86
-
87
-
88
-    /**
89
-     * @var EEM_Transaction
90
-     */
91
-    private $transaction_model;
92
-
93
-
94
-    /**
95
-     * @var EE_Config
96
-     */
97
-    private $config;
98
-
99
-
100
-    /**
101
-     * StatsGatherer constructor.
102
-     *
103
-     * @param EEM_Payment_Method $payment_method_model
104
-     * @param EEM_Event          $event_model
105
-     * @param EEM_Datetime       $datetime_model
106
-     * @param EEM_Ticket         $ticket_model
107
-     * @param EEM_Registration   $registration_model
108
-     * @param EEM_Transaction    $transaction_model
109
-     * @param EE_Config          $config
110
-     */
111
-    public function __construct(
112
-        EEM_Payment_Method $payment_method_model,
113
-        EEM_Event $event_model,
114
-        EEM_Datetime $datetime_model,
115
-        EEM_Ticket $ticket_model,
116
-        EEM_Registration $registration_model,
117
-        EEM_Transaction $transaction_model,
118
-        EE_Config $config
119
-    ) {
120
-        $this->payment_method_model = $payment_method_model;
121
-        $this->event_model          = $event_model;
122
-        $this->datetime_model       = $datetime_model;
123
-        $this->ticket_model         = $ticket_model;
124
-        $this->registration_model   = $registration_model;
125
-        $this->transaction_model    = $transaction_model;
126
-        $this->config               = $config;
127
-    }
128
-
129
-
130
-    /**
131
-     * Return the stats array for PUE UXIP stats.
132
-     *
133
-     * @return array
134
-     */
135
-    public function stats(): array
136
-    {
137
-        global $wp_version;
138
-        $stats = $this->paymentMethodStats();
139
-        // a-ok so let's setup our stats.
140
-        $stats = array_merge(
141
-            $stats,
142
-            [
143
-                'is_multisite'                    => is_multisite() && is_main_site(),
144
-                'active_theme'                    => $this->getActiveThemeStat(),
145
-                'ee4_all_events_count'            => $this->getCountFor(self::COUNT_ALL_EVENTS),
146
-                'ee4_active_events_count'         => $this->getCountFor(self::COUNT_ACTIVE_EVENTS),
147
-                'all_dtts_count'                  => $this->getCountFor(self::COUNT_DATETIMES),
148
-                'dtt_sold'                        => $this->getCountFor(self::COUNT_DATETIMES_SOLD),
149
-                'all_tkt_count'                   => $this->getCountFor(self::COUNT_TICKETS),
150
-                'free_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_FREE),
151
-                'paid_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_PAID),
152
-                'tkt_sold'                        => $this->getCountFor(self::COUNT_TICKETS_SOLD),
153
-                'approve_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_APPROVED),
154
-                'pending_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_PENDING),
155
-                'not_approved_registration_count' => $this->getCountFor(self::COUNT_REGISTRATIONS_NOT_APPROVED),
156
-                'incomplete_registration_count'   => $this->getCountFor(self::COUNT_REGISTRATIONS_INCOMPLETE),
157
-                'cancelled_registration_count'    => $this->getCountFor(self::COUNT_REGISTRATIONS_CANCELLED),
158
-                'declined_registration_count'     => $this->getCountFor(self::COUNT_REGISTRATIONS_DECLINED),
159
-                'all_registration_count'          => $this->getCountFor(self::COUNT_REGISTRATIONS_ALL),
160
-                'completed_transaction_total_sum' => $this->getCountFor(self::SUM_TRANSACTIONS_COMPLETE_TOTAL),
161
-                'all_transaction_paid_sum'        => $this->getCountFor(self::SUM_TRANSACTIONS_ALL_PAID),
162
-                self::INFO_SITE_CURRENCY          => $this->config->currency instanceof EE_Currency_Config
163
-                    ? $this->config->currency->code
164
-                    : 'unknown',
165
-                'phpversion'                      => implode(
166
-                    '.',
167
-                    [PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION]
168
-                ),
169
-                'wpversion'                       => $wp_version,
170
-                'active_addons'                   => $this->getActiveAddons(),
171
-            ]
172
-        );
173
-        // remove any values that equal null.  This ensures any stats that weren't retrieved successfully are excluded.
174
-        return array_filter($stats, function ($value) {
175
-            return $value !== null;
176
-        });
177
-    }
178
-
179
-
180
-    /**
181
-     * @param string $which enum (@see constants prefixed with COUNT)
182
-     * @return int|float|null
183
-     */
184
-    private function getCountFor(string $which)
185
-    {
186
-        try {
187
-            switch ($which) {
188
-                case self::COUNT_ALL_EVENTS:
189
-                    $count = $this->event_model->count();
190
-                    break;
191
-                case self::COUNT_TICKETS:
192
-                    $count = $this->ticket_model->count();
193
-                    break;
194
-                case self::COUNT_DATETIMES:
195
-                    $count = $this->datetime_model->count();
196
-                    break;
197
-                case self::COUNT_ACTIVE_EVENTS:
198
-                    $count = $this->event_model->get_active_events([], true);
199
-                    break;
200
-                case self::COUNT_DATETIMES_SOLD:
201
-                    $count = $this->datetime_model->sum([], 'DTT_sold');
202
-                    break;
203
-                case self::COUNT_TICKETS_FREE:
204
-                    $count = $this->ticket_model->count([['TKT_price' => 0]]);
205
-                    break;
206
-                case self::COUNT_TICKETS_PAID:
207
-                    $count = $this->ticket_model->count([['TKT_price' => ['>', 0]]]);
208
-                    break;
209
-                case self::COUNT_TICKETS_SOLD:
210
-                    $count = $this->ticket_model->sum([], 'TKT_sold');
211
-                    break;
212
-                case self::COUNT_REGISTRATIONS_ALL:
213
-                    $count = $this->registration_model->count();
214
-                    break;
215
-                case self::COUNT_REGISTRATIONS_CANCELLED:
216
-                    $count = $this->registration_model->count([['STS_ID' => RegStatus::CANCELLED]]);
217
-                    break;
218
-                case self::COUNT_REGISTRATIONS_INCOMPLETE:
219
-                    $count = $this->registration_model->count([['STS_ID' => RegStatus::INCOMPLETE]]);
220
-                    break;
221
-                case self::COUNT_REGISTRATIONS_NOT_APPROVED:
222
-                    $count = $this->registration_model->count([['STS_ID' => RegStatus::AWAITING_REVIEW]]);
223
-                    break;
224
-                case self::COUNT_REGISTRATIONS_DECLINED:
225
-                    $count = $this->registration_model->count([['STS_ID' => RegStatus::DECLINED]]);
226
-                    break;
227
-                case self::COUNT_REGISTRATIONS_PENDING:
228
-                    $count = $this->registration_model->count(
229
-                        [['STS_ID' => RegStatus::PENDING_PAYMENT]]
230
-                    );
231
-                    break;
232
-                case self::COUNT_REGISTRATIONS_APPROVED:
233
-                    $count = $this->registration_model->count([['STS_ID' => RegStatus::APPROVED]]);
234
-                    break;
235
-                case self::SUM_TRANSACTIONS_COMPLETE_TOTAL:
236
-                    $count = $this->transaction_model->sum(
237
-                        [['STS_ID' => EEM_Transaction::complete_status_code]],
238
-                        'TXN_total'
239
-                    );
240
-                    break;
241
-                case self::SUM_TRANSACTIONS_ALL_PAID:
242
-                    $count = $this->transaction_model->sum([], 'TXN_paid');
243
-                    break;
244
-                default:
245
-                    $count = null;
246
-                    break;
247
-            }
248
-        } catch (Exception $e) {
249
-            $count = null;
250
-        }
251
-        return $count;
252
-    }
253
-
254
-
255
-    /**
256
-     * Return the active theme.
257
-     *
258
-     * @return false|string
259
-     */
260
-    private function getActiveThemeStat()
261
-    {
262
-        $theme = wp_get_theme();
263
-        return $theme->get('Name');
264
-    }
265
-
266
-
267
-    /**
268
-     * @return array
269
-     */
270
-    private function paymentMethodStats(): array
271
-    {
272
-        $payment_method_stats = [];
273
-        try {
274
-            $active_payment_methods = $this->payment_method_model->get_all_active(
275
-                '',
276
-                ['group_by' => 'PMD_type']
277
-            );
278
-            if ($active_payment_methods) {
279
-                foreach ($active_payment_methods as $payment_method) {
280
-                    $payment_method_stats[ $payment_method->name() . '_active_payment_method' ] = 1;
281
-                }
282
-            }
283
-        } catch (Exception $e) {
284
-            // do nothing just prevents fatals.
285
-        }
286
-        return $payment_method_stats;
287
-    }
288
-
289
-
290
-    /**
291
-     * Return a list of active EE add-ons and their versions.
292
-     *
293
-     * @return string
294
-     */
295
-    private function getActiveAddons(): string
296
-    {
297
-        $activeAddons = [];
298
-        $addOns       = EE_Registry::instance()->addons;
299
-        if (! empty($addOns)) {
300
-            foreach ($addOns as $addon) {
301
-                $activeAddons[] = $addon->name() . '@' . $addon->version();
302
-            }
303
-        }
304
-        return implode(',', $activeAddons);
305
-    }
59
+	/**
60
+	 * @var EEM_Payment_Method
61
+	 */
62
+	private $payment_method_model;
63
+
64
+
65
+	/**
66
+	 * @var EEM_Event
67
+	 */
68
+	private $event_model;
69
+
70
+	/**
71
+	 * @var EEM_Datetime
72
+	 */
73
+	private $datetime_model;
74
+
75
+
76
+	/**
77
+	 * @var EEM_Ticket
78
+	 */
79
+	private $ticket_model;
80
+
81
+
82
+	/**
83
+	 * @var EEM_Registration
84
+	 */
85
+	private $registration_model;
86
+
87
+
88
+	/**
89
+	 * @var EEM_Transaction
90
+	 */
91
+	private $transaction_model;
92
+
93
+
94
+	/**
95
+	 * @var EE_Config
96
+	 */
97
+	private $config;
98
+
99
+
100
+	/**
101
+	 * StatsGatherer constructor.
102
+	 *
103
+	 * @param EEM_Payment_Method $payment_method_model
104
+	 * @param EEM_Event          $event_model
105
+	 * @param EEM_Datetime       $datetime_model
106
+	 * @param EEM_Ticket         $ticket_model
107
+	 * @param EEM_Registration   $registration_model
108
+	 * @param EEM_Transaction    $transaction_model
109
+	 * @param EE_Config          $config
110
+	 */
111
+	public function __construct(
112
+		EEM_Payment_Method $payment_method_model,
113
+		EEM_Event $event_model,
114
+		EEM_Datetime $datetime_model,
115
+		EEM_Ticket $ticket_model,
116
+		EEM_Registration $registration_model,
117
+		EEM_Transaction $transaction_model,
118
+		EE_Config $config
119
+	) {
120
+		$this->payment_method_model = $payment_method_model;
121
+		$this->event_model          = $event_model;
122
+		$this->datetime_model       = $datetime_model;
123
+		$this->ticket_model         = $ticket_model;
124
+		$this->registration_model   = $registration_model;
125
+		$this->transaction_model    = $transaction_model;
126
+		$this->config               = $config;
127
+	}
128
+
129
+
130
+	/**
131
+	 * Return the stats array for PUE UXIP stats.
132
+	 *
133
+	 * @return array
134
+	 */
135
+	public function stats(): array
136
+	{
137
+		global $wp_version;
138
+		$stats = $this->paymentMethodStats();
139
+		// a-ok so let's setup our stats.
140
+		$stats = array_merge(
141
+			$stats,
142
+			[
143
+				'is_multisite'                    => is_multisite() && is_main_site(),
144
+				'active_theme'                    => $this->getActiveThemeStat(),
145
+				'ee4_all_events_count'            => $this->getCountFor(self::COUNT_ALL_EVENTS),
146
+				'ee4_active_events_count'         => $this->getCountFor(self::COUNT_ACTIVE_EVENTS),
147
+				'all_dtts_count'                  => $this->getCountFor(self::COUNT_DATETIMES),
148
+				'dtt_sold'                        => $this->getCountFor(self::COUNT_DATETIMES_SOLD),
149
+				'all_tkt_count'                   => $this->getCountFor(self::COUNT_TICKETS),
150
+				'free_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_FREE),
151
+				'paid_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_PAID),
152
+				'tkt_sold'                        => $this->getCountFor(self::COUNT_TICKETS_SOLD),
153
+				'approve_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_APPROVED),
154
+				'pending_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_PENDING),
155
+				'not_approved_registration_count' => $this->getCountFor(self::COUNT_REGISTRATIONS_NOT_APPROVED),
156
+				'incomplete_registration_count'   => $this->getCountFor(self::COUNT_REGISTRATIONS_INCOMPLETE),
157
+				'cancelled_registration_count'    => $this->getCountFor(self::COUNT_REGISTRATIONS_CANCELLED),
158
+				'declined_registration_count'     => $this->getCountFor(self::COUNT_REGISTRATIONS_DECLINED),
159
+				'all_registration_count'          => $this->getCountFor(self::COUNT_REGISTRATIONS_ALL),
160
+				'completed_transaction_total_sum' => $this->getCountFor(self::SUM_TRANSACTIONS_COMPLETE_TOTAL),
161
+				'all_transaction_paid_sum'        => $this->getCountFor(self::SUM_TRANSACTIONS_ALL_PAID),
162
+				self::INFO_SITE_CURRENCY          => $this->config->currency instanceof EE_Currency_Config
163
+					? $this->config->currency->code
164
+					: 'unknown',
165
+				'phpversion'                      => implode(
166
+					'.',
167
+					[PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION]
168
+				),
169
+				'wpversion'                       => $wp_version,
170
+				'active_addons'                   => $this->getActiveAddons(),
171
+			]
172
+		);
173
+		// remove any values that equal null.  This ensures any stats that weren't retrieved successfully are excluded.
174
+		return array_filter($stats, function ($value) {
175
+			return $value !== null;
176
+		});
177
+	}
178
+
179
+
180
+	/**
181
+	 * @param string $which enum (@see constants prefixed with COUNT)
182
+	 * @return int|float|null
183
+	 */
184
+	private function getCountFor(string $which)
185
+	{
186
+		try {
187
+			switch ($which) {
188
+				case self::COUNT_ALL_EVENTS:
189
+					$count = $this->event_model->count();
190
+					break;
191
+				case self::COUNT_TICKETS:
192
+					$count = $this->ticket_model->count();
193
+					break;
194
+				case self::COUNT_DATETIMES:
195
+					$count = $this->datetime_model->count();
196
+					break;
197
+				case self::COUNT_ACTIVE_EVENTS:
198
+					$count = $this->event_model->get_active_events([], true);
199
+					break;
200
+				case self::COUNT_DATETIMES_SOLD:
201
+					$count = $this->datetime_model->sum([], 'DTT_sold');
202
+					break;
203
+				case self::COUNT_TICKETS_FREE:
204
+					$count = $this->ticket_model->count([['TKT_price' => 0]]);
205
+					break;
206
+				case self::COUNT_TICKETS_PAID:
207
+					$count = $this->ticket_model->count([['TKT_price' => ['>', 0]]]);
208
+					break;
209
+				case self::COUNT_TICKETS_SOLD:
210
+					$count = $this->ticket_model->sum([], 'TKT_sold');
211
+					break;
212
+				case self::COUNT_REGISTRATIONS_ALL:
213
+					$count = $this->registration_model->count();
214
+					break;
215
+				case self::COUNT_REGISTRATIONS_CANCELLED:
216
+					$count = $this->registration_model->count([['STS_ID' => RegStatus::CANCELLED]]);
217
+					break;
218
+				case self::COUNT_REGISTRATIONS_INCOMPLETE:
219
+					$count = $this->registration_model->count([['STS_ID' => RegStatus::INCOMPLETE]]);
220
+					break;
221
+				case self::COUNT_REGISTRATIONS_NOT_APPROVED:
222
+					$count = $this->registration_model->count([['STS_ID' => RegStatus::AWAITING_REVIEW]]);
223
+					break;
224
+				case self::COUNT_REGISTRATIONS_DECLINED:
225
+					$count = $this->registration_model->count([['STS_ID' => RegStatus::DECLINED]]);
226
+					break;
227
+				case self::COUNT_REGISTRATIONS_PENDING:
228
+					$count = $this->registration_model->count(
229
+						[['STS_ID' => RegStatus::PENDING_PAYMENT]]
230
+					);
231
+					break;
232
+				case self::COUNT_REGISTRATIONS_APPROVED:
233
+					$count = $this->registration_model->count([['STS_ID' => RegStatus::APPROVED]]);
234
+					break;
235
+				case self::SUM_TRANSACTIONS_COMPLETE_TOTAL:
236
+					$count = $this->transaction_model->sum(
237
+						[['STS_ID' => EEM_Transaction::complete_status_code]],
238
+						'TXN_total'
239
+					);
240
+					break;
241
+				case self::SUM_TRANSACTIONS_ALL_PAID:
242
+					$count = $this->transaction_model->sum([], 'TXN_paid');
243
+					break;
244
+				default:
245
+					$count = null;
246
+					break;
247
+			}
248
+		} catch (Exception $e) {
249
+			$count = null;
250
+		}
251
+		return $count;
252
+	}
253
+
254
+
255
+	/**
256
+	 * Return the active theme.
257
+	 *
258
+	 * @return false|string
259
+	 */
260
+	private function getActiveThemeStat()
261
+	{
262
+		$theme = wp_get_theme();
263
+		return $theme->get('Name');
264
+	}
265
+
266
+
267
+	/**
268
+	 * @return array
269
+	 */
270
+	private function paymentMethodStats(): array
271
+	{
272
+		$payment_method_stats = [];
273
+		try {
274
+			$active_payment_methods = $this->payment_method_model->get_all_active(
275
+				'',
276
+				['group_by' => 'PMD_type']
277
+			);
278
+			if ($active_payment_methods) {
279
+				foreach ($active_payment_methods as $payment_method) {
280
+					$payment_method_stats[ $payment_method->name() . '_active_payment_method' ] = 1;
281
+				}
282
+			}
283
+		} catch (Exception $e) {
284
+			// do nothing just prevents fatals.
285
+		}
286
+		return $payment_method_stats;
287
+	}
288
+
289
+
290
+	/**
291
+	 * Return a list of active EE add-ons and their versions.
292
+	 *
293
+	 * @return string
294
+	 */
295
+	private function getActiveAddons(): string
296
+	{
297
+		$activeAddons = [];
298
+		$addOns       = EE_Registry::instance()->addons;
299
+		if (! empty($addOns)) {
300
+			foreach ($addOns as $addon) {
301
+				$activeAddons[] = $addon->name() . '@' . $addon->version();
302
+			}
303
+		}
304
+		return implode(',', $activeAddons);
305
+	}
306 306
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Payment_Method.model.php 2 patches
Indentation   +462 added lines, -462 removed lines patch added patch discarded remove patch
@@ -17,466 +17,466 @@
 block discarded – undo
17 17
  */
18 18
 class EEM_Payment_Method extends EEM_Base
19 19
 {
20
-    const scope_cart  = 'CART';
21
-
22
-    const scope_admin = 'ADMIN';
23
-
24
-    const scope_api   = 'API';
25
-
26
-
27
-    protected static ?EEM_Payment_Method $_instance = null;
28
-
29
-
30
-    /**
31
-     * private constructor to prevent direct creation
32
-     *
33
-     * @param string|null $timezone
34
-     * @throws EE_Error
35
-     */
36
-    protected function __construct(?string $timezone = '')
37
-    {
38
-        $this->singular_item    = esc_html__('Payment Method', 'event_espresso');
39
-        $this->plural_item      = esc_html__('Payment Methods', 'event_espresso');
40
-        $this->_tables          = [
41
-            'Payment_Method' => new EE_Primary_Table('esp_payment_method', 'PMD_ID'),
42
-        ];
43
-        $this->_fields          = [
44
-            'Payment_Method' => [
45
-                'PMD_ID'              => new EE_Primary_Key_Int_Field(
46
-                    'PMD_ID',
47
-                    esc_html__('ID', 'event_espresso')
48
-                ),
49
-                'PMD_type'            => new EE_Plain_Text_Field(
50
-                    'PMD_type',
51
-                    esc_html__('Payment Method Type', 'event_espresso'),
52
-                    false,
53
-                    'Admin_Only'
54
-                ),
55
-                'PMD_name'            => new EE_Plain_Text_Field(
56
-                    'PMD_name',
57
-                    esc_html__('Name', 'event_espresso'),
58
-                    false
59
-                ),
60
-                'PMD_desc'            => new EE_Post_Content_Field(
61
-                    'PMD_desc',
62
-                    esc_html__('Description', 'event_espresso'),
63
-                    false,
64
-                    ''
65
-                ),
66
-                'PMD_admin_name'      => new EE_Plain_Text_Field(
67
-                    'PMD_admin_name',
68
-                    esc_html__('Admin-Only Name', 'event_espresso'),
69
-                    true
70
-                ),
71
-                'PMD_admin_desc'      => new EE_Post_Content_Field(
72
-                    'PMD_admin_desc',
73
-                    esc_html__('Admin-Only Description', 'event_espresso'),
74
-                    true,
75
-                    ''
76
-                ),
77
-                'PMD_slug'            => new EE_Slug_Field(
78
-                    'PMD_slug',
79
-                    esc_html__('Slug', 'event_espresso'),
80
-                    false
81
-                ),
82
-                'PMD_order'           => new EE_Integer_Field(
83
-                    'PMD_order',
84
-                    esc_html__('Order', 'event_espresso'),
85
-                    false,
86
-                    0
87
-                ),
88
-                'PMD_debug_mode'      => new EE_Boolean_Field(
89
-                    'PMD_debug_mode',
90
-                    esc_html__('Sandbox Mode On? (AKA: debug mode)', 'event_espresso'),
91
-                    false,
92
-                    false
93
-                ),
94
-                'PMD_wp_user'         => new EE_WP_User_Field(
95
-                    'PMD_wp_user',
96
-                    esc_html__('Payment Method Creator ID', 'event_espresso'),
97
-                    false
98
-                ),
99
-                'PMD_open_by_default' => new EE_Boolean_Field(
100
-                    'PMD_open_by_default',
101
-                    esc_html__('Open by Default?', 'event_espresso'),
102
-                    false,
103
-                    false
104
-                ),
105
-                'PMD_button_url'      => new EE_Plain_Text_Field(
106
-                    'PMD_button_url',
107
-                    esc_html__('Button URL', 'event_espresso'),
108
-                    true,
109
-                    ''
110
-                ),
111
-                'PMD_scope'           => new EE_Serialized_Text_Field(
112
-                    'PMD_scope',
113
-                    esc_html__('Usable From?', 'event_espresso'),
114
-                    false,
115
-                    []// possible values currently are 'CART','ADMIN','API'
116
-                ),
117
-            ],
118
-        ];
119
-        $this->_model_relations = [
120
-            'Currency'    => new EE_HABTM_Relation('Currency_Payment_Method'),
121
-            'Payment'     => new EE_Has_Many_Relation(),
122
-            'Transaction' => new EE_Has_Many_Relation(),
123
-            'WP_User'     => new EE_Belongs_To_Relation(),
124
-        ];
125
-        parent::__construct($timezone);
126
-    }
127
-
128
-
129
-    /**
130
-     * Gets one by the slug provided
131
-     *
132
-     * @param string $slug
133
-     * @return EE_Payment_Method|null
134
-     * @throws EE_Error
135
-     * @throws ReflectionException
136
-     */
137
-    public function get_one_by_slug($slug): ?EE_Payment_Method
138
-    {
139
-        return $slug ? $this->get_one([['PMD_slug' => (string) $slug]]) : null;
140
-    }
141
-
142
-
143
-    /**
144
-     * Gets all the acceptable scopes for payment methods.
145
-     * Keys are their names as store din the DB, and values are nice names for displaying them
146
-     *
147
-     * @return array
148
-     */
149
-    public function scopes(): array
150
-    {
151
-        return apply_filters(
152
-            'FHEE__EEM_Payment_Method__scopes',
153
-            [
154
-                EEM_Payment_Method::scope_cart  => esc_html__('Front-end Registration Page', 'event_espresso'),
155
-                EEM_Payment_Method::scope_admin => esc_html__(
156
-                    'Admin Registration Page (no online processing)',
157
-                    'event_espresso'
158
-                ),
159
-            ]
160
-        );
161
-    }
162
-
163
-
164
-    /**
165
-     * Determines if this is a valid scope
166
-     *
167
-     * @param string $scope like one of EEM_Payment_Method::instance()->scopes()
168
-     * @return boolean
169
-     */
170
-    public function is_valid_scope(string $scope): bool
171
-    {
172
-        $scopes = $this->scopes();
173
-        return isset($scopes[ $scope ]);
174
-    }
175
-
176
-
177
-    /**
178
-     * Gets all active payment methods
179
-     *
180
-     * @param string $scope one of
181
-     * @param array  $query_params
182
-     * @return EE_Payment_Method[]
183
-     * @throws EE_Error
184
-     * @throws ReflectionException
185
-     */
186
-    public function get_all_active(string $scope = '', array $query_params = []): array
187
-    {
188
-        if (! isset($query_params['order_by']) && ! isset($query_params['order'])) {
189
-            $query_params['order_by'] = ['PMD_order' => 'ASC', 'PMD_ID' => 'ASC'];
190
-        }
191
-        return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
192
-    }
193
-
194
-
195
-    /**
196
-     * Counts all active gateways in the specified scope
197
-     *
198
-     * @param string $scope one of EEM_Payment_Method::scope_*
199
-     * @param array  $query_params
200
-     * @return int
201
-     * @throws EE_Error
202
-     * @throws ReflectionException
203
-     */
204
-    public function count_active(string $scope = '', array $query_params = []): int
205
-    {
206
-        return $this->count($this->_get_query_params_for_all_active($scope, $query_params));
207
-    }
208
-
209
-
210
-    /**
211
-     * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
212
-     * argument to get all active for a given scope
213
-     *
214
-     * @param string $scope one of the constants EEM_Payment_Method::scope_*
215
-     * @param array  $query_params
216
-     * @return array
217
-     * @throws EE_Error
218
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
219
-     */
220
-    protected function _get_query_params_for_all_active(string $scope = '', array $query_params = []): array
221
-    {
222
-        if ($scope) {
223
-            if ($this->is_valid_scope($scope)) {
224
-                return array_replace_recursive([['PMD_scope' => ['LIKE', "%$scope%"]]], $query_params);
225
-            }
226
-            throw new EE_Error(
227
-                sprintf(
228
-                    esc_html__("'%s' is not a valid scope for a payment method", 'event_espresso'),
229
-                    $scope
230
-                )
231
-            );
232
-        }
233
-        $acceptable_scopes = [];
234
-        $count             = 0;
235
-        foreach ($this->scopes() as $scope_name => $desc) {
236
-            $count++;
237
-            $acceptable_scopes[ 'PMD_scope*' . $count ] = ['LIKE', '%' . $scope_name . '%'];
238
-        }
239
-        return array_replace_recursive([['OR*active_scope' => $acceptable_scopes]], $query_params);
240
-    }
241
-
242
-
243
-    /**
244
-     * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
245
-     * argument to get all active for a given scope
246
-     *
247
-     * @param string $scope one of the constants EEM_Payment_Method::scope_*
248
-     * @param array  $query_params
249
-     * @return array
250
-     * @throws EE_Error
251
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
252
-     */
253
-    public function get_query_params_for_all_active(string $scope = '', array $query_params = []): array
254
-    {
255
-        return $this->_get_query_params_for_all_active($scope, $query_params);
256
-    }
257
-
258
-
259
-    /**
260
-     * Gets one active payment method. see @get_all_active for documentation
261
-     *
262
-     * @param string $scope
263
-     * @param array  $query_params
264
-     * @return EE_Payment_Method|null
265
-     * @throws EE_Error
266
-     * @throws ReflectionException
267
-     */
268
-    public function get_one_active(string $scope = '', array $query_params = []): ?EE_Payment_Method
269
-    {
270
-        return $this->get_one($this->_get_query_params_for_all_active($scope, $query_params));
271
-    }
272
-
273
-
274
-    /**
275
-     * Gets one payment method of that type, regardless of whether it's active or not
276
-     *
277
-     * @param string $type
278
-     * @return EE_Payment_Method|null
279
-     * @throws EE_Error
280
-     * @throws ReflectionException
281
-     */
282
-    public function get_one_of_type(string $type): ?EE_Payment_Method
283
-    {
284
-        return $this->get_one([['PMD_type' => $type]]);
285
-    }
286
-
287
-
288
-    /**
289
-     * Overrides parent ot also check by the slug
290
-     *
291
-     * @param string|int|EE_Payment_Method $base_class_obj_or_id
292
-     * @param boolean                      $ensure_is_in_db
293
-     * @return EE_Payment_Method
294
-     * @throws EE_Error
295
-     * @throws ReflectionException
296
-     * @see EEM_Base::ensure_is_obj()
297
-     */
298
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
299
-    {
300
-        // first: check if it's a slug
301
-        if (is_string($base_class_obj_or_id)) {
302
-            $obj = $this->get_one_by_slug($base_class_obj_or_id);
303
-            if ($obj instanceof EE_Payment_Method) {
304
-                return $obj;
305
-            }
306
-        }
307
-        // ok so it wasn't a slug we were passed. try the usual then (ie, it's an object or an ID)
308
-        try {
309
-            return parent::ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db);
310
-        } catch (EE_Error $e) {
311
-            // handle it outside the catch
312
-        }
313
-        throw new EE_Error(
314
-            sprintf(
315
-                esc_html__("'%s' is neither a Payment Method ID, slug, nor object.", 'event_espresso'),
316
-                $base_class_obj_or_id
317
-            )
318
-        );
319
-    }
320
-
321
-
322
-    /**
323
-     * Gets the ID of this object, or if it's a string finds the object's id
324
-     * associated with that slug
325
-     *
326
-     * @param mixed $base_obj_or_id_or_slug
327
-     * @return int
328
-     * @throws EE_Error
329
-     * @throws ReflectionException
330
-     */
331
-    public function ensure_is_ID($base_obj_or_id_or_slug)
332
-    {
333
-        if (is_string($base_obj_or_id_or_slug)) {
334
-            // assume it's a slug
335
-            $base_obj_or_id_or_slug = $this->get_one_by_slug($base_obj_or_id_or_slug);
336
-        }
337
-        return parent::ensure_is_ID($base_obj_or_id_or_slug);
338
-    }
339
-
340
-
341
-    /**
342
-     * Verifies the button urls on all the passed payment methods have a valid button url.
343
-     * If not, resets them to their default.
344
-     *
345
-     * @param EE_Payment_Method[] $payment_methods if empty, defaults to all payment methods active in the cart
346
-     * @throws EE_Error
347
-     * @throws ReflectionException
348
-     */
349
-    public function verify_button_urls(array $payment_methods = [])
350
-    {
351
-        $payment_methods = $payment_methods ?: $this->get_all_active(EEM_Payment_Method::scope_cart);
352
-        foreach ($payment_methods as $payment_method) {
353
-            try {
354
-                // If there is really no button URL at all, or if the button URLs still point to decaf folder even
355
-                // though this is a caffeinated install, reset it to the default.
356
-                $current_button_url = $payment_method->button_url();
357
-                if (
358
-                    empty($current_button_url)
359
-                    || (
360
-                        strpos($current_button_url, 'decaf') !== false
361
-                        && strpos($payment_method->type_obj()->default_button_url(), 'decaf') === false
362
-                    )
363
-                ) {
364
-                    $payment_method->save(
365
-                        [
366
-                            'PMD_button_url' => $payment_method->type_obj()->default_button_url(),
367
-                        ]
368
-                    );
369
-                }
370
-            } catch (EE_Error $e) {
371
-                $payment_method->deactivate();
372
-            }
373
-        }
374
-    }
375
-
376
-
377
-    /**
378
-     * Overrides parent to not only turn wpdb results into EE_Payment_Method objects,
379
-     * but also verifies the payment method type of each is a usable object. If not,
380
-     * deactivate it, sets a notification, and deactivates it
381
-     *
382
-     * @param array $rows
383
-     * @return EE_Payment_Method[]
384
-     * @throws EE_Error
385
-     * @throws InvalidDataTypeException
386
-     * @throws ReflectionException
387
-     */
388
-    protected function _create_objects($rows = [])
389
-    {
390
-        EE_Registry::instance()->load_lib('Payment_Method_Manager');
391
-        $PMM             = EE_Payment_Method_Manager::instance();
392
-        $payment_methods = parent::_create_objects($rows);
393
-        /* @var $payment_methods EE_Payment_Method[] */
394
-        $usable_payment_methods = [];
395
-        foreach ($payment_methods as $key => $payment_method) {
396
-            // check if the payment method type exists and force recheck
397
-            $pm_type_exists = $PMM->payment_method_type_exists($payment_method->type(), true);
398
-            if ($pm_type_exists) {
399
-                $usable_payment_methods[ $key ] = $payment_method;
400
-                // some payment methods enqueue their scripts in EE_PMT_*::__construct
401
-                // which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
402
-                // its scripts). but for backwards-compat we should continue to do that
403
-                $payment_method->type_obj();
404
-            } elseif ($payment_method->active()) {
405
-                // only deactivate and notify the admin if the payment is active somewhere
406
-                $payment_method->deactivate();
407
-                $payment_method->save();
408
-                do_action(
409
-                    'AHEE__EEM_Payment_Method___create_objects_auto_deactivated_payment_method',
410
-                    $payment_method
411
-                );
412
-                new PersistentAdminNotice(
413
-                    'auto-deactivated-' . $payment_method->slug(),
414
-                    sprintf(
415
-                        esc_html__(
416
-                            'The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.',
417
-                            'event_espresso'
418
-                        ),
419
-                        $payment_method->admin_name(),
420
-                        '<br />',
421
-                        '<a href="' . admin_url('plugins.php') . '">',
422
-                        '</a>'
423
-                    ),
424
-                    true,
425
-                    'manage_options',
426
-                    'view persistent admin notice',
427
-                    false,
428
-                    'attention'
429
-                );
430
-            }
431
-        }
432
-        return $usable_payment_methods;
433
-    }
434
-
435
-
436
-    /**
437
-     * Gets all the payment methods which can be used for transaction
438
-     * (according to the relations between payment methods and events, and
439
-     * the currencies used for the transaction and their relation to payment methods)
440
-     *
441
-     * @param EE_Transaction $transaction
442
-     * @param string         $scope @see EEM_Payment_Method::get_all_for_events
443
-     * @return EE_Payment_Method[]
444
-     * @throws EE_Error
445
-     * @throws ReflectionException
446
-     */
447
-    public function get_all_for_transaction(EE_Transaction $transaction, string $scope): array
448
-    {
449
-        // give addons a chance to override what payment methods are chosen based on the transaction
450
-        return apply_filters(
451
-            'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
452
-            $this->get_all_active($scope, ['group_by' => 'PMD_type']),
453
-            $transaction,
454
-            $scope
455
-        );
456
-    }
457
-
458
-
459
-    /**
460
-     * Returns the payment method used for the last payment made for a registration.
461
-     * Note: if an offline payment method was selected on the related transaction then this will have no payment
462
-     * methods returned. It will ONLY return a payment method for a PAYMENT recorded against the registration.
463
-     *
464
-     * @param EE_Registration|int $registration_or_reg_id Either the EE_Registration object or the id for the
465
-     *                                                    registration.
466
-     * @return EE_Payment_Method|null
467
-     * @throws EE_Error
468
-     * @throws ReflectionException
469
-     */
470
-    public function get_last_used_for_registration($registration_or_reg_id): ?EE_Payment_Method
471
-    {
472
-        $registration_id = EEM_Registration::instance()->ensure_is_ID($registration_or_reg_id);
473
-
474
-        $query_params = [
475
-            0          => [
476
-                'Payment.Registration.REG_ID' => $registration_id,
477
-            ],
478
-            'order_by' => ['Payment.PAY_ID' => 'DESC'],
479
-        ];
480
-        return $this->get_one($query_params);
481
-    }
20
+	const scope_cart  = 'CART';
21
+
22
+	const scope_admin = 'ADMIN';
23
+
24
+	const scope_api   = 'API';
25
+
26
+
27
+	protected static ?EEM_Payment_Method $_instance = null;
28
+
29
+
30
+	/**
31
+	 * private constructor to prevent direct creation
32
+	 *
33
+	 * @param string|null $timezone
34
+	 * @throws EE_Error
35
+	 */
36
+	protected function __construct(?string $timezone = '')
37
+	{
38
+		$this->singular_item    = esc_html__('Payment Method', 'event_espresso');
39
+		$this->plural_item      = esc_html__('Payment Methods', 'event_espresso');
40
+		$this->_tables          = [
41
+			'Payment_Method' => new EE_Primary_Table('esp_payment_method', 'PMD_ID'),
42
+		];
43
+		$this->_fields          = [
44
+			'Payment_Method' => [
45
+				'PMD_ID'              => new EE_Primary_Key_Int_Field(
46
+					'PMD_ID',
47
+					esc_html__('ID', 'event_espresso')
48
+				),
49
+				'PMD_type'            => new EE_Plain_Text_Field(
50
+					'PMD_type',
51
+					esc_html__('Payment Method Type', 'event_espresso'),
52
+					false,
53
+					'Admin_Only'
54
+				),
55
+				'PMD_name'            => new EE_Plain_Text_Field(
56
+					'PMD_name',
57
+					esc_html__('Name', 'event_espresso'),
58
+					false
59
+				),
60
+				'PMD_desc'            => new EE_Post_Content_Field(
61
+					'PMD_desc',
62
+					esc_html__('Description', 'event_espresso'),
63
+					false,
64
+					''
65
+				),
66
+				'PMD_admin_name'      => new EE_Plain_Text_Field(
67
+					'PMD_admin_name',
68
+					esc_html__('Admin-Only Name', 'event_espresso'),
69
+					true
70
+				),
71
+				'PMD_admin_desc'      => new EE_Post_Content_Field(
72
+					'PMD_admin_desc',
73
+					esc_html__('Admin-Only Description', 'event_espresso'),
74
+					true,
75
+					''
76
+				),
77
+				'PMD_slug'            => new EE_Slug_Field(
78
+					'PMD_slug',
79
+					esc_html__('Slug', 'event_espresso'),
80
+					false
81
+				),
82
+				'PMD_order'           => new EE_Integer_Field(
83
+					'PMD_order',
84
+					esc_html__('Order', 'event_espresso'),
85
+					false,
86
+					0
87
+				),
88
+				'PMD_debug_mode'      => new EE_Boolean_Field(
89
+					'PMD_debug_mode',
90
+					esc_html__('Sandbox Mode On? (AKA: debug mode)', 'event_espresso'),
91
+					false,
92
+					false
93
+				),
94
+				'PMD_wp_user'         => new EE_WP_User_Field(
95
+					'PMD_wp_user',
96
+					esc_html__('Payment Method Creator ID', 'event_espresso'),
97
+					false
98
+				),
99
+				'PMD_open_by_default' => new EE_Boolean_Field(
100
+					'PMD_open_by_default',
101
+					esc_html__('Open by Default?', 'event_espresso'),
102
+					false,
103
+					false
104
+				),
105
+				'PMD_button_url'      => new EE_Plain_Text_Field(
106
+					'PMD_button_url',
107
+					esc_html__('Button URL', 'event_espresso'),
108
+					true,
109
+					''
110
+				),
111
+				'PMD_scope'           => new EE_Serialized_Text_Field(
112
+					'PMD_scope',
113
+					esc_html__('Usable From?', 'event_espresso'),
114
+					false,
115
+					[]// possible values currently are 'CART','ADMIN','API'
116
+				),
117
+			],
118
+		];
119
+		$this->_model_relations = [
120
+			'Currency'    => new EE_HABTM_Relation('Currency_Payment_Method'),
121
+			'Payment'     => new EE_Has_Many_Relation(),
122
+			'Transaction' => new EE_Has_Many_Relation(),
123
+			'WP_User'     => new EE_Belongs_To_Relation(),
124
+		];
125
+		parent::__construct($timezone);
126
+	}
127
+
128
+
129
+	/**
130
+	 * Gets one by the slug provided
131
+	 *
132
+	 * @param string $slug
133
+	 * @return EE_Payment_Method|null
134
+	 * @throws EE_Error
135
+	 * @throws ReflectionException
136
+	 */
137
+	public function get_one_by_slug($slug): ?EE_Payment_Method
138
+	{
139
+		return $slug ? $this->get_one([['PMD_slug' => (string) $slug]]) : null;
140
+	}
141
+
142
+
143
+	/**
144
+	 * Gets all the acceptable scopes for payment methods.
145
+	 * Keys are their names as store din the DB, and values are nice names for displaying them
146
+	 *
147
+	 * @return array
148
+	 */
149
+	public function scopes(): array
150
+	{
151
+		return apply_filters(
152
+			'FHEE__EEM_Payment_Method__scopes',
153
+			[
154
+				EEM_Payment_Method::scope_cart  => esc_html__('Front-end Registration Page', 'event_espresso'),
155
+				EEM_Payment_Method::scope_admin => esc_html__(
156
+					'Admin Registration Page (no online processing)',
157
+					'event_espresso'
158
+				),
159
+			]
160
+		);
161
+	}
162
+
163
+
164
+	/**
165
+	 * Determines if this is a valid scope
166
+	 *
167
+	 * @param string $scope like one of EEM_Payment_Method::instance()->scopes()
168
+	 * @return boolean
169
+	 */
170
+	public function is_valid_scope(string $scope): bool
171
+	{
172
+		$scopes = $this->scopes();
173
+		return isset($scopes[ $scope ]);
174
+	}
175
+
176
+
177
+	/**
178
+	 * Gets all active payment methods
179
+	 *
180
+	 * @param string $scope one of
181
+	 * @param array  $query_params
182
+	 * @return EE_Payment_Method[]
183
+	 * @throws EE_Error
184
+	 * @throws ReflectionException
185
+	 */
186
+	public function get_all_active(string $scope = '', array $query_params = []): array
187
+	{
188
+		if (! isset($query_params['order_by']) && ! isset($query_params['order'])) {
189
+			$query_params['order_by'] = ['PMD_order' => 'ASC', 'PMD_ID' => 'ASC'];
190
+		}
191
+		return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
192
+	}
193
+
194
+
195
+	/**
196
+	 * Counts all active gateways in the specified scope
197
+	 *
198
+	 * @param string $scope one of EEM_Payment_Method::scope_*
199
+	 * @param array  $query_params
200
+	 * @return int
201
+	 * @throws EE_Error
202
+	 * @throws ReflectionException
203
+	 */
204
+	public function count_active(string $scope = '', array $query_params = []): int
205
+	{
206
+		return $this->count($this->_get_query_params_for_all_active($scope, $query_params));
207
+	}
208
+
209
+
210
+	/**
211
+	 * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
212
+	 * argument to get all active for a given scope
213
+	 *
214
+	 * @param string $scope one of the constants EEM_Payment_Method::scope_*
215
+	 * @param array  $query_params
216
+	 * @return array
217
+	 * @throws EE_Error
218
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
219
+	 */
220
+	protected function _get_query_params_for_all_active(string $scope = '', array $query_params = []): array
221
+	{
222
+		if ($scope) {
223
+			if ($this->is_valid_scope($scope)) {
224
+				return array_replace_recursive([['PMD_scope' => ['LIKE', "%$scope%"]]], $query_params);
225
+			}
226
+			throw new EE_Error(
227
+				sprintf(
228
+					esc_html__("'%s' is not a valid scope for a payment method", 'event_espresso'),
229
+					$scope
230
+				)
231
+			);
232
+		}
233
+		$acceptable_scopes = [];
234
+		$count             = 0;
235
+		foreach ($this->scopes() as $scope_name => $desc) {
236
+			$count++;
237
+			$acceptable_scopes[ 'PMD_scope*' . $count ] = ['LIKE', '%' . $scope_name . '%'];
238
+		}
239
+		return array_replace_recursive([['OR*active_scope' => $acceptable_scopes]], $query_params);
240
+	}
241
+
242
+
243
+	/**
244
+	 * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
245
+	 * argument to get all active for a given scope
246
+	 *
247
+	 * @param string $scope one of the constants EEM_Payment_Method::scope_*
248
+	 * @param array  $query_params
249
+	 * @return array
250
+	 * @throws EE_Error
251
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
252
+	 */
253
+	public function get_query_params_for_all_active(string $scope = '', array $query_params = []): array
254
+	{
255
+		return $this->_get_query_params_for_all_active($scope, $query_params);
256
+	}
257
+
258
+
259
+	/**
260
+	 * Gets one active payment method. see @get_all_active for documentation
261
+	 *
262
+	 * @param string $scope
263
+	 * @param array  $query_params
264
+	 * @return EE_Payment_Method|null
265
+	 * @throws EE_Error
266
+	 * @throws ReflectionException
267
+	 */
268
+	public function get_one_active(string $scope = '', array $query_params = []): ?EE_Payment_Method
269
+	{
270
+		return $this->get_one($this->_get_query_params_for_all_active($scope, $query_params));
271
+	}
272
+
273
+
274
+	/**
275
+	 * Gets one payment method of that type, regardless of whether it's active or not
276
+	 *
277
+	 * @param string $type
278
+	 * @return EE_Payment_Method|null
279
+	 * @throws EE_Error
280
+	 * @throws ReflectionException
281
+	 */
282
+	public function get_one_of_type(string $type): ?EE_Payment_Method
283
+	{
284
+		return $this->get_one([['PMD_type' => $type]]);
285
+	}
286
+
287
+
288
+	/**
289
+	 * Overrides parent ot also check by the slug
290
+	 *
291
+	 * @param string|int|EE_Payment_Method $base_class_obj_or_id
292
+	 * @param boolean                      $ensure_is_in_db
293
+	 * @return EE_Payment_Method
294
+	 * @throws EE_Error
295
+	 * @throws ReflectionException
296
+	 * @see EEM_Base::ensure_is_obj()
297
+	 */
298
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
299
+	{
300
+		// first: check if it's a slug
301
+		if (is_string($base_class_obj_or_id)) {
302
+			$obj = $this->get_one_by_slug($base_class_obj_or_id);
303
+			if ($obj instanceof EE_Payment_Method) {
304
+				return $obj;
305
+			}
306
+		}
307
+		// ok so it wasn't a slug we were passed. try the usual then (ie, it's an object or an ID)
308
+		try {
309
+			return parent::ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db);
310
+		} catch (EE_Error $e) {
311
+			// handle it outside the catch
312
+		}
313
+		throw new EE_Error(
314
+			sprintf(
315
+				esc_html__("'%s' is neither a Payment Method ID, slug, nor object.", 'event_espresso'),
316
+				$base_class_obj_or_id
317
+			)
318
+		);
319
+	}
320
+
321
+
322
+	/**
323
+	 * Gets the ID of this object, or if it's a string finds the object's id
324
+	 * associated with that slug
325
+	 *
326
+	 * @param mixed $base_obj_or_id_or_slug
327
+	 * @return int
328
+	 * @throws EE_Error
329
+	 * @throws ReflectionException
330
+	 */
331
+	public function ensure_is_ID($base_obj_or_id_or_slug)
332
+	{
333
+		if (is_string($base_obj_or_id_or_slug)) {
334
+			// assume it's a slug
335
+			$base_obj_or_id_or_slug = $this->get_one_by_slug($base_obj_or_id_or_slug);
336
+		}
337
+		return parent::ensure_is_ID($base_obj_or_id_or_slug);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Verifies the button urls on all the passed payment methods have a valid button url.
343
+	 * If not, resets them to their default.
344
+	 *
345
+	 * @param EE_Payment_Method[] $payment_methods if empty, defaults to all payment methods active in the cart
346
+	 * @throws EE_Error
347
+	 * @throws ReflectionException
348
+	 */
349
+	public function verify_button_urls(array $payment_methods = [])
350
+	{
351
+		$payment_methods = $payment_methods ?: $this->get_all_active(EEM_Payment_Method::scope_cart);
352
+		foreach ($payment_methods as $payment_method) {
353
+			try {
354
+				// If there is really no button URL at all, or if the button URLs still point to decaf folder even
355
+				// though this is a caffeinated install, reset it to the default.
356
+				$current_button_url = $payment_method->button_url();
357
+				if (
358
+					empty($current_button_url)
359
+					|| (
360
+						strpos($current_button_url, 'decaf') !== false
361
+						&& strpos($payment_method->type_obj()->default_button_url(), 'decaf') === false
362
+					)
363
+				) {
364
+					$payment_method->save(
365
+						[
366
+							'PMD_button_url' => $payment_method->type_obj()->default_button_url(),
367
+						]
368
+					);
369
+				}
370
+			} catch (EE_Error $e) {
371
+				$payment_method->deactivate();
372
+			}
373
+		}
374
+	}
375
+
376
+
377
+	/**
378
+	 * Overrides parent to not only turn wpdb results into EE_Payment_Method objects,
379
+	 * but also verifies the payment method type of each is a usable object. If not,
380
+	 * deactivate it, sets a notification, and deactivates it
381
+	 *
382
+	 * @param array $rows
383
+	 * @return EE_Payment_Method[]
384
+	 * @throws EE_Error
385
+	 * @throws InvalidDataTypeException
386
+	 * @throws ReflectionException
387
+	 */
388
+	protected function _create_objects($rows = [])
389
+	{
390
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
391
+		$PMM             = EE_Payment_Method_Manager::instance();
392
+		$payment_methods = parent::_create_objects($rows);
393
+		/* @var $payment_methods EE_Payment_Method[] */
394
+		$usable_payment_methods = [];
395
+		foreach ($payment_methods as $key => $payment_method) {
396
+			// check if the payment method type exists and force recheck
397
+			$pm_type_exists = $PMM->payment_method_type_exists($payment_method->type(), true);
398
+			if ($pm_type_exists) {
399
+				$usable_payment_methods[ $key ] = $payment_method;
400
+				// some payment methods enqueue their scripts in EE_PMT_*::__construct
401
+				// which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
402
+				// its scripts). but for backwards-compat we should continue to do that
403
+				$payment_method->type_obj();
404
+			} elseif ($payment_method->active()) {
405
+				// only deactivate and notify the admin if the payment is active somewhere
406
+				$payment_method->deactivate();
407
+				$payment_method->save();
408
+				do_action(
409
+					'AHEE__EEM_Payment_Method___create_objects_auto_deactivated_payment_method',
410
+					$payment_method
411
+				);
412
+				new PersistentAdminNotice(
413
+					'auto-deactivated-' . $payment_method->slug(),
414
+					sprintf(
415
+						esc_html__(
416
+							'The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.',
417
+							'event_espresso'
418
+						),
419
+						$payment_method->admin_name(),
420
+						'<br />',
421
+						'<a href="' . admin_url('plugins.php') . '">',
422
+						'</a>'
423
+					),
424
+					true,
425
+					'manage_options',
426
+					'view persistent admin notice',
427
+					false,
428
+					'attention'
429
+				);
430
+			}
431
+		}
432
+		return $usable_payment_methods;
433
+	}
434
+
435
+
436
+	/**
437
+	 * Gets all the payment methods which can be used for transaction
438
+	 * (according to the relations between payment methods and events, and
439
+	 * the currencies used for the transaction and their relation to payment methods)
440
+	 *
441
+	 * @param EE_Transaction $transaction
442
+	 * @param string         $scope @see EEM_Payment_Method::get_all_for_events
443
+	 * @return EE_Payment_Method[]
444
+	 * @throws EE_Error
445
+	 * @throws ReflectionException
446
+	 */
447
+	public function get_all_for_transaction(EE_Transaction $transaction, string $scope): array
448
+	{
449
+		// give addons a chance to override what payment methods are chosen based on the transaction
450
+		return apply_filters(
451
+			'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
452
+			$this->get_all_active($scope, ['group_by' => 'PMD_type']),
453
+			$transaction,
454
+			$scope
455
+		);
456
+	}
457
+
458
+
459
+	/**
460
+	 * Returns the payment method used for the last payment made for a registration.
461
+	 * Note: if an offline payment method was selected on the related transaction then this will have no payment
462
+	 * methods returned. It will ONLY return a payment method for a PAYMENT recorded against the registration.
463
+	 *
464
+	 * @param EE_Registration|int $registration_or_reg_id Either the EE_Registration object or the id for the
465
+	 *                                                    registration.
466
+	 * @return EE_Payment_Method|null
467
+	 * @throws EE_Error
468
+	 * @throws ReflectionException
469
+	 */
470
+	public function get_last_used_for_registration($registration_or_reg_id): ?EE_Payment_Method
471
+	{
472
+		$registration_id = EEM_Registration::instance()->ensure_is_ID($registration_or_reg_id);
473
+
474
+		$query_params = [
475
+			0          => [
476
+				'Payment.Registration.REG_ID' => $registration_id,
477
+			],
478
+			'order_by' => ['Payment.PAY_ID' => 'DESC'],
479
+		];
480
+		return $this->get_one($query_params);
481
+	}
482 482
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
     public function is_valid_scope(string $scope): bool
171 171
     {
172 172
         $scopes = $this->scopes();
173
-        return isset($scopes[ $scope ]);
173
+        return isset($scopes[$scope]);
174 174
     }
175 175
 
176 176
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
      */
186 186
     public function get_all_active(string $scope = '', array $query_params = []): array
187 187
     {
188
-        if (! isset($query_params['order_by']) && ! isset($query_params['order'])) {
188
+        if ( ! isset($query_params['order_by']) && ! isset($query_params['order'])) {
189 189
             $query_params['order_by'] = ['PMD_order' => 'ASC', 'PMD_ID' => 'ASC'];
190 190
         }
191 191
         return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
         $count             = 0;
235 235
         foreach ($this->scopes() as $scope_name => $desc) {
236 236
             $count++;
237
-            $acceptable_scopes[ 'PMD_scope*' . $count ] = ['LIKE', '%' . $scope_name . '%'];
237
+            $acceptable_scopes['PMD_scope*'.$count] = ['LIKE', '%'.$scope_name.'%'];
238 238
         }
239 239
         return array_replace_recursive([['OR*active_scope' => $acceptable_scopes]], $query_params);
240 240
     }
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
             // check if the payment method type exists and force recheck
397 397
             $pm_type_exists = $PMM->payment_method_type_exists($payment_method->type(), true);
398 398
             if ($pm_type_exists) {
399
-                $usable_payment_methods[ $key ] = $payment_method;
399
+                $usable_payment_methods[$key] = $payment_method;
400 400
                 // some payment methods enqueue their scripts in EE_PMT_*::__construct
401 401
                 // which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
402 402
                 // its scripts). but for backwards-compat we should continue to do that
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
                     $payment_method
411 411
                 );
412 412
                 new PersistentAdminNotice(
413
-                    'auto-deactivated-' . $payment_method->slug(),
413
+                    'auto-deactivated-'.$payment_method->slug(),
414 414
                     sprintf(
415 415
                         esc_html__(
416 416
                             'The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.',
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
                         ),
419 419
                         $payment_method->admin_name(),
420 420
                         '<br />',
421
-                        '<a href="' . admin_url('plugins.php') . '">',
421
+                        '<a href="'.admin_url('plugins.php').'">',
422 422
                         '</a>'
423 423
                     ),
424 424
                     true,
Please login to merge, or discard this patch.
core/db_models/EEM_WP_User.model.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -12,126 +12,126 @@
 block discarded – undo
12 12
  */
13 13
 class EEM_WP_User extends EEM_Base
14 14
 {
15
-    protected static ?EEM_WP_User $_instance = null;
15
+	protected static ?EEM_WP_User $_instance = null;
16 16
 
17 17
 
18
-    /**
19
-     * @param string|null            $timezone
20
-     * @param ModelFieldFactory|null $model_field_factory
21
-     * @throws EE_Error
22
-     */
23
-    protected function __construct(?string $timezone = '', ModelFieldFactory $model_field_factory = null)
24
-    {
25
-        $this->singular_item = esc_html__('WP_User', 'event_espresso');
26
-        $this->plural_item   = esc_html__('WP_Users', 'event_espresso');
27
-        global $wpdb;
28
-        $this->_tables                                                      = [
29
-            'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
30
-        ];
31
-        $this->_fields                                                      = [
32
-            'WP_User' => [
33
-                'ID'                  => $model_field_factory->createPrimaryKeyIntField(
34
-                    'ID',
35
-                    esc_html__('WP_User ID', 'event_espresso')
36
-                ),
37
-                'user_login'          => $model_field_factory->createPlainTextField(
38
-                    'user_login',
39
-                    esc_html__('User Login', 'event_espresso'),
40
-                    false
41
-                ),
42
-                'user_pass'           => $model_field_factory->createPlainTextField(
43
-                    'user_pass',
44
-                    esc_html__('User Password', 'event_espresso'),
45
-                    false
46
-                ),
47
-                'user_nicename'       => $model_field_factory->createPlainTextField(
48
-                    'user_nicename',
49
-                    esc_html__(' User Nice Name', 'event_espresso'),
50
-                    false
51
-                ),
52
-                'user_email'          => $model_field_factory->createEmailField(
53
-                    'user_email',
54
-                    esc_html__('User Email', 'event_espresso'),
55
-                    false
56
-                ),
57
-                'user_registered'     => $model_field_factory->createDatetimeField(
58
-                    'user_registered',
59
-                    esc_html__('Date User Registered', 'event_espresso'),
60
-                    false,
61
-                    EE_Datetime_Field::now,
62
-                    $timezone
63
-                ),
64
-                'user_activation_key' => $model_field_factory->createPlainTextField(
65
-                    'user_activation_key',
66
-                    esc_html__('User Activation Key', 'event_espresso'),
67
-                    false
68
-                ),
69
-                'user_status'         => $model_field_factory->createIntegerField(
70
-                    'user_status',
71
-                    esc_html__('User Status', 'event_espresso')
72
-                ),
73
-                'display_name'        => $model_field_factory->createPlainTextField(
74
-                    'display_name',
75
-                    esc_html__('Display Name', 'event_espresso'),
76
-                    false
77
-                ),
78
-            ],
79
-        ];
80
-        $this->_model_relations                                             = [
81
-            'Attendee'       => new EE_Has_Many_Relation(),
82
-            // all models are related to the change log
83
-            // 'Change_Log'     => new EE_Has_Many_Relation(),
84
-            'Event'          => new EE_Has_Many_Relation(),
85
-            'Message'        => new EE_Has_Many_Relation(),
86
-            'Payment_Method' => new EE_Has_Many_Relation(),
87
-            'Price'          => new EE_Has_Many_Relation(),
88
-            'Price_Type'     => new EE_Has_Many_Relation(),
89
-            'Question'       => new EE_Has_Many_Relation(),
90
-            'Question_Group' => new EE_Has_Many_Relation(),
91
-            'Ticket'         => new EE_Has_Many_Relation(),
92
-            'Venue'          => new EE_Has_Many_Relation(),
93
-        ];
94
-        $this->foreign_key_aliases                                          = [
95
-            'Event.EVT_wp_user'          => 'WP_User.ID',
96
-            'Payment_Method.PMD_wp_user' => 'WP_User.ID',
97
-            'Price.PRC_wp_user'          => 'WP_User.ID',
98
-            'Price_Type.PRT_wp_user'     => 'WP_User.ID',
99
-            'Question.QST_wp_user'       => 'WP_User.ID',
100
-            'Question_Group.QSG_wp_user' => 'WP_User.ID',
101
-            'Ticket.VNU_wp_user'         => 'WP_User.ID',
102
-            'Venue.TKT_wp_user'          => 'WP_User.ID',
103
-        ];
104
-        $this->_wp_core_model                                               = true;
105
-        $this->_caps_slug                                                   = 'users';
106
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ]       = 'list';
107
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
108
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
109
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
110
-        }
111
-        // @todo: account for create_users controls whether they can create users at all
112
-        parent::__construct($timezone);
113
-    }
18
+	/**
19
+	 * @param string|null            $timezone
20
+	 * @param ModelFieldFactory|null $model_field_factory
21
+	 * @throws EE_Error
22
+	 */
23
+	protected function __construct(?string $timezone = '', ModelFieldFactory $model_field_factory = null)
24
+	{
25
+		$this->singular_item = esc_html__('WP_User', 'event_espresso');
26
+		$this->plural_item   = esc_html__('WP_Users', 'event_espresso');
27
+		global $wpdb;
28
+		$this->_tables                                                      = [
29
+			'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
30
+		];
31
+		$this->_fields                                                      = [
32
+			'WP_User' => [
33
+				'ID'                  => $model_field_factory->createPrimaryKeyIntField(
34
+					'ID',
35
+					esc_html__('WP_User ID', 'event_espresso')
36
+				),
37
+				'user_login'          => $model_field_factory->createPlainTextField(
38
+					'user_login',
39
+					esc_html__('User Login', 'event_espresso'),
40
+					false
41
+				),
42
+				'user_pass'           => $model_field_factory->createPlainTextField(
43
+					'user_pass',
44
+					esc_html__('User Password', 'event_espresso'),
45
+					false
46
+				),
47
+				'user_nicename'       => $model_field_factory->createPlainTextField(
48
+					'user_nicename',
49
+					esc_html__(' User Nice Name', 'event_espresso'),
50
+					false
51
+				),
52
+				'user_email'          => $model_field_factory->createEmailField(
53
+					'user_email',
54
+					esc_html__('User Email', 'event_espresso'),
55
+					false
56
+				),
57
+				'user_registered'     => $model_field_factory->createDatetimeField(
58
+					'user_registered',
59
+					esc_html__('Date User Registered', 'event_espresso'),
60
+					false,
61
+					EE_Datetime_Field::now,
62
+					$timezone
63
+				),
64
+				'user_activation_key' => $model_field_factory->createPlainTextField(
65
+					'user_activation_key',
66
+					esc_html__('User Activation Key', 'event_espresso'),
67
+					false
68
+				),
69
+				'user_status'         => $model_field_factory->createIntegerField(
70
+					'user_status',
71
+					esc_html__('User Status', 'event_espresso')
72
+				),
73
+				'display_name'        => $model_field_factory->createPlainTextField(
74
+					'display_name',
75
+					esc_html__('Display Name', 'event_espresso'),
76
+					false
77
+				),
78
+			],
79
+		];
80
+		$this->_model_relations                                             = [
81
+			'Attendee'       => new EE_Has_Many_Relation(),
82
+			// all models are related to the change log
83
+			// 'Change_Log'     => new EE_Has_Many_Relation(),
84
+			'Event'          => new EE_Has_Many_Relation(),
85
+			'Message'        => new EE_Has_Many_Relation(),
86
+			'Payment_Method' => new EE_Has_Many_Relation(),
87
+			'Price'          => new EE_Has_Many_Relation(),
88
+			'Price_Type'     => new EE_Has_Many_Relation(),
89
+			'Question'       => new EE_Has_Many_Relation(),
90
+			'Question_Group' => new EE_Has_Many_Relation(),
91
+			'Ticket'         => new EE_Has_Many_Relation(),
92
+			'Venue'          => new EE_Has_Many_Relation(),
93
+		];
94
+		$this->foreign_key_aliases                                          = [
95
+			'Event.EVT_wp_user'          => 'WP_User.ID',
96
+			'Payment_Method.PMD_wp_user' => 'WP_User.ID',
97
+			'Price.PRC_wp_user'          => 'WP_User.ID',
98
+			'Price_Type.PRT_wp_user'     => 'WP_User.ID',
99
+			'Question.QST_wp_user'       => 'WP_User.ID',
100
+			'Question_Group.QSG_wp_user' => 'WP_User.ID',
101
+			'Ticket.VNU_wp_user'         => 'WP_User.ID',
102
+			'Venue.TKT_wp_user'          => 'WP_User.ID',
103
+		];
104
+		$this->_wp_core_model                                               = true;
105
+		$this->_caps_slug                                                   = 'users';
106
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ]       = 'list';
107
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
108
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
109
+			$this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
110
+		}
111
+		// @todo: account for create_users controls whether they can create users at all
112
+		parent::__construct($timezone);
113
+	}
114 114
 
115 115
 
116
-    /**
117
-     * We don't need a foreign key to the WP_User model, we just need its primary key
118
-     *
119
-     * @return string
120
-     * @throws EE_Error
121
-     */
122
-    public function wp_user_field_name()
123
-    {
124
-        return $this->primary_key_name();
125
-    }
116
+	/**
117
+	 * We don't need a foreign key to the WP_User model, we just need its primary key
118
+	 *
119
+	 * @return string
120
+	 * @throws EE_Error
121
+	 */
122
+	public function wp_user_field_name()
123
+	{
124
+		return $this->primary_key_name();
125
+	}
126 126
 
127 127
 
128
-    /**
129
-     * This WP_User model IS owned, even though it doesn't have a foreign key to itself
130
-     *
131
-     * @return boolean
132
-     */
133
-    public function is_owned()
134
-    {
135
-        return true;
136
-    }
128
+	/**
129
+	 * This WP_User model IS owned, even though it doesn't have a foreign key to itself
130
+	 *
131
+	 * @return boolean
132
+	 */
133
+	public function is_owned()
134
+	{
135
+		return true;
136
+	}
137 137
 }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Datetime_Field.php 2 patches
Indentation   +759 added lines, -759 removed lines patch added patch discarded remove patch
@@ -19,763 +19,763 @@
 block discarded – undo
19 19
  */
20 20
 class EE_Datetime_Field extends EE_Model_Field_Base
21 21
 {
22
-    /**
23
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
24
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
25
-     *
26
-     * @type string unix_timestamp_regex
27
-     */
28
-    const unix_timestamp_regex = '/[0-9]{10,}/';
29
-
30
-    /**
31
-     * @type string mysql_timestamp_format
32
-     */
33
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
34
-
35
-    /**
36
-     * @type string mysql_date_format
37
-     */
38
-    const mysql_date_format = 'Y-m-d';
39
-
40
-    /**
41
-     * @type string mysql_time_format
42
-     */
43
-    const mysql_time_format = 'H:i:s';
44
-
45
-    /**
46
-     * Const for using in the default value. If the field's default is set to this,
47
-     * then we will return the time of calling `get_default_value()`, not
48
-     * just the current time at construction
49
-     */
50
-    const now = 'now';
51
-
52
-    /**
53
-     * The following properties hold the default formats for date and time.
54
-     * Defaults are set via the constructor and can be overridden on class instantiation.
55
-     * However they can also be overridden later by the set_format() method
56
-     * (and corresponding set_date_format, set_time_format methods);
57
-     */
58
-
59
-    protected string $_date_format        = '';
60
-
61
-    protected string $_time_format        = '';
62
-
63
-    protected string $_pretty_date_format = '';
64
-
65
-    protected string $_pretty_time_format = '';
66
-
67
-    protected ?DateTimeZone $_DateTimeZone       = null;
68
-
69
-    protected ?DateTimeZone $_UTC_DateTimeZone   = null;
70
-
71
-    protected ?DateTimeZone $_blog_DateTimeZone  = null;
72
-
73
-
74
-    /**
75
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
76
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
77
-     * and time returned via getters.
78
-     *
79
-     * @var mixed (null|string)
80
-     */
81
-    protected $_date_time_output;
82
-
83
-
84
-    /**
85
-     * timezone string
86
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
87
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
88
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
89
-     */
90
-    protected ?string $_timezone_string = null;
91
-
92
-
93
-    /**
94
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
95
-     * offsets for comparison purposes).
96
-     *
97
-     * @var int
98
-     */
99
-    protected int $_blog_offset = 0;
100
-
101
-
102
-    /**
103
-     * @param string      $table_column
104
-     * @param string      $nice_name
105
-     * @param bool        $nullable
106
-     * @param string|null $default_value
107
-     * @param string|null $timezone_string
108
-     * @param string|null $date_format
109
-     * @param string|null $time_format
110
-     * @param string|null $pretty_date_format
111
-     * @param string|null $pretty_time_format
112
-     * @throws InvalidArgumentException
113
-     * @throws Exception
114
-     */
115
-    public function __construct(
116
-        string $table_column,
117
-        string $nice_name,
118
-        bool $nullable,
119
-        ?string $default_value,
120
-        ?string $timezone_string = '',
121
-        ?string $date_format = '',
122
-        ?string $time_format = '',
123
-        ?string $pretty_date_format = '',
124
-        ?string $pretty_time_format = ''
125
-    ) {
126
-        $this->set_date_format($date_format);
127
-        $this->set_time_format($time_format);
128
-        $this->set_date_format($pretty_date_format, true);
129
-        $this->set_time_format($pretty_time_format, true);
130
-
131
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
132
-        $this->set_timezone($timezone_string);
133
-        $this->setSchemaType(SchemaType::STRING);
134
-        $this->setSchemaFormat(SchemaFormat::DATETIME);
135
-    }
136
-
137
-
138
-    /**
139
-     * @return DateTimeZone
140
-     * @throws Exception
141
-     */
142
-    public function get_UTC_DateTimeZone(): DateTimeZone
143
-    {
144
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
145
-            ? $this->_UTC_DateTimeZone
146
-            : $this->_create_timezone_object_from_timezone_string('UTC');
147
-    }
148
-
149
-
150
-    /**
151
-     * @return DateTimeZone
152
-     * @throws Exception
153
-     */
154
-    public function get_blog_DateTimeZone(): DateTimeZone
155
-    {
156
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
157
-            ? $this->_blog_DateTimeZone
158
-            : $this->_create_timezone_object_from_timezone_string();
159
-    }
160
-
161
-
162
-    /**
163
-     * this prepares any incoming date data and make sure it's converted to a UTC unix timestamp
164
-     *
165
-     * @param string|int|null $value value inputted for field on model object
166
-     *                               could be a string formatted date time or int unix timestamp
167
-     * @return DateTime
168
-     * @throws Exception
169
-     */
170
-    public function prepare_for_set($value)
171
-    {
172
-        return $this->_get_date_object($value);
173
-    }
174
-
175
-
176
-    /**
177
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
178
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
179
-     *
180
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
181
-     * @return string    The final assembled format string.
182
-     */
183
-    protected function _get_date_time_output(bool $pretty = false): string
184
-    {
185
-        switch ($this->_date_time_output) {
186
-            case 'time':
187
-                return $pretty
188
-                    ? $this->_pretty_time_format
189
-                    : $this->_time_format;
190
-
191
-            case 'date':
192
-                return $pretty
193
-                    ? $this->_pretty_date_format
194
-                    : $this->_date_format;
195
-
196
-            default:
197
-                return $pretty
198
-                    ? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
199
-                    : trim($this->_date_format . ' ' . $this->_time_format);
200
-        }
201
-    }
202
-
203
-
204
-    /**
205
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
206
-     * returned (using the format properties)
207
-     *
208
-     * @param string|null $what acceptable values are 'time' or 'date'.
209
-     *                          Any other value will be set but will always result
210
-     *                          in both 'date' and 'time' being returned.
211
-     * @return void
212
-     */
213
-    public function set_date_time_output(?string $what = null)
214
-    {
215
-        $this->_date_time_output = $what;
216
-    }
217
-
218
-
219
-    /**
220
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
221
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
222
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
223
-     * We also set some other properties in this method.
224
-     *
225
-     * @param string|null $timezone_string A valid timezone string as described by @link
226
-     *                                     http://www.php.net/manual/en/timezones.php
227
-     * @return void
228
-     * @throws InvalidArgumentException
229
-     * @throws InvalidDataTypeException
230
-     * @throws InvalidInterfaceException
231
-     * @throws Exception
232
-     */
233
-    public function set_timezone(?string $timezone_string = '')
234
-    {
235
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
236
-            // leave the timezone AS-IS if we already have one and
237
-            // the function arg didn't provide one
238
-            return;
239
-        }
240
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
241
-        $this->_timezone_string = ! empty($timezone_string)
242
-            ? $timezone_string
243
-            : 'UTC';
244
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
245
-    }
246
-
247
-
248
-    /**
249
-     * _create_timezone_object_from_timezone_name
250
-     *
251
-     * @access protected
252
-     * @param string|null $timezone_string
253
-     * @return DateTimeZone
254
-     * @throws InvalidArgumentException
255
-     * @throws InvalidDataTypeException
256
-     * @throws InvalidInterfaceException
257
-     * @throws Exception
258
-     */
259
-    protected function _create_timezone_object_from_timezone_string(?string $timezone_string = ''): DateTimeZone
260
-    {
261
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
262
-    }
263
-
264
-
265
-    /**
266
-     * This just returns whatever is set for the current timezone.
267
-     *
268
-     * @access public
269
-     * @return string timezone string
270
-     */
271
-    public function get_timezone(): ?string
272
-    {
273
-        return $this->_timezone_string;
274
-    }
275
-
276
-
277
-    /**
278
-     * set the $_date_format property
279
-     *
280
-     * @access public
281
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
282
-     * @param bool   $pretty Whether to set pretty format or not.
283
-     * @return void
284
-     */
285
-    public function set_date_format(string $format, bool $pretty = false)
286
-    {
287
-        if ($pretty) {
288
-            $this->_pretty_date_format = new DateFormat($format);
289
-        } else {
290
-            $this->_date_format = new DateFormat($format);
291
-        }
292
-    }
293
-
294
-
295
-    /**
296
-     * return the $_date_format property value.
297
-     *
298
-     * @param bool $pretty Whether to get pretty format or not.
299
-     * @return string
300
-     */
301
-    public function get_date_format(bool $pretty = false): string
302
-    {
303
-        return $pretty
304
-            ? $this->_pretty_date_format
305
-            : $this->_date_format;
306
-    }
307
-
308
-
309
-    /**
310
-     * set the $_time_format property
311
-     *
312
-     * @access public
313
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
314
-     * @param bool   $pretty Whether to set pretty format or not.
315
-     * @return void
316
-     */
317
-    public function set_time_format(string $format, bool $pretty = false)
318
-    {
319
-        if ($pretty) {
320
-            $this->_pretty_time_format = new TimeFormat($format);
321
-        } else {
322
-            $this->_time_format = new TimeFormat($format);
323
-        }
324
-    }
325
-
326
-
327
-    /**
328
-     * return the $_time_format property value.
329
-     *
330
-     * @param bool $pretty Whether to get pretty format or not.
331
-     * @return string
332
-     */
333
-    public function get_time_format(bool $pretty = false): string
334
-    {
335
-        return $pretty
336
-            ? $this->_pretty_time_format
337
-            : $this->_time_format;
338
-    }
339
-
340
-
341
-    /**
342
-     * set the $_pretty_date_format property
343
-     *
344
-     * @access public
345
-     * @param string|null $format a new pretty date format (corresponding to formats accepted by PHP date() function)
346
-     * @return void
347
-     */
348
-    public function set_pretty_date_format(?string $format)
349
-    {
350
-        $this->set_date_format($format, true);
351
-    }
352
-
353
-
354
-    /**
355
-     * set the $_pretty_time_format property
356
-     *
357
-     * @access public
358
-     * @param string|null $format a new pretty time format (corresponding to formats accepted by PHP date() function)
359
-     * @return void
360
-     */
361
-    public function set_pretty_time_format(?string $format)
362
-    {
363
-        $this->set_time_format($format, true);
364
-    }
365
-
366
-
367
-    /**
368
-     * Only sets the time portion of the datetime.
369
-     *
370
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
371
-     * @param DateTime        $current            current DateTime object for the datetime field
372
-     * @return DateTime
373
-     */
374
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current): DateTime
375
-    {
376
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
377
-        // Otherwise parse the string.
378
-        if ($time_to_set_string instanceof DateTime) {
379
-            $parsed = [
380
-                'hour'   => $time_to_set_string->format('H'),
381
-                'minute' => $time_to_set_string->format('i'),
382
-                'second' => $time_to_set_string->format('s'),
383
-            ];
384
-        } else {
385
-            // parse incoming string
386
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
387
-        }
388
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
389
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
390
-    }
391
-
392
-
393
-    /**
394
-     * Only sets the date portion of the datetime.
395
-     *
396
-     * @param string|DateTime $date_to_set_string like "Friday, January 8th" or a DateTime object.
397
-     * @param DateTime        $current            current DateTime object for the datetime field
398
-     * @return DateTime
399
-     */
400
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current): DateTime
401
-    {
402
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
403
-        // Otherwise parse the string.
404
-        if ($date_to_set_string instanceof DateTime) {
405
-            $parsed = [
406
-                'year'  => $date_to_set_string->format('Y'),
407
-                'month' => $date_to_set_string->format('m'),
408
-                'day'   => $date_to_set_string->format('d'),
409
-            ];
410
-        } else {
411
-            // parse incoming string
412
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
413
-        }
414
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
415
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
416
-    }
417
-
418
-
419
-    /**
420
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).
421
-     * When the datetime gets to this stage it should ALREADY be in UTC time
422
-     *
423
-     * @param int|string|DateTime|null $DateTime
424
-     * @return string formatted date time for given timezone
425
-     * @throws EE_Error
426
-     */
427
-    public function prepare_for_get($DateTime): string
428
-    {
429
-        return $this->_prepare_for_display($DateTime);
430
-    }
431
-
432
-
433
-    /**
434
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
435
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
436
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
437
-     * abbreviation to the date_string.
438
-     *
439
-     * @param mixed       $DateTime
440
-     * @param string|null $schema
441
-     * @return string
442
-     * @throws EE_Error
443
-     */
444
-    public function prepare_for_pretty_echoing($DateTime, ?string $schema = null): string
445
-    {
446
-        $schema = $schema ?: true;
447
-        return $this->_prepare_for_display($DateTime, $schema);
448
-    }
449
-
450
-
451
-    /**
452
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
453
-     * timezone).
454
-     *
455
-     * @param int|string|DateTime|null $DateTime
456
-     * @param bool|string   $schema
457
-     * @return string
458
-     * @throws EE_Error
459
-     * @throws Exception
460
-     */
461
-    protected function _prepare_for_display($DateTime, $schema = false): string
462
-    {
463
-        if (! $DateTime instanceof DateTime) {
464
-            if ($this->_nullable) {
465
-                return '';
466
-            }
467
-            if (WP_DEBUG) {
468
-                throw new EE_Error(
469
-                    sprintf(
470
-                        esc_html__(
471
-                            '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.',
472
-                            'event_espresso'
473
-                        ),
474
-                        $this->_nicename
475
-                    )
476
-                );
477
-            }
478
-            $DateTime = new DbSafeDateTime(EE_Datetime_Field::now);
479
-            EE_Error::add_error(
480
-                sprintf(
481
-                    esc_html__(
482
-                        '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.',
483
-                        'event_espresso'
484
-                    ),
485
-                    $this->_nicename
486
-                ),
487
-                __FILE__,
488
-                __FUNCTION__,
489
-                __LINE__
490
-            );
491
-        }
492
-        $format_string = $this->_get_date_time_output($schema);
493
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
494
-        if ($schema) {
495
-            $timezone_string = '';
496
-            if ($this->_display_timezone()) {
497
-                // must be explicit because schema could equal true.
498
-                if ($schema === 'no_html') {
499
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
500
-                } else {
501
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
502
-                }
503
-            }
504
-
505
-            return $DateTime->format($format_string) . $timezone_string;
506
-        }
507
-        return $DateTime->format($format_string);
508
-    }
509
-
510
-
511
-    /**
512
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
513
-     * timezone).
514
-     *
515
-     * @param mixed $datetime_value u
516
-     * @return string mysql timestamp in UTC
517
-     * @throws EE_Error
518
-     * @throws Exception
519
-     */
520
-    public function prepare_for_use_in_db($datetime_value): ?string
521
-    {
522
-        // we allow an empty value or DateTime object, but nothing else.
523
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
524
-            $datetime_value = $this->_get_date_object($datetime_value);
525
-            if (! $datetime_value instanceof DateTime) {
526
-                throw new EE_Error(
527
-                    sprintf(
528
-                        esc_html__(
529
-                            'The incoming value being prepared for setting in the database for the %1$s field must either be empty or a php DateTime object, instead of: %2$s %3$s',
530
-                            'event_espresso'
531
-                        ),
532
-                        $this->get_name(),
533
-                        '<br />',
534
-                        print_r($datetime_value, true)
535
-                    )
536
-                );
537
-            }
538
-        }
539
-
540
-        if ($datetime_value instanceof DateTime) {
541
-            if (! $datetime_value instanceof DbSafeDateTime) {
542
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543
-            }
544
-            EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
545
-            return $datetime_value->format(
546
-                EE_Datetime_Field::mysql_timestamp_format
547
-            );
548
-        }
549
-
550
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
551
-        return ! $this->_nullable
552
-            ? current_time('mysql', true)
553
-            : null;
554
-    }
555
-
556
-
557
-    /**
558
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
559
-     * allowed)
560
-     *
561
-     * @param string $datetime_string mysql timestamp in UTC
562
-     * @return  bool|DbSafeDateTime|null
563
-     * @throws EE_Error
564
-     * @throws Exception
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
-        $DateTime = empty($datetime_string)
574
-            ? new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone())
575
-            : DbSafeDateTime::createFromFormat(
576
-                EE_Datetime_Field::mysql_timestamp_format,
577
-                $datetime_string,
578
-                $this->get_UTC_DateTimeZone()
579
-            );
580
-
581
-        if (! $DateTime instanceof DbSafeDateTime) {
582
-            // if still no datetime object, then let's just use now
583
-            $DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
584
-        }
585
-        // THEN apply the field's set DateTimeZone
586
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
587
-        return $DateTime;
588
-    }
589
-
590
-
591
-    /**
592
-     * All this method does is determine if we're going to display the timezone string or not on any output.
593
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
594
-     * If so, then true.
595
-     *
596
-     * @return bool true for yes false for no
597
-     * @throws Exception
598
-     */
599
-    protected function _display_timezone(): bool
600
-    {
601
-        // first let's do a comparison of timezone strings.
602
-        // If they match then we can get out without any further calculations
603
-        $blog_string = get_option('timezone_string');
604
-        if ($blog_string === $this->_timezone_string) {
605
-            return false;
606
-        }
607
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
608
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
609
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
610
-        // now compare
611
-        return $blog_offset !== $this_offset;
612
-    }
613
-
614
-
615
-    /**
616
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
617
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
618
-     * with.
619
-     *
620
-     * @param int|string|DateTime|null $date_string This should be the incoming date string. It's assumed to be in
621
-     *                                              the format that is set on the date_field (or DateTime object)!
622
-     * @return DateTime|null
623
-     * @throws Exception
624
-     */
625
-    protected function _get_date_object($date_string)
626
-    {
627
-        // first if this is an empty date_string and nullable is allowed, just return null.
628
-        if ($this->_nullable && empty($date_string)) {
629
-            return null;
630
-        }
631
-
632
-        // if incoming date
633
-        if ($date_string instanceof DateTime) {
634
-            EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
635
-            return $date_string;
636
-        }
637
-        // if empty date_string and made it here.
638
-        // Return a datetime object for now in the given timezone.
639
-        if (empty($date_string)) {
640
-            return new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
641
-        }
642
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
643
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
644
-            try {
645
-                // This is operating under the assumption that the incoming Unix timestamp
646
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
647
-                $DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
648
-                $DateTime->setTimestamp($date_string);
649
-
650
-                return $DateTime;
651
-            } catch (Exception $e) {
652
-                // should be rare, but if things got fooled then let's just continue
653
-            }
654
-        }
655
-        // not a unix timestamp.  So we will use the set format on this object and set timezone to
656
-        // create the DateTime object.
657
-        $format = $this->_date_format . ' ' . $this->_time_format;
658
-        try {
659
-            $DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
660
-            if (! $DateTime instanceof DbSafeDateTime) {
661
-                throw new EE_Error(
662
-                    sprintf(
663
-                        esc_html__(
664
-                            '"%1$s" does not represent a valid Date Time in the format "%2$s".',
665
-                            'event_espresso'
666
-                        ),
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
-     * get_timezone_transitions
684
-     *
685
-     * @param DateTimeZone $DateTimeZone
686
-     * @param int|null     $time
687
-     * @param bool|null    $first_only
688
-     * @return array
689
-     */
690
-    public function get_timezone_transitions(
691
-        DateTimeZone $DateTimeZone,
692
-        ?int $time = null,
693
-        bool $first_only = true
694
-    ): array {
695
-        return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
696
-    }
697
-
698
-
699
-    /**
700
-     * get_timezone_offset
701
-     *
702
-     * @param DateTimeZone    $DateTimeZone
703
-     * @param int|string|null $time
704
-     * @return mixed
705
-     * @throws DomainException
706
-     */
707
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
708
-    {
709
-        return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
710
-    }
711
-
712
-
713
-    /**
714
-     * This will take an incoming timezone string and return the abbreviation for that timezone
715
-     *
716
-     * @param string|null $timezone_string
717
-     * @return string           abbreviation
718
-     * @throws Exception
719
-     */
720
-    public function get_timezone_abbrev(?string $timezone_string = ''): string
721
-    {
722
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
723
-        $dateTime        = new DateTime(EE_Datetime_Field::now, new DateTimeZone($timezone_string));
724
-        return $dateTime->format('T');
725
-    }
726
-
727
-
728
-    /**
729
-     * Overrides the parent to allow for having a dynamic "now" value
730
-     *
731
-     * @return mixed
732
-     */
733
-    public function get_default_value()
734
-    {
735
-        if ($this->_default_value === EE_Datetime_Field::now) {
736
-            return time();
737
-        }
738
-        return parent::get_default_value();
739
-    }
740
-
741
-
742
-    /**
743
-     * Gets the default datetime object from the field's default time
744
-     *
745
-     * @return DbSafeDateTime|DateTime|null
746
-     * @throws InvalidArgumentException
747
-     * @throws InvalidDataTypeException
748
-     * @throws InvalidInterfaceException
749
-     * @throws Exception
750
-     * @since 4.9.66.p
751
-     */
752
-    public function getDefaultDateTimeObj()
753
-    {
754
-        $default_raw = $this->get_default_value();
755
-        if ($default_raw instanceof DateTime) {
756
-            return $default_raw;
757
-        }
758
-        if (is_null($default_raw)) {
759
-            return null;
760
-        }
761
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($this->get_timezone());
762
-        $timezone        = new DateTimeZone($timezone_string);
763
-
764
-        // can't pass unix timestamps directly to Datetime constructor
765
-        if (is_numeric($default_raw)) {
766
-            $datetime = new DbSafeDateTime();
767
-            $datetime->setTimestamp($default_raw);
768
-            return $datetime;
769
-        }
770
-        return new DbSafeDateTime($default_raw, $timezone);
771
-    }
772
-
773
-
774
-    public function getSchemaDescription(): string
775
-    {
776
-        return sprintf(
777
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
778
-            $this->get_nicename()
779
-        );
780
-    }
22
+	/**
23
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
24
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
25
+	 *
26
+	 * @type string unix_timestamp_regex
27
+	 */
28
+	const unix_timestamp_regex = '/[0-9]{10,}/';
29
+
30
+	/**
31
+	 * @type string mysql_timestamp_format
32
+	 */
33
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
34
+
35
+	/**
36
+	 * @type string mysql_date_format
37
+	 */
38
+	const mysql_date_format = 'Y-m-d';
39
+
40
+	/**
41
+	 * @type string mysql_time_format
42
+	 */
43
+	const mysql_time_format = 'H:i:s';
44
+
45
+	/**
46
+	 * Const for using in the default value. If the field's default is set to this,
47
+	 * then we will return the time of calling `get_default_value()`, not
48
+	 * just the current time at construction
49
+	 */
50
+	const now = 'now';
51
+
52
+	/**
53
+	 * The following properties hold the default formats for date and time.
54
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
55
+	 * However they can also be overridden later by the set_format() method
56
+	 * (and corresponding set_date_format, set_time_format methods);
57
+	 */
58
+
59
+	protected string $_date_format        = '';
60
+
61
+	protected string $_time_format        = '';
62
+
63
+	protected string $_pretty_date_format = '';
64
+
65
+	protected string $_pretty_time_format = '';
66
+
67
+	protected ?DateTimeZone $_DateTimeZone       = null;
68
+
69
+	protected ?DateTimeZone $_UTC_DateTimeZone   = null;
70
+
71
+	protected ?DateTimeZone $_blog_DateTimeZone  = null;
72
+
73
+
74
+	/**
75
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
76
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
77
+	 * and time returned via getters.
78
+	 *
79
+	 * @var mixed (null|string)
80
+	 */
81
+	protected $_date_time_output;
82
+
83
+
84
+	/**
85
+	 * timezone string
86
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
87
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
88
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
89
+	 */
90
+	protected ?string $_timezone_string = null;
91
+
92
+
93
+	/**
94
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
95
+	 * offsets for comparison purposes).
96
+	 *
97
+	 * @var int
98
+	 */
99
+	protected int $_blog_offset = 0;
100
+
101
+
102
+	/**
103
+	 * @param string      $table_column
104
+	 * @param string      $nice_name
105
+	 * @param bool        $nullable
106
+	 * @param string|null $default_value
107
+	 * @param string|null $timezone_string
108
+	 * @param string|null $date_format
109
+	 * @param string|null $time_format
110
+	 * @param string|null $pretty_date_format
111
+	 * @param string|null $pretty_time_format
112
+	 * @throws InvalidArgumentException
113
+	 * @throws Exception
114
+	 */
115
+	public function __construct(
116
+		string $table_column,
117
+		string $nice_name,
118
+		bool $nullable,
119
+		?string $default_value,
120
+		?string $timezone_string = '',
121
+		?string $date_format = '',
122
+		?string $time_format = '',
123
+		?string $pretty_date_format = '',
124
+		?string $pretty_time_format = ''
125
+	) {
126
+		$this->set_date_format($date_format);
127
+		$this->set_time_format($time_format);
128
+		$this->set_date_format($pretty_date_format, true);
129
+		$this->set_time_format($pretty_time_format, true);
130
+
131
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
132
+		$this->set_timezone($timezone_string);
133
+		$this->setSchemaType(SchemaType::STRING);
134
+		$this->setSchemaFormat(SchemaFormat::DATETIME);
135
+	}
136
+
137
+
138
+	/**
139
+	 * @return DateTimeZone
140
+	 * @throws Exception
141
+	 */
142
+	public function get_UTC_DateTimeZone(): DateTimeZone
143
+	{
144
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
145
+			? $this->_UTC_DateTimeZone
146
+			: $this->_create_timezone_object_from_timezone_string('UTC');
147
+	}
148
+
149
+
150
+	/**
151
+	 * @return DateTimeZone
152
+	 * @throws Exception
153
+	 */
154
+	public function get_blog_DateTimeZone(): DateTimeZone
155
+	{
156
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
157
+			? $this->_blog_DateTimeZone
158
+			: $this->_create_timezone_object_from_timezone_string();
159
+	}
160
+
161
+
162
+	/**
163
+	 * this prepares any incoming date data and make sure it's converted to a UTC unix timestamp
164
+	 *
165
+	 * @param string|int|null $value value inputted for field on model object
166
+	 *                               could be a string formatted date time or int unix timestamp
167
+	 * @return DateTime
168
+	 * @throws Exception
169
+	 */
170
+	public function prepare_for_set($value)
171
+	{
172
+		return $this->_get_date_object($value);
173
+	}
174
+
175
+
176
+	/**
177
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
178
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
179
+	 *
180
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
181
+	 * @return string    The final assembled format string.
182
+	 */
183
+	protected function _get_date_time_output(bool $pretty = false): string
184
+	{
185
+		switch ($this->_date_time_output) {
186
+			case 'time':
187
+				return $pretty
188
+					? $this->_pretty_time_format
189
+					: $this->_time_format;
190
+
191
+			case 'date':
192
+				return $pretty
193
+					? $this->_pretty_date_format
194
+					: $this->_date_format;
195
+
196
+			default:
197
+				return $pretty
198
+					? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
199
+					: trim($this->_date_format . ' ' . $this->_time_format);
200
+		}
201
+	}
202
+
203
+
204
+	/**
205
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
206
+	 * returned (using the format properties)
207
+	 *
208
+	 * @param string|null $what acceptable values are 'time' or 'date'.
209
+	 *                          Any other value will be set but will always result
210
+	 *                          in both 'date' and 'time' being returned.
211
+	 * @return void
212
+	 */
213
+	public function set_date_time_output(?string $what = null)
214
+	{
215
+		$this->_date_time_output = $what;
216
+	}
217
+
218
+
219
+	/**
220
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
221
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
222
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
223
+	 * We also set some other properties in this method.
224
+	 *
225
+	 * @param string|null $timezone_string A valid timezone string as described by @link
226
+	 *                                     http://www.php.net/manual/en/timezones.php
227
+	 * @return void
228
+	 * @throws InvalidArgumentException
229
+	 * @throws InvalidDataTypeException
230
+	 * @throws InvalidInterfaceException
231
+	 * @throws Exception
232
+	 */
233
+	public function set_timezone(?string $timezone_string = '')
234
+	{
235
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
236
+			// leave the timezone AS-IS if we already have one and
237
+			// the function arg didn't provide one
238
+			return;
239
+		}
240
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
241
+		$this->_timezone_string = ! empty($timezone_string)
242
+			? $timezone_string
243
+			: 'UTC';
244
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
245
+	}
246
+
247
+
248
+	/**
249
+	 * _create_timezone_object_from_timezone_name
250
+	 *
251
+	 * @access protected
252
+	 * @param string|null $timezone_string
253
+	 * @return DateTimeZone
254
+	 * @throws InvalidArgumentException
255
+	 * @throws InvalidDataTypeException
256
+	 * @throws InvalidInterfaceException
257
+	 * @throws Exception
258
+	 */
259
+	protected function _create_timezone_object_from_timezone_string(?string $timezone_string = ''): DateTimeZone
260
+	{
261
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
262
+	}
263
+
264
+
265
+	/**
266
+	 * This just returns whatever is set for the current timezone.
267
+	 *
268
+	 * @access public
269
+	 * @return string timezone string
270
+	 */
271
+	public function get_timezone(): ?string
272
+	{
273
+		return $this->_timezone_string;
274
+	}
275
+
276
+
277
+	/**
278
+	 * set the $_date_format property
279
+	 *
280
+	 * @access public
281
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
282
+	 * @param bool   $pretty Whether to set pretty format or not.
283
+	 * @return void
284
+	 */
285
+	public function set_date_format(string $format, bool $pretty = false)
286
+	{
287
+		if ($pretty) {
288
+			$this->_pretty_date_format = new DateFormat($format);
289
+		} else {
290
+			$this->_date_format = new DateFormat($format);
291
+		}
292
+	}
293
+
294
+
295
+	/**
296
+	 * return the $_date_format property value.
297
+	 *
298
+	 * @param bool $pretty Whether to get pretty format or not.
299
+	 * @return string
300
+	 */
301
+	public function get_date_format(bool $pretty = false): string
302
+	{
303
+		return $pretty
304
+			? $this->_pretty_date_format
305
+			: $this->_date_format;
306
+	}
307
+
308
+
309
+	/**
310
+	 * set the $_time_format property
311
+	 *
312
+	 * @access public
313
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
314
+	 * @param bool   $pretty Whether to set pretty format or not.
315
+	 * @return void
316
+	 */
317
+	public function set_time_format(string $format, bool $pretty = false)
318
+	{
319
+		if ($pretty) {
320
+			$this->_pretty_time_format = new TimeFormat($format);
321
+		} else {
322
+			$this->_time_format = new TimeFormat($format);
323
+		}
324
+	}
325
+
326
+
327
+	/**
328
+	 * return the $_time_format property value.
329
+	 *
330
+	 * @param bool $pretty Whether to get pretty format or not.
331
+	 * @return string
332
+	 */
333
+	public function get_time_format(bool $pretty = false): string
334
+	{
335
+		return $pretty
336
+			? $this->_pretty_time_format
337
+			: $this->_time_format;
338
+	}
339
+
340
+
341
+	/**
342
+	 * set the $_pretty_date_format property
343
+	 *
344
+	 * @access public
345
+	 * @param string|null $format a new pretty date format (corresponding to formats accepted by PHP date() function)
346
+	 * @return void
347
+	 */
348
+	public function set_pretty_date_format(?string $format)
349
+	{
350
+		$this->set_date_format($format, true);
351
+	}
352
+
353
+
354
+	/**
355
+	 * set the $_pretty_time_format property
356
+	 *
357
+	 * @access public
358
+	 * @param string|null $format a new pretty time format (corresponding to formats accepted by PHP date() function)
359
+	 * @return void
360
+	 */
361
+	public function set_pretty_time_format(?string $format)
362
+	{
363
+		$this->set_time_format($format, true);
364
+	}
365
+
366
+
367
+	/**
368
+	 * Only sets the time portion of the datetime.
369
+	 *
370
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
371
+	 * @param DateTime        $current            current DateTime object for the datetime field
372
+	 * @return DateTime
373
+	 */
374
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current): DateTime
375
+	{
376
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
377
+		// Otherwise parse the string.
378
+		if ($time_to_set_string instanceof DateTime) {
379
+			$parsed = [
380
+				'hour'   => $time_to_set_string->format('H'),
381
+				'minute' => $time_to_set_string->format('i'),
382
+				'second' => $time_to_set_string->format('s'),
383
+			];
384
+		} else {
385
+			// parse incoming string
386
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
387
+		}
388
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
389
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
390
+	}
391
+
392
+
393
+	/**
394
+	 * Only sets the date portion of the datetime.
395
+	 *
396
+	 * @param string|DateTime $date_to_set_string like "Friday, January 8th" or a DateTime object.
397
+	 * @param DateTime        $current            current DateTime object for the datetime field
398
+	 * @return DateTime
399
+	 */
400
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current): DateTime
401
+	{
402
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
403
+		// Otherwise parse the string.
404
+		if ($date_to_set_string instanceof DateTime) {
405
+			$parsed = [
406
+				'year'  => $date_to_set_string->format('Y'),
407
+				'month' => $date_to_set_string->format('m'),
408
+				'day'   => $date_to_set_string->format('d'),
409
+			];
410
+		} else {
411
+			// parse incoming string
412
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
413
+		}
414
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
415
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
416
+	}
417
+
418
+
419
+	/**
420
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).
421
+	 * When the datetime gets to this stage it should ALREADY be in UTC time
422
+	 *
423
+	 * @param int|string|DateTime|null $DateTime
424
+	 * @return string formatted date time for given timezone
425
+	 * @throws EE_Error
426
+	 */
427
+	public function prepare_for_get($DateTime): string
428
+	{
429
+		return $this->_prepare_for_display($DateTime);
430
+	}
431
+
432
+
433
+	/**
434
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
435
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
436
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
437
+	 * abbreviation to the date_string.
438
+	 *
439
+	 * @param mixed       $DateTime
440
+	 * @param string|null $schema
441
+	 * @return string
442
+	 * @throws EE_Error
443
+	 */
444
+	public function prepare_for_pretty_echoing($DateTime, ?string $schema = null): string
445
+	{
446
+		$schema = $schema ?: true;
447
+		return $this->_prepare_for_display($DateTime, $schema);
448
+	}
449
+
450
+
451
+	/**
452
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
453
+	 * timezone).
454
+	 *
455
+	 * @param int|string|DateTime|null $DateTime
456
+	 * @param bool|string   $schema
457
+	 * @return string
458
+	 * @throws EE_Error
459
+	 * @throws Exception
460
+	 */
461
+	protected function _prepare_for_display($DateTime, $schema = false): string
462
+	{
463
+		if (! $DateTime instanceof DateTime) {
464
+			if ($this->_nullable) {
465
+				return '';
466
+			}
467
+			if (WP_DEBUG) {
468
+				throw new EE_Error(
469
+					sprintf(
470
+						esc_html__(
471
+							'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.',
472
+							'event_espresso'
473
+						),
474
+						$this->_nicename
475
+					)
476
+				);
477
+			}
478
+			$DateTime = new DbSafeDateTime(EE_Datetime_Field::now);
479
+			EE_Error::add_error(
480
+				sprintf(
481
+					esc_html__(
482
+						'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.',
483
+						'event_espresso'
484
+					),
485
+					$this->_nicename
486
+				),
487
+				__FILE__,
488
+				__FUNCTION__,
489
+				__LINE__
490
+			);
491
+		}
492
+		$format_string = $this->_get_date_time_output($schema);
493
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
494
+		if ($schema) {
495
+			$timezone_string = '';
496
+			if ($this->_display_timezone()) {
497
+				// must be explicit because schema could equal true.
498
+				if ($schema === 'no_html') {
499
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
500
+				} else {
501
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
502
+				}
503
+			}
504
+
505
+			return $DateTime->format($format_string) . $timezone_string;
506
+		}
507
+		return $DateTime->format($format_string);
508
+	}
509
+
510
+
511
+	/**
512
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
513
+	 * timezone).
514
+	 *
515
+	 * @param mixed $datetime_value u
516
+	 * @return string mysql timestamp in UTC
517
+	 * @throws EE_Error
518
+	 * @throws Exception
519
+	 */
520
+	public function prepare_for_use_in_db($datetime_value): ?string
521
+	{
522
+		// we allow an empty value or DateTime object, but nothing else.
523
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
524
+			$datetime_value = $this->_get_date_object($datetime_value);
525
+			if (! $datetime_value instanceof DateTime) {
526
+				throw new EE_Error(
527
+					sprintf(
528
+						esc_html__(
529
+							'The incoming value being prepared for setting in the database for the %1$s field must either be empty or a php DateTime object, instead of: %2$s %3$s',
530
+							'event_espresso'
531
+						),
532
+						$this->get_name(),
533
+						'<br />',
534
+						print_r($datetime_value, true)
535
+					)
536
+				);
537
+			}
538
+		}
539
+
540
+		if ($datetime_value instanceof DateTime) {
541
+			if (! $datetime_value instanceof DbSafeDateTime) {
542
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543
+			}
544
+			EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
545
+			return $datetime_value->format(
546
+				EE_Datetime_Field::mysql_timestamp_format
547
+			);
548
+		}
549
+
550
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
551
+		return ! $this->_nullable
552
+			? current_time('mysql', true)
553
+			: null;
554
+	}
555
+
556
+
557
+	/**
558
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
559
+	 * allowed)
560
+	 *
561
+	 * @param string $datetime_string mysql timestamp in UTC
562
+	 * @return  bool|DbSafeDateTime|null
563
+	 * @throws EE_Error
564
+	 * @throws Exception
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
+		$DateTime = empty($datetime_string)
574
+			? new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone())
575
+			: DbSafeDateTime::createFromFormat(
576
+				EE_Datetime_Field::mysql_timestamp_format,
577
+				$datetime_string,
578
+				$this->get_UTC_DateTimeZone()
579
+			);
580
+
581
+		if (! $DateTime instanceof DbSafeDateTime) {
582
+			// if still no datetime object, then let's just use now
583
+			$DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
584
+		}
585
+		// THEN apply the field's set DateTimeZone
586
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
587
+		return $DateTime;
588
+	}
589
+
590
+
591
+	/**
592
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
593
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
594
+	 * If so, then true.
595
+	 *
596
+	 * @return bool true for yes false for no
597
+	 * @throws Exception
598
+	 */
599
+	protected function _display_timezone(): bool
600
+	{
601
+		// first let's do a comparison of timezone strings.
602
+		// If they match then we can get out without any further calculations
603
+		$blog_string = get_option('timezone_string');
604
+		if ($blog_string === $this->_timezone_string) {
605
+			return false;
606
+		}
607
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
608
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
609
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
610
+		// now compare
611
+		return $blog_offset !== $this_offset;
612
+	}
613
+
614
+
615
+	/**
616
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
617
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
618
+	 * with.
619
+	 *
620
+	 * @param int|string|DateTime|null $date_string This should be the incoming date string. It's assumed to be in
621
+	 *                                              the format that is set on the date_field (or DateTime object)!
622
+	 * @return DateTime|null
623
+	 * @throws Exception
624
+	 */
625
+	protected function _get_date_object($date_string)
626
+	{
627
+		// first if this is an empty date_string and nullable is allowed, just return null.
628
+		if ($this->_nullable && empty($date_string)) {
629
+			return null;
630
+		}
631
+
632
+		// if incoming date
633
+		if ($date_string instanceof DateTime) {
634
+			EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
635
+			return $date_string;
636
+		}
637
+		// if empty date_string and made it here.
638
+		// Return a datetime object for now in the given timezone.
639
+		if (empty($date_string)) {
640
+			return new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
641
+		}
642
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
643
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
644
+			try {
645
+				// This is operating under the assumption that the incoming Unix timestamp
646
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
647
+				$DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->_DateTimeZone);
648
+				$DateTime->setTimestamp($date_string);
649
+
650
+				return $DateTime;
651
+			} catch (Exception $e) {
652
+				// should be rare, but if things got fooled then let's just continue
653
+			}
654
+		}
655
+		// not a unix timestamp.  So we will use the set format on this object and set timezone to
656
+		// create the DateTime object.
657
+		$format = $this->_date_format . ' ' . $this->_time_format;
658
+		try {
659
+			$DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
660
+			if (! $DateTime instanceof DbSafeDateTime) {
661
+				throw new EE_Error(
662
+					sprintf(
663
+						esc_html__(
664
+							'"%1$s" does not represent a valid Date Time in the format "%2$s".',
665
+							'event_espresso'
666
+						),
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
+	 * get_timezone_transitions
684
+	 *
685
+	 * @param DateTimeZone $DateTimeZone
686
+	 * @param int|null     $time
687
+	 * @param bool|null    $first_only
688
+	 * @return array
689
+	 */
690
+	public function get_timezone_transitions(
691
+		DateTimeZone $DateTimeZone,
692
+		?int $time = null,
693
+		bool $first_only = true
694
+	): array {
695
+		return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
696
+	}
697
+
698
+
699
+	/**
700
+	 * get_timezone_offset
701
+	 *
702
+	 * @param DateTimeZone    $DateTimeZone
703
+	 * @param int|string|null $time
704
+	 * @return mixed
705
+	 * @throws DomainException
706
+	 */
707
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
708
+	{
709
+		return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
710
+	}
711
+
712
+
713
+	/**
714
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
715
+	 *
716
+	 * @param string|null $timezone_string
717
+	 * @return string           abbreviation
718
+	 * @throws Exception
719
+	 */
720
+	public function get_timezone_abbrev(?string $timezone_string = ''): string
721
+	{
722
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
723
+		$dateTime        = new DateTime(EE_Datetime_Field::now, new DateTimeZone($timezone_string));
724
+		return $dateTime->format('T');
725
+	}
726
+
727
+
728
+	/**
729
+	 * Overrides the parent to allow for having a dynamic "now" value
730
+	 *
731
+	 * @return mixed
732
+	 */
733
+	public function get_default_value()
734
+	{
735
+		if ($this->_default_value === EE_Datetime_Field::now) {
736
+			return time();
737
+		}
738
+		return parent::get_default_value();
739
+	}
740
+
741
+
742
+	/**
743
+	 * Gets the default datetime object from the field's default time
744
+	 *
745
+	 * @return DbSafeDateTime|DateTime|null
746
+	 * @throws InvalidArgumentException
747
+	 * @throws InvalidDataTypeException
748
+	 * @throws InvalidInterfaceException
749
+	 * @throws Exception
750
+	 * @since 4.9.66.p
751
+	 */
752
+	public function getDefaultDateTimeObj()
753
+	{
754
+		$default_raw = $this->get_default_value();
755
+		if ($default_raw instanceof DateTime) {
756
+			return $default_raw;
757
+		}
758
+		if (is_null($default_raw)) {
759
+			return null;
760
+		}
761
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($this->get_timezone());
762
+		$timezone        = new DateTimeZone($timezone_string);
763
+
764
+		// can't pass unix timestamps directly to Datetime constructor
765
+		if (is_numeric($default_raw)) {
766
+			$datetime = new DbSafeDateTime();
767
+			$datetime->setTimestamp($default_raw);
768
+			return $datetime;
769
+		}
770
+		return new DbSafeDateTime($default_raw, $timezone);
771
+	}
772
+
773
+
774
+	public function getSchemaDescription(): string
775
+	{
776
+		return sprintf(
777
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
778
+			$this->get_nicename()
779
+		);
780
+	}
781 781
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -195,8 +195,8 @@  discard block
 block discarded – undo
195 195
 
196 196
             default:
197 197
                 return $pretty
198
-                    ? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
199
-                    : trim($this->_date_format . ' ' . $this->_time_format);
198
+                    ? trim($this->_pretty_date_format.' '.$this->_pretty_time_format)
199
+                    : trim($this->_date_format.' '.$this->_time_format);
200 200
         }
201 201
     }
202 202
 
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
      */
461 461
     protected function _prepare_for_display($DateTime, $schema = false): string
462 462
     {
463
-        if (! $DateTime instanceof DateTime) {
463
+        if ( ! $DateTime instanceof DateTime) {
464 464
             if ($this->_nullable) {
465 465
                 return '';
466 466
             }
@@ -496,13 +496,13 @@  discard block
 block discarded – undo
496 496
             if ($this->_display_timezone()) {
497 497
                 // must be explicit because schema could equal true.
498 498
                 if ($schema === 'no_html') {
499
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
499
+                    $timezone_string = ' ('.$DateTime->format('T').')';
500 500
                 } else {
501
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
501
+                    $timezone_string = ' <span class="ee_dtt_timezone_string">('.$DateTime->format('T').')</span>';
502 502
                 }
503 503
             }
504 504
 
505
-            return $DateTime->format($format_string) . $timezone_string;
505
+            return $DateTime->format($format_string).$timezone_string;
506 506
         }
507 507
         return $DateTime->format($format_string);
508 508
     }
@@ -520,9 +520,9 @@  discard block
 block discarded – undo
520 520
     public function prepare_for_use_in_db($datetime_value): ?string
521 521
     {
522 522
         // we allow an empty value or DateTime object, but nothing else.
523
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
523
+        if ( ! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
524 524
             $datetime_value = $this->_get_date_object($datetime_value);
525
-            if (! $datetime_value instanceof DateTime) {
525
+            if ( ! $datetime_value instanceof DateTime) {
526 526
                 throw new EE_Error(
527 527
                     sprintf(
528 528
                         esc_html__(
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
         }
539 539
 
540 540
         if ($datetime_value instanceof DateTime) {
541
-            if (! $datetime_value instanceof DbSafeDateTime) {
541
+            if ( ! $datetime_value instanceof DbSafeDateTime) {
542 542
                 $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543 543
             }
544 544
             EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
                 $this->get_UTC_DateTimeZone()
579 579
             );
580 580
 
581
-        if (! $DateTime instanceof DbSafeDateTime) {
581
+        if ( ! $DateTime instanceof DbSafeDateTime) {
582 582
             // if still no datetime object, then let's just use now
583 583
             $DateTime = new DbSafeDateTime(EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
584 584
         }
@@ -654,10 +654,10 @@  discard block
 block discarded – undo
654 654
         }
655 655
         // not a unix timestamp.  So we will use the set format on this object and set timezone to
656 656
         // create the DateTime object.
657
-        $format = $this->_date_format . ' ' . $this->_time_format;
657
+        $format = $this->_date_format.' '.$this->_time_format;
658 658
         try {
659 659
             $DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
660
-            if (! $DateTime instanceof DbSafeDateTime) {
660
+            if ( ! $DateTime instanceof DbSafeDateTime) {
661 661
                 throw new EE_Error(
662 662
                     sprintf(
663 663
                         esc_html__(
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6677 added lines, -6677 removed lines patch added patch discarded remove patch
@@ -39,6686 +39,6686 @@
 block discarded – undo
39 39
  */
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42
-    /**
43
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
-     * They almost always WILL NOT, but it's not necessarily a requirement.
46
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
-     *
48
-     * @var boolean
49
-     */
50
-    private $_values_already_prepared_by_model_object = 0;
51
-
52
-    /**
53
-     * when $_values_already_prepared_by_model_object equals this, we assume
54
-     * the data is just like form input that needs to have the model fields'
55
-     * prepare_for_set and prepare_for_use_in_db called on it
56
-     */
57
-    const not_prepared_by_model_object = 0;
58
-
59
-    /**
60
-     * when $_values_already_prepared_by_model_object equals this, we
61
-     * assume this value is coming from a model object and doesn't need to have
62
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
63
-     */
64
-    const prepared_by_model_object = 1;
65
-
66
-    /**
67
-     * when $_values_already_prepared_by_model_object equals this, we assume
68
-     * the values are already to be used in the database (ie no processing is done
69
-     * on them by the model's fields)
70
-     */
71
-    const prepared_for_use_in_db = 2;
72
-
73
-
74
-    protected $singular_item = 'Item';
75
-
76
-    protected $plural_item   = 'Items';
77
-
78
-    /**
79
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
-     */
81
-    protected $_tables;
82
-
83
-    /**
84
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
-     *
88
-     * @var EE_Model_Field_Base[][] $_fields
89
-     */
90
-    protected $_fields;
91
-
92
-    /**
93
-     * array of different kinds of relations
94
-     *
95
-     * @var EE_Model_Relation_Base[] $_model_relations
96
-     */
97
-    protected $_model_relations = [];
98
-
99
-    /**
100
-     * @var EE_Index[] $_indexes
101
-     */
102
-    protected $_indexes = [];
103
-
104
-    /**
105
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
106
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
-     * by setting the same columns as used in these queries in the query yourself.
108
-     *
109
-     * @var EE_Default_Where_Conditions
110
-     */
111
-    protected $_default_where_conditions_strategy;
112
-
113
-    /**
114
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
-     * This is particularly useful when you want something between 'none' and 'default'
116
-     *
117
-     * @var EE_Default_Where_Conditions
118
-     */
119
-    protected $_minimum_where_conditions_strategy;
120
-
121
-    /**
122
-     * String describing how to find the "owner" of this model's objects.
123
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
-     * But when there isn't, this indicates which related model, or transiently-related model,
125
-     * has the foreign key to the wp_users table.
126
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
-     * related to events, and events have a foreign key to wp_users.
128
-     * On EEM_Transaction, this would be 'Transaction.Event'
129
-     *
130
-     * @var string
131
-     */
132
-    protected $_model_chain_to_wp_user = '';
133
-
134
-    /**
135
-     * String describing how to find the model with a password controlling access to this model. This property has the
136
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
-     * This value is the path of models to follow to arrive at the model with the password field.
138
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
-     * model with a password that should affect reading this on the front-end.
140
-     * Eg this is an empty string for the Event model because it has a password.
141
-     * This is null for the Registration model, because its event's password has no bearing on whether
142
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
-     * should hide tickets for datetimes for events that have a password set.
145
-     *
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = [
178
-        self::caps_read       => [],
179
-        self::caps_read_admin => [],
180
-        self::caps_edit       => [],
181
-        self::caps_delete     => [],
182
-    ];
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = [];
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in the capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = [
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    ];
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = [];
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     *
298
-     * @var boolean
299
-     */
300
-    protected $_wp_core_model = false;
301
-
302
-    /**
303
-     * @var bool stores whether this model has a password field or not.
304
-     * null until initialized by hasPasswordField()
305
-     */
306
-    protected $has_password_field;
307
-
308
-    /**
309
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
-     */
311
-    protected $password_field;
312
-
313
-    /**
314
-     *    List of valid operators that can be used for querying.
315
-     * The keys are all operators we'll accept, the values are the real SQL
316
-     * operators used
317
-     *
318
-     * @var array
319
-     */
320
-    protected $_valid_operators = [
321
-        '='           => '=',
322
-        '<='          => '<=',
323
-        '<'           => '<',
324
-        '>='          => '>=',
325
-        '>'           => '>',
326
-        '!='          => '!=',
327
-        'LIKE'        => 'LIKE',
328
-        'like'        => 'LIKE',
329
-        'NOT_LIKE'    => 'NOT LIKE',
330
-        'not_like'    => 'NOT LIKE',
331
-        'NOT LIKE'    => 'NOT LIKE',
332
-        'not like'    => 'NOT LIKE',
333
-        'IN'          => 'IN',
334
-        'in'          => 'IN',
335
-        'NOT_IN'      => 'NOT IN',
336
-        'not_in'      => 'NOT IN',
337
-        'NOT IN'      => 'NOT IN',
338
-        'not in'      => 'NOT IN',
339
-        'between'     => 'BETWEEN',
340
-        'BETWEEN'     => 'BETWEEN',
341
-        'IS_NOT_NULL' => 'IS NOT NULL',
342
-        'is_not_null' => 'IS NOT NULL',
343
-        'IS NOT NULL' => 'IS NOT NULL',
344
-        'is not null' => 'IS NOT NULL',
345
-        'IS_NULL'     => 'IS NULL',
346
-        'is_null'     => 'IS NULL',
347
-        'IS NULL'     => 'IS NULL',
348
-        'is null'     => 'IS NULL',
349
-        'REGEXP'      => 'REGEXP',
350
-        'regexp'      => 'REGEXP',
351
-        'NOT_REGEXP'  => 'NOT REGEXP',
352
-        'not_regexp'  => 'NOT REGEXP',
353
-        'NOT REGEXP'  => 'NOT REGEXP',
354
-        'not regexp'  => 'NOT REGEXP',
355
-    ];
356
-
357
-    /**
358
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
-     *
360
-     * @var array
361
-     */
362
-    protected $_in_style_operators = ['IN', 'NOT IN'];
363
-
364
-    /**
365
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
-     * '12-31-2012'"
367
-     *
368
-     * @var array
369
-     */
370
-    protected $_between_style_operators = ['BETWEEN'];
371
-
372
-    /**
373
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
-
379
-    /**
380
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
-     * on a join table.
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
-
387
-    /**
388
-     * Allowed values for $query_params['order'] for ordering in queries
389
-     *
390
-     * @var array
391
-     */
392
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
-
394
-    /**
395
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
397
-     *
398
-     * @var array
399
-     */
400
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
-
402
-    /**
403
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
405
-     *
406
-     * @var array
407
-     */
408
-    private $_allowed_query_params = [
409
-        0,
410
-        'limit',
411
-        'order_by',
412
-        'group_by',
413
-        'having',
414
-        'force_join',
415
-        'order',
416
-        'on_join_limit',
417
-        'default_where_conditions',
418
-        'caps',
419
-        'extra_selects',
420
-        'exclude_protected',
421
-    ];
422
-
423
-    /**
424
-     * All the data types that can be used in $wpdb->prepare statements.
425
-     *
426
-     * @var array
427
-     */
428
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
-
430
-    /**
431
-     * @var EE_Registry $EE
432
-     */
433
-    protected $EE = null;
434
-
435
-
436
-    /**
437
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
-     *
439
-     * @var int
440
-     */
441
-    protected $_show_next_x_db_queries = 0;
442
-
443
-    /**
444
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
-     * WHERE, GROUP_BY, etc.
447
-     *
448
-     * @var CustomSelects
449
-     */
450
-    protected $_custom_selections = [];
451
-
452
-    /**
453
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
-     * caches every model object we've fetched from the DB on this request
455
-     *
456
-     * @var array
457
-     */
458
-    protected $_entity_map;
459
-
460
-    /**
461
-     * @var LoaderInterface
462
-     */
463
-    protected static $loader;
464
-
465
-    /**
466
-     * @var Mirror
467
-     */
468
-    private static $mirror;
469
-
470
-
471
-    /**
472
-     * constant used to show EEM_Base has not yet verified the db on this http request
473
-     */
474
-    const db_verified_none = 0;
475
-
476
-    /**
477
-     * constant used to show EEM_Base has verified the EE core db on this http request,
478
-     * but not the addons' dbs
479
-     */
480
-    const db_verified_core = 1;
481
-
482
-    /**
483
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
-     * the EE core db too)
485
-     */
486
-    const db_verified_addons = 2;
487
-
488
-    /**
489
-     * indicates whether an EEM_Base child has already re-verified the DB
490
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
491
-     * looking like EEM_Base::db_verified_*
492
-     *
493
-     * @var int - 0 = none, 1 = core, 2 = addons
494
-     */
495
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
496
-
497
-    /**
498
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
499
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
500
-     *        registrations for non-trashed tickets for non-trashed datetimes)
501
-     */
502
-    const default_where_conditions_all = 'all';
503
-
504
-    /**
505
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
506
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
507
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
508
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
509
-     *        models which share tables with other models, this can return data for the wrong model.
510
-     */
511
-    const default_where_conditions_this_only = 'this_model_only';
512
-
513
-    /**
514
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
515
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
516
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
517
-     */
518
-    const default_where_conditions_others_only = 'other_models_only';
519
-
520
-    /**
521
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
522
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
523
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
524
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
525
-     *        (regardless of whether those events and venues are trashed)
526
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
527
-     *        events.
528
-     */
529
-    const default_where_conditions_minimum_all = 'minimum';
530
-
531
-    /**
532
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
533
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
534
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
535
-     *        not)
536
-     */
537
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
538
-
539
-    /**
540
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
541
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
542
-     *        it's possible it will return table entries for other models. You should use
543
-     *        EEM_Base::default_where_conditions_minimum_all instead.
544
-     */
545
-    const default_where_conditions_none = 'none';
546
-
547
-
548
-    /**
549
-     * About all child constructors:
550
-     * they should define the _tables, _fields and _model_relations arrays.
551
-     * Should ALWAYS be called after child constructor.
552
-     * In order to make the child constructors to be as simple as possible, this parent constructor
553
-     * finalizes constructing all the object's attributes.
554
-     * Generally, rather than requiring a child to code
555
-     * $this->_tables = array(
556
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
557
-     *        ...);
558
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
559
-     * each EE_Table has a function to set the table's alias after the constructor, using
560
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
561
-     * do something similar.
562
-     *
563
-     * @param string|null $timezone
564
-     * @throws EE_Error
565
-     * @throws Exception
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        '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.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
599
-            }
600
-        }
601
-        /**
602
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
603
-         * EE_Register_Model_Extension
604
-         *
605
-         * @param EE_Model_Field_Base[] $_fields
606
-         */
607
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
-        $this->_invalidate_field_caches();
609
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
610
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
-                throw new EE_Error(
612
-                    sprintf(
613
-                        esc_html__(
614
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
615
-                            'event_espresso'
616
-                        ),
617
-                        $table_alias,
618
-                        implode(",", $this->_fields)
619
-                    )
620
-                );
621
-            }
622
-            foreach ($fields_for_table as $field_name => $field_obj) {
623
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
624
-                // primary key field base has a slightly different _construct_finalize
625
-                /** @var $field_obj EE_Model_Field_Base */
626
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
627
-            }
628
-        }
629
-        // everything is related to Extra_Meta
630
-        if (get_class($this) !== 'EEM_Extra_Meta') {
631
-            // make extra meta related to everything, but don't block deleting things just
632
-            // because they have related extra meta info. For now just orphan those extra meta
633
-            // in the future we should automatically delete them
634
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
635
-        }
636
-        // and change logs
637
-        if (get_class($this) !== 'EEM_Change_Log') {
638
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
639
-        }
640
-        /**
641
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
642
-         * EE_Register_Model_Extension
643
-         *
644
-         * @param EE_Model_Relation_Base[] $_model_relations
645
-         */
646
-        $this->_model_relations = (array) apply_filters(
647
-            'FHEE__' . get_class($this) . '__construct__model_relations',
648
-            $this->_model_relations
649
-        );
650
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
651
-            /** @var $relation_obj EE_Model_Relation_Base */
652
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
653
-        }
654
-        foreach ($this->_indexes as $index_name => $index_obj) {
655
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
656
-        }
657
-        $this->set_timezone($timezone);
658
-        // finalize default where condition strategy, or set default
659
-        if (! $this->_default_where_conditions_strategy) {
660
-            // nothing was set during child constructor, so set default
661
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662
-        }
663
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
664
-        if (! $this->_minimum_where_conditions_strategy) {
665
-            // nothing was set during child constructor, so set default
666
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667
-        }
668
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
669
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
670
-        // to indicate to NOT set it, set it to the logical default
671
-        if ($this->_caps_slug === null) {
672
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
673
-        }
674
-        // initialize the standard cap restriction generators if none were specified by the child constructor
675
-        if (is_array($this->_cap_restriction_generators)) {
676
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
679
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680
-                        new EE_Restriction_Generator_Protected(),
681
-                        $cap_context,
682
-                        $this
683
-                    );
684
-                }
685
-            }
686
-        }
687
-        // if there are cap restriction generators, use them to make the default cap restrictions
688
-        if (is_array($this->_cap_restriction_generators)) {
689
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
-                if (! $generator_object) {
691
-                    continue;
692
-                }
693
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
-                    throw new EE_Error(
695
-                        sprintf(
696
-                            esc_html__(
697
-                                '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.',
698
-                                'event_espresso'
699
-                            ),
700
-                            $context,
701
-                            $this->get_this_model_name()
702
-                        )
703
-                    );
704
-                }
705
-                $action = $this->cap_action_for_context($context);
706
-                if (! $generator_object->construction_finalized()) {
707
-                    $generator_object->_construct_finalize($this, $action);
708
-                }
709
-            }
710
-        }
711
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
-    }
713
-
714
-
715
-    /**
716
-     * @return LoaderInterface
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    protected static function getLoader(): LoaderInterface
722
-    {
723
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
724
-            EEM_Base::$loader = LoaderFactory::getLoader();
725
-        }
726
-        return EEM_Base::$loader;
727
-    }
728
-
729
-
730
-    /**
731
-     * @return Mirror
732
-     * @since   5.0.0.p
733
-     */
734
-    private static function getMirror(): Mirror
735
-    {
736
-        if (! EEM_Base::$mirror instanceof Mirror) {
737
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738
-        }
739
-        return EEM_Base::$mirror;
740
-    }
741
-
742
-
743
-    /**
744
-     * @param string $model_class_Name
745
-     * @param string $timezone
746
-     * @return array
747
-     * @throws ReflectionException
748
-     * @since   5.0.0.p
749
-     */
750
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
751
-    {
752
-        $arguments = [$timezone];
753
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
754
-        if (count($params) > 1) {
755
-            if ($params[1]->getName() === 'model_field_factory') {
756
-                $arguments = [
757
-                    $timezone,
758
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
759
-                ];
760
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
761
-                $arguments = [
762
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
763
-                    $timezone,
764
-                ];
765
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
766
-                $arguments = [
767
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
768
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
769
-                    $timezone,
770
-                ];
771
-            }
772
-        }
773
-        return $arguments;
774
-    }
775
-
776
-
777
-    /**
778
-     * This function is a singleton method used to instantiate the Espresso_model object
779
-     *
780
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
781
-     *                                (and any incoming timezone data that gets saved).
782
-     *                                Note this just sends the timezone info to the date time model field objects.
783
-     *                                Default is NULL
784
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
785
-     * @return static (as in the concrete child class)
786
-     * @throws EE_Error
787
-     * @throws ReflectionException
788
-     */
789
-    public static function instance($timezone = '')
790
-    {
791
-        // check if instance of Espresso_model already exists
792
-        if (! static::$_instance instanceof static) {
793
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794
-            $model     = new static(...$arguments);
795
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
796
-            static::$_instance = $model;
797
-        }
798
-        // we might have a timezone set, let set_timezone decide what to do with it
799
-        if ($timezone) {
800
-            static::$_instance->set_timezone($timezone);
801
-        }
802
-        // Espresso_model object
803
-        return static::$_instance;
804
-    }
805
-
806
-
807
-    /**
808
-     * resets the model and returns it
809
-     *
810
-     * @param string|null $timezone
811
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
812
-     * all its properties reset; if it wasn't instantiated, returns null)
813
-     * @throws EE_Error
814
-     * @throws ReflectionException
815
-     * @throws InvalidArgumentException
816
-     * @throws InvalidDataTypeException
817
-     * @throws InvalidInterfaceException
818
-     */
819
-    public static function reset($timezone = '')
820
-    {
821
-        if (! static::$_instance instanceof EEM_Base) {
822
-            return null;
823
-        }
824
-        // Let's NOT swap out the current instance for a new one
825
-        // because if someone has a reference to it, we can't remove their reference.
826
-        // It's best to keep using the same reference but change the original object instead,
827
-        // so reset all its properties to their original values as defined in the class.
828
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
829
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830
-            // don't set instance to null like it was originally,
831
-            // but it's static anyways, and we're ignoring static properties (for now at least)
832
-            if (! isset($static_properties[ $property ])) {
833
-                static::$_instance->{$property} = $value;
834
-            }
835
-        }
836
-        // and then directly call its constructor again, like we would if we were creating a new one
837
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
838
-        static::$_instance->__construct(...$arguments);
839
-        return self::instance();
840
-    }
841
-
842
-
843
-    /**
844
-     * Used to set the $_model_query_blog_id static property.
845
-     *
846
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
847
-     *                      value for get_current_blog_id() will be used.
848
-     */
849
-    public static function set_model_query_blog_id($blog_id = 0)
850
-    {
851
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
852
-            ? (int) $blog_id
853
-            : get_current_blog_id();
854
-    }
855
-
856
-
857
-    /**
858
-     * Returns whatever is set as the internal $model_query_blog_id.
859
-     *
860
-     * @return int
861
-     */
862
-    public static function get_model_query_blog_id()
863
-    {
864
-        return EEM_Base::$_model_query_blog_id;
865
-    }
866
-
867
-
868
-    /**
869
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
870
-     *
871
-     * @param boolean $translated return localized strings or JUST the array.
872
-     * @return array
873
-     * @throws EE_Error
874
-     * @throws InvalidArgumentException
875
-     * @throws InvalidDataTypeException
876
-     * @throws InvalidInterfaceException
877
-     * @throws ReflectionException
878
-     */
879
-    public function status_array($translated = false)
880
-    {
881
-        if (! array_key_exists('Status', $this->_model_relations)) {
882
-            return [];
883
-        }
884
-        $model_name   = $this->get_this_model_name();
885
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
886
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887
-        $status_array = [];
888
-        foreach ($stati as $status) {
889
-            $status_array[ $status->ID() ] = $status->get('STS_code');
890
-        }
891
-        return $translated
892
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
893
-            : $status_array;
894
-    }
895
-
896
-
897
-    /**
898
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
899
-     *
900
-     * @param array $query_params             @see
901
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     *                                        or if you have the development copy of EE you can view this at the path:
903
-     *                                        /docs/G--Model-System/model-query-params.md
904
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
905
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
906
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
907
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
908
-     *                                        EEM_Transaction::instance()->get_all( array( array(
909
-     *                                        'OR'=>array(
910
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
911
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
912
-     *                                        )
913
-     *                                        ),
914
-     *                                        'limit'=>10,
915
-     *                                        'group_by'=>'TXN_ID'
916
-     *                                        ));
917
-     *                                        get all the answers to the question titled "shirt size" for event with id
918
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
919
-     *                                        'Question.QST_display_text'=>'shirt size',
920
-     *                                        'Registration.Event.EVT_ID'=>12
921
-     *                                        ),
922
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
923
-     *                                        ));
924
-     * @throws EE_Error
925
-     * @throws ReflectionException
926
-     */
927
-    public function get_all($query_params = [])
928
-    {
929
-        if (
930
-            isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
936
-    }
937
-
938
-
939
-    /**
940
-     * Modifies the query parameters so we only get back model objects
941
-     * that "belong" to the current user
942
-     *
943
-     * @param array $query_params @see
944
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
-     * @return array @see
946
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
947
-     * @throws ReflectionException
948
-     * @throws ReflectionException
949
-     */
950
-    public function alter_query_params_to_only_include_mine($query_params = [])
951
-    {
952
-        $wp_user_field_name = $this->wp_user_field_name();
953
-        if ($wp_user_field_name) {
954
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
955
-        }
956
-        return $query_params;
957
-    }
958
-
959
-
960
-    /**
961
-     * Returns the name of the field's name that points to the WP_User table
962
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
963
-     * foreign key to the WP_User table)
964
-     *
965
-     * @return string|boolean string on success, boolean false when there is no
966
-     * foreign key to the WP_User table
967
-     * @throws ReflectionException
968
-     * @throws ReflectionException
969
-     */
970
-    public function wp_user_field_name()
971
-    {
972
-        try {
973
-            if (! empty($this->_model_chain_to_wp_user)) {
974
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975
-                $last_model_name              = end($models_to_follow_to_wp_users);
976
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
978
-            } else {
979
-                $model_with_fk_to_wp_users = $this;
980
-                $model_chain_to_wp_user    = '';
981
-            }
982
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
984
-        } catch (EE_Error $e) {
985
-            return false;
986
-        }
987
-    }
988
-
989
-
990
-    /**
991
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
992
-     * (or transiently-related model) has a foreign key to the wp_users table;
993
-     * useful for finding if model objects of this type are 'owned' by the current user.
994
-     * This is an empty string when the foreign key is on this model and when it isn't,
995
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
996
-     * (or transiently-related model)
997
-     *
998
-     * @return string
999
-     */
1000
-    public function model_chain_to_wp_user()
1001
-    {
1002
-        return $this->_model_chain_to_wp_user;
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1008
-     * like how registrations don't have a foreign key to wp_users, but the
1009
-     * events they are for are), or is unrelated to wp users.
1010
-     * generally available
1011
-     *
1012
-     * @return boolean
1013
-     */
1014
-    public function is_owned()
1015
-    {
1016
-        if ($this->model_chain_to_wp_user()) {
1017
-            return true;
1018
-        }
1019
-        try {
1020
-            $this->get_foreign_key_to('WP_User');
1021
-            return true;
1022
-        } catch (EE_Error $e) {
1023
-            return false;
1024
-        }
1025
-    }
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      @see
1034
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws EE_Error
1046
-     * @throws InvalidArgumentException
1047
-     * @throws ReflectionException
1048
-     */
1049
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1050
-    {
1051
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1052
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions       = $columns_to_select === null
1054
-            ? $this->_construct_default_select_sql($model_query_info)
1055
-            : '';
1056
-        if ($this->_custom_selections instanceof CustomSelects) {
1057
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058
-            $select_expressions .= $select_expressions
1059
-                ? ', ' . $custom_expressions
1060
-                : $custom_expressions;
1061
-        }
1062
-
1063
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1064
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1070
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1071
-     * method of including extra select information.
1072
-     *
1073
-     * @param array             $query_params
1074
-     * @param null|array|string $columns_to_select
1075
-     * @return null|CustomSelects
1076
-     * @throws InvalidArgumentException
1077
-     */
1078
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079
-    {
1080
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081
-            return null;
1082
-        }
1083
-        $selects = $query_params['extra_selects'] ?? $columns_to_select;
1084
-        $selects = is_string($selects)
1085
-            ? explode(',', $selects)
1086
-            : $selects;
1087
-        return new CustomSelects($selects);
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1093
-     * but you can use the model query params to more easily
1094
-     * take care of joins, field preparation etc.
1095
-     *
1096
-     * @param array  $query_params      @see
1097
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1098
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1099
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1101
-     *                                  override this and set the select to "*", or a specific column name, like
1102
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1103
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1104
-     *                                  the aliases used to refer to this selection, and values are to be
1105
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1106
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1107
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1108
-     * @throws EE_Error
1109
-     * @throws ReflectionException
1110
-     */
1111
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1112
-    {
1113
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * For creating a custom select statement
1119
-     *
1120
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1121
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1122
-     *                                 SQL, and 1=>is the datatype
1123
-     * @return string
1124
-     * @throws EE_Error
1125
-     */
1126
-    private function _construct_select_from_input($columns_to_select)
1127
-    {
1128
-        if (is_array($columns_to_select)) {
1129
-            $select_sql_array = [];
1130
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
-                    throw new EE_Error(
1133
-                        sprintf(
1134
-                            esc_html__(
1135
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1136
-                                'event_espresso'
1137
-                            ),
1138
-                            $selection_and_datatype,
1139
-                            $alias
1140
-                        )
1141
-                    );
1142
-                }
1143
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144
-                    throw new EE_Error(
1145
-                        sprintf(
1146
-                            esc_html__(
1147
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1148
-                                'event_espresso'
1149
-                            ),
1150
-                            $selection_and_datatype[1],
1151
-                            $selection_and_datatype[0],
1152
-                            $alias,
1153
-                            implode(', ', $this->_valid_wpdb_data_types)
1154
-                        )
1155
-                    );
1156
-                }
1157
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1158
-            }
1159
-            $columns_to_select_string = implode(', ', $select_sql_array);
1160
-        } else {
1161
-            $columns_to_select_string = $columns_to_select;
1162
-        }
1163
-        return $columns_to_select_string;
1164
-    }
1165
-
1166
-
1167
-    /**
1168
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1169
-     *
1170
-     * @return string
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function primary_key_name()
1174
-    {
1175
-        return $this->get_primary_key_field()->get_name();
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1181
-     * If there is no primary key on this model, $id is treated as primary key string
1182
-     *
1183
-     * @param mixed $id int or string, depending on the type of the model's primary key
1184
-     * @return EE_Base_Class|mixed|null
1185
-     * @throws EE_Error
1186
-     * @throws ReflectionException
1187
-     */
1188
-    public function get_one_by_ID($id)
1189
-    {
1190
-        // since entities with no ID can still have properties, we need to check the cache for them
1191
-        $cached_value = $this->get_from_entity_map($id);
1192
-        if ($cached_value) {
1193
-            return $cached_value;
1194
-        }
1195
-        // but if no cahced property AND no id is passed, just return null
1196
-        if (empty($id)) {
1197
-            return null;
1198
-        }
1199
-        $model_object = $this->get_one(
1200
-            $this->alter_query_params_to_restrict_by_ID(
1201
-                $id,
1202
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203
-            )
1204
-        );
1205
-        $className    = $this->_get_class_name();
1206
-        if ($model_object instanceof $className) {
1207
-            // make sure valid objects get added to the entity map
1208
-            // so that the next call to this method doesn't trigger another trip to the db
1209
-            $this->add_to_entity_map($model_object);
1210
-        }
1211
-        return $model_object;
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Alters query parameters to only get items with this ID are returned.
1217
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1218
-     * or could just be a simple primary key ID
1219
-     *
1220
-     * @param int   $id
1221
-     * @param array $query_params
1222
-     * @return array of normal query params, @see
1223
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1224
-     * @throws EE_Error
1225
-     */
1226
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227
-    {
1228
-        if (! isset($query_params[0])) {
1229
-            $query_params[0] = [];
1230
-        }
1231
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1232
-        if ($conditions_from_id === null) {
1233
-            $query_params[0][ $this->primary_key_name() ] = $id;
1234
-        } else {
1235
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1236
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1237
-        }
1238
-        return $query_params;
1239
-    }
1240
-
1241
-
1242
-    /**
1243
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1244
-     * array. If no item is found, null is returned.
1245
-     *
1246
-     * @param array $query_params like EEM_Base's $query_params variable.
1247
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1248
-     * @throws EE_Error
1249
-     * @throws ReflectionException
1250
-     */
1251
-    public function get_one($query_params = [])
1252
-    {
1253
-        if (! is_array($query_params)) {
1254
-            EE_Error::doing_it_wrong(
1255
-                'EEM_Base::get_one',
1256
-                sprintf(
1257
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1258
-                    gettype($query_params)
1259
-                ),
1260
-                '4.6.0'
1261
-            );
1262
-            $query_params = [];
1263
-        }
1264
-        $query_params['limit'] = 1;
1265
-        $items                 = $this->get_all($query_params);
1266
-        if (empty($items)) {
1267
-            return null;
1268
-        }
1269
-        return array_shift($items);
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Returns the next x number of items in sequence from the given value as
1275
-     * found in the database matching the given query conditions.
1276
-     *
1277
-     * @param mixed $current_field_value    Value used for the reference point.
1278
-     * @param null  $field_to_order_by      What field is used for the
1279
-     *                                      reference point.
1280
-     * @param int   $limit                  How many to return.
1281
-     * @param array $query_params           Extra conditions on the query.
1282
-     * @param null  $columns_to_select      If left null, then an array of
1283
-     *                                      EE_Base_Class objects is returned,
1284
-     *                                      otherwise you can indicate just the
1285
-     *                                      columns you want returned.
1286
-     * @return EE_Base_Class[]|array
1287
-     * @throws EE_Error
1288
-     * @throws ReflectionException
1289
-     */
1290
-    public function next_x(
1291
-        $current_field_value,
1292
-        $field_to_order_by = null,
1293
-        $limit = 1,
1294
-        $query_params = [],
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        return $this->_get_consecutive(
1298
-            $current_field_value,
1299
-            '>',
1300
-            $field_to_order_by,
1301
-            $limit,
1302
-            $query_params,
1303
-            $columns_to_select
1304
-        );
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * Returns the previous x number of items in sequence from the given value
1310
-     * as found in the database matching the given query conditions.
1311
-     *
1312
-     * @param mixed $current_field_value    Value used for the reference point.
1313
-     * @param null  $field_to_order_by      What field is used for the
1314
-     *                                      reference point.
1315
-     * @param int   $limit                  How many to return.
1316
-     * @param array $query_params           Extra conditions on the query.
1317
-     * @param null  $columns_to_select      If left null, then an array of
1318
-     *                                      EE_Base_Class objects is returned,
1319
-     *                                      otherwise you can indicate just the
1320
-     *                                      columns you want returned.
1321
-     * @return EE_Base_Class[]|array
1322
-     * @throws EE_Error
1323
-     * @throws ReflectionException
1324
-     */
1325
-    public function previous_x(
1326
-        $current_field_value,
1327
-        $field_to_order_by = null,
1328
-        $limit = 1,
1329
-        $query_params = [],
1330
-        $columns_to_select = null
1331
-    ) {
1332
-        return $this->_get_consecutive(
1333
-            $current_field_value,
1334
-            '<',
1335
-            $field_to_order_by,
1336
-            $limit,
1337
-            $query_params,
1338
-            $columns_to_select
1339
-        );
1340
-    }
1341
-
1342
-
1343
-    /**
1344
-     * Returns the next item in sequence from the given value as found in the
1345
-     * database matching the given query conditions.
1346
-     *
1347
-     * @param mixed $current_field_value    Value used for the reference point.
1348
-     * @param null  $field_to_order_by      What field is used for the
1349
-     *                                      reference point.
1350
-     * @param array $query_params           Extra conditions on the query.
1351
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1352
-     *                                      object is returned, otherwise you
1353
-     *                                      can indicate just the columns you
1354
-     *                                      want and a single array indexed by
1355
-     *                                      the columns will be returned.
1356
-     * @return EE_Base_Class|null|array()
1357
-     * @throws EE_Error
1358
-     * @throws ReflectionException
1359
-     */
1360
-    public function next(
1361
-        $current_field_value,
1362
-        $field_to_order_by = null,
1363
-        $query_params = [],
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        $results = $this->_get_consecutive(
1367
-            $current_field_value,
1368
-            '>',
1369
-            $field_to_order_by,
1370
-            1,
1371
-            $query_params,
1372
-            $columns_to_select
1373
-        );
1374
-        return empty($results)
1375
-            ? null
1376
-            : reset($results);
1377
-    }
1378
-
1379
-
1380
-    /**
1381
-     * Returns the previous item in sequence from the given value as found in
1382
-     * the database matching the given query conditions.
1383
-     *
1384
-     * @param mixed $current_field_value    Value used for the reference point.
1385
-     * @param null  $field_to_order_by      What field is used for the
1386
-     *                                      reference point.
1387
-     * @param array $query_params           Extra conditions on the query.
1388
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
-     *                                      object is returned, otherwise you
1390
-     *                                      can indicate just the columns you
1391
-     *                                      want and a single array indexed by
1392
-     *                                      the columns will be returned.
1393
-     * @return EE_Base_Class|null|array()
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function previous(
1398
-        $current_field_value,
1399
-        $field_to_order_by = null,
1400
-        $query_params = [],
1401
-        $columns_to_select = null
1402
-    ) {
1403
-        $results = $this->_get_consecutive(
1404
-            $current_field_value,
1405
-            '<',
1406
-            $field_to_order_by,
1407
-            1,
1408
-            $query_params,
1409
-            $columns_to_select
1410
-        );
1411
-        return empty($results)
1412
-            ? null
1413
-            : reset($results);
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Returns the a consecutive number of items in sequence from the given
1419
-     * value as found in the database matching the given query conditions.
1420
-     *
1421
-     * @param mixed  $current_field_value   Value used for the reference point.
1422
-     * @param string $operand               What operand is used for the sequence.
1423
-     * @param string $field_to_order_by     What field is used for the reference point.
1424
-     * @param int    $limit                 How many to return.
1425
-     * @param array  $query_params          Extra conditions on the query.
1426
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1427
-     *                                      otherwise you can indicate just the columns you want returned.
1428
-     * @return EE_Base_Class[]|array
1429
-     * @throws EE_Error
1430
-     * @throws ReflectionException
1431
-     */
1432
-    protected function _get_consecutive(
1433
-        $current_field_value,
1434
-        $operand = '>',
1435
-        $field_to_order_by = null,
1436
-        $limit = 1,
1437
-        $query_params = [],
1438
-        $columns_to_select = null
1439
-    ) {
1440
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1441
-        if (empty($field_to_order_by)) {
1442
-            if ($this->has_primary_key_field()) {
1443
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1444
-            } else {
1445
-                if (defined('WP_DEBUG') && WP_DEBUG) {
1446
-                    throw new EE_Error(
1447
-                        esc_html__(
1448
-                            '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).',
1449
-                            'event_espresso'
1450
-                        )
1451
-                    );
1452
-                }
1453
-                EE_Error::add_error(
1454
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1455
-                    __FILE__,
1456
-                    __FUNCTION__,
1457
-                    __LINE__
1458
-                );
1459
-                return [];
1460
-            }
1461
-        }
1462
-        if (! is_array($query_params)) {
1463
-            EE_Error::doing_it_wrong(
1464
-                'EEM_Base::_get_consecutive',
1465
-                sprintf(
1466
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1467
-                    gettype($query_params)
1468
-                ),
1469
-                '4.6.0'
1470
-            );
1471
-            $query_params = [];
1472
-        }
1473
-        // let's add the where query param for consecutive look up.
1474
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1475
-        $query_params['limit']                 = $limit;
1476
-        // set direction
1477
-        $incoming_orderby         = isset($query_params['order_by'])
1478
-            ? (array) $query_params['order_by']
1479
-            : [];
1480
-        $query_params['order_by'] = $operand === '>'
1481
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1482
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1483
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1484
-        if (empty($columns_to_select)) {
1485
-            return $this->get_all($query_params);
1486
-        }
1487
-        // getting just the fields
1488
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1489
-    }
1490
-
1491
-
1492
-    /**
1493
-     * This sets the _timezone property after model object has been instantiated.
1494
-     *
1495
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1496
-     * @throws Exception
1497
-     */
1498
-    public function set_timezone(?string $timezone = '')
1499
-    {
1500
-        if (! $timezone) {
1501
-            return;
1502
-        }
1503
-        $this->_timezone = $timezone;
1504
-        // note we need to loop through relations and set the timezone on those objects as well.
1505
-        foreach ($this->_model_relations as $relation) {
1506
-            $relation->set_timezone($timezone);
1507
-        }
1508
-        // and finally we do the same for any datetime fields
1509
-        foreach ($this->_fields as $field) {
1510
-            if ($field instanceof EE_Datetime_Field) {
1511
-                $field->set_timezone($timezone);
1512
-            }
1513
-        }
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * This just returns whatever is set for the current timezone.
1519
-     *
1520
-     * @access public
1521
-     * @return string
1522
-     * @throws Exception
1523
-     */
1524
-    public function get_timezone()
1525
-    {
1526
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1527
-        if (empty($this->_timezone)) {
1528
-            foreach ($this->_fields as $field) {
1529
-                if ($field instanceof EE_Datetime_Field) {
1530
-                    $this->set_timezone($field->get_timezone());
1531
-                    break;
1532
-                }
1533
-            }
1534
-        }
1535
-        // if timezone STILL empty then return the default timezone for the site.
1536
-        if (empty($this->_timezone)) {
1537
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1538
-        }
1539
-        return $this->_timezone;
1540
-    }
1541
-
1542
-
1543
-    /**
1544
-     * This returns the date formats set for the given field name and also ensures that
1545
-     * $this->_timezone property is set correctly.
1546
-     *
1547
-     * @param string $field_name The name of the field the formats are being retrieved for.
1548
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1549
-     * @return array formats in an array with the date format first, and the time format last.
1550
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1551
-     * @since 4.6.x
1552
-     */
1553
-    public function get_formats_for($field_name, $pretty = false)
1554
-    {
1555
-        $field_settings = $this->field_settings_for($field_name);
1556
-        // if not a valid EE_Datetime_Field then throw error
1557
-        if (! $field_settings instanceof EE_Datetime_Field) {
1558
-            throw new EE_Error(
1559
-                sprintf(
1560
-                    esc_html__(
1561
-                        '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.',
1562
-                        'event_espresso'
1563
-                    ),
1564
-                    $field_name
1565
-                )
1566
-            );
1567
-        }
1568
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1569
-        // the field.
1570
-        $this->_timezone = $field_settings->get_timezone();
1571
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1572
-    }
1573
-
1574
-
1575
-    /**
1576
-     * This returns the current time in a format setup for a query on this model.
1577
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1578
-     * it will return:
1579
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1580
-     *  NOW
1581
-     *  - or a unix timestamp (equivalent to time())
1582
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1583
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1584
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1585
-     *
1586
-     * @param string $field_name       The field the current time is needed for.
1587
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1588
-     *                                 formatted string matching the set format for the field in the set timezone will
1589
-     *                                 be returned.
1590
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1591
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1592
-     *                                 exception is triggered.
1593
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1594
-     * @throws Exception
1595
-     * @since 4.6.x
1596
-     */
1597
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1598
-    {
1599
-        $formats  = $this->get_formats_for($field_name);
1600
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1601
-        if ($timestamp) {
1602
-            return $DateTime->format('U');
1603
-        }
1604
-        // not returning timestamp, so return formatted string in timezone.
1605
-        switch ($what) {
1606
-            case 'time':
1607
-                return $DateTime->format($formats[1]);
1608
-            case 'date':
1609
-                return $DateTime->format($formats[0]);
1610
-            default:
1611
-                return $DateTime->format(implode(' ', $formats));
1612
-        }
1613
-    }
1614
-
1615
-
1616
-    /**
1617
-     * This receives a time string for a given field and ensures
1618
-     * that it is set up to match what the internal settings for the model are.
1619
-     * Returns a DateTime object.
1620
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1621
-     * (functionally the equivalent of UTC+0).
1622
-     * So when you send it in, whatever timezone string you include is ignored.
1623
-     *
1624
-     * @param string      $field_name      The field being setup.
1625
-     * @param string      $timestring      The date time string being used.
1626
-     * @param string      $incoming_format The format for the time string.
1627
-     * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1628
-     *                                     the blog.  If this is not the case, then it can be specified here.  If
1629
-     *                                     incoming format is
1630
-     *                                     'U', this is ignored.
1631
-     * @return DbSafeDateTime
1632
-     * @throws EE_Error
1633
-     * @throws Exception
1634
-     */
1635
-    public function convert_datetime_for_query(
1636
-        string $field_name,
1637
-        string $timestring,
1638
-        string $incoming_format,
1639
-        ?string $timezone_string = ''
1640
-    ): DbSafeDateTime {
1641
-        // just using this to ensure the timezone is set correctly internally
1642
-        $this->get_formats_for($field_name);
1643
-        // load EEH_DTT_Helper
1644
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647
-        return DbSafeDateTime::createFromDateTime($incomingDateTime);
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1653
-     *
1654
-     * @return EE_Table_Base[]
1655
-     */
1656
-    public function get_tables()
1657
-    {
1658
-        return $this->_tables;
1659
-    }
1660
-
1661
-
1662
-    /**
1663
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1664
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1665
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1666
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1667
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1668
-     * model object with EVT_ID = 1
1669
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1670
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1671
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1672
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1673
-     * are not specified)
1674
-     *
1675
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1676
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1677
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1678
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1679
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1680
-     *                                         ID=34, we'd use this method as follows:
1681
-     *                                         EEM_Transaction::instance()->update(
1682
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1683
-     *                                         array(array('TXN_ID'=>34)));
1684
-     * @param array   $query_params            @see
1685
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1686
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1687
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1688
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1689
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1690
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1691
-     *                                         TRUE, it is assumed that you've already called
1692
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1693
-     *                                         malicious javascript. However, if
1694
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1695
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1696
-     *                                         and every other field, before insertion. We provide this parameter
1697
-     *                                         because model objects perform their prepare_for_set function on all
1698
-     *                                         their values, and so don't need to be called again (and in many cases,
1699
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1700
-     *                                         prepare_for_set method...)
1701
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1702
-     *                                         in this model's entity map according to $fields_n_values that match
1703
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1704
-     *                                         by setting this to FALSE, but be aware that model objects being used
1705
-     *                                         could get out-of-sync with the database
1706
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1707
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1708
-     *                                         bad)
1709
-     * @throws EE_Error
1710
-     * @throws ReflectionException
1711
-     */
1712
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713
-    {
1714
-        if (! is_array($query_params)) {
1715
-            EE_Error::doing_it_wrong(
1716
-                'EEM_Base::update',
1717
-                sprintf(
1718
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1719
-                    gettype($query_params)
1720
-                ),
1721
-                '4.6.0'
1722
-            );
1723
-            $query_params = [];
1724
-        }
1725
-        /**
1726
-         * Action called before a model update call has been made.
1727
-         *
1728
-         * @param EEM_Base $model
1729
-         * @param array    $fields_n_values the updated fields and their new values
1730
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1731
-         */
1732
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1733
-        /**
1734
-         * Filters the fields about to be updated given the query parameters. You can provide the
1735
-         * $query_params to $this->get_all() to find exactly which records will be updated
1736
-         *
1737
-         * @param array    $fields_n_values fields and their new values
1738
-         * @param EEM_Base $model           the model being queried
1739
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1740
-         */
1741
-        $fields_n_values = (array) apply_filters(
1742
-            'FHEE__EEM_Base__update__fields_n_values',
1743
-            $fields_n_values,
1744
-            $this,
1745
-            $query_params
1746
-        );
1747
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1748
-        // to do that, for each table, verify that it's PK isn't null.
1749
-        $tables = $this->get_tables();
1750
-        // 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
1751
-        // NOTE: we should make this code more efficient by NOT querying twice
1752
-        // before the real update, but that needs to first go through ALPHA testing
1753
-        // as it's dangerous. says Mike August 8 2014
1754
-        // we want to make sure the default_where strategy is ignored
1755
-        $this->_ignore_where_strategy = true;
1756
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1757
-        foreach ($wpdb_select_results as $wpdb_result) {
1758
-            // type cast stdClass as array
1759
-            $wpdb_result = (array) $wpdb_result;
1760
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761
-            if ($this->has_primary_key_field()) {
1762
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1763
-            } else {
1764
-                // 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)
1765
-                $main_table_pk_value = null;
1766
-            }
1767
-            // 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
1768
-            // 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
1769
-            if (count($tables) > 1) {
1770
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1771
-                // in that table, and so we'll want to insert one
1772
-                foreach ($tables as $table_obj) {
1773
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1774
-                    // if there is no private key for this table on the results, it means there's no entry
1775
-                    // in this table, right? so insert a row in the current table, using any fields available
1776
-                    if (
1777
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
-                           && $wpdb_result[ $this_table_pk_column ])
1779
-                    ) {
1780
-                        $success = $this->_insert_into_specific_table(
1781
-                            $table_obj,
1782
-                            $fields_n_values,
1783
-                            $main_table_pk_value
1784
-                        );
1785
-                        // if we died here, report the error
1786
-                        if (! $success) {
1787
-                            return false;
1788
-                        }
1789
-                    }
1790
-                }
1791
-            }
1792
-            //              //and now check that if we have cached any models by that ID on the model, that
1793
-            //              //they also get updated properly
1794
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1795
-            //              if( $model_object ){
1796
-            //                  foreach( $fields_n_values as $field => $value ){
1797
-            //                      $model_object->set($field, $value);
1798
-            // let's make sure default_where strategy is followed now
1799
-            $this->_ignore_where_strategy = false;
1800
-        }
1801
-        // if we want to keep model objects in sync, AND
1802
-        // if this wasn't called from a model object (to update itself)
1803
-        // then we want to make sure we keep all the existing
1804
-        // model objects in sync with the db
1805
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1806
-            if ($this->has_primary_key_field()) {
1807
-                $model_objs_affected_ids = $this->get_col($query_params);
1808
-            } else {
1809
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1810
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1811
-                $model_objs_affected_ids     = [];
1812
-                foreach ($models_affected_key_columns as $row) {
1813
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1814
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1815
-                }
1816
-            }
1817
-            if (! $model_objs_affected_ids) {
1818
-                // wait wait wait- if nothing was affected let's stop here
1819
-                return 0;
1820
-            }
1821
-            foreach ($model_objs_affected_ids as $id) {
1822
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1823
-                if ($model_obj_in_entity_map) {
1824
-                    foreach ($fields_n_values as $field => $new_value) {
1825
-                        $model_obj_in_entity_map->set($field, $new_value);
1826
-                    }
1827
-                }
1828
-            }
1829
-            // if there is a primary key on this model, we can now do a slight optimization
1830
-            if ($this->has_primary_key_field()) {
1831
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1832
-                $query_params = [
1833
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1834
-                    'limit'                    => count($model_objs_affected_ids),
1835
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1836
-                ];
1837
-            }
1838
-        }
1839
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1840
-
1841
-        // note: the following query doesn't use _construct_2nd_half_of_select_query()
1842
-        // because it doesn't accept LIMIT, ORDER BY, etc.
1843
-        $rows_affected = $this->_do_wpdb_query(
1844
-            'query',
1845
-            [
1846
-                "UPDATE " . $model_query_info->get_full_join_sql()
1847
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1848
-                . $model_query_info->get_where_sql(),
1849
-            ]
1850
-        );
1851
-
1852
-        /**
1853
-         * Action called after a model update call has been made.
1854
-         *
1855
-         * @param EEM_Base $model
1856
-         * @param array    $fields_n_values the updated fields and their new values
1857
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1858
-         * @param int      $rows_affected
1859
-         */
1860
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
-        return $rows_affected;// how many supposedly got updated
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where the values
1867
-     * are the values of the field specified (or by default the primary key field)
1868
-     * that matched the query params. Note that you should pass the name of the
1869
-     * model FIELD, not the database table's column name.
1870
-     *
1871
-     * @param array  $query_params 
1872
-     * @param string $field_to_select
1873
-     * @return array just like $wpdb->get_col()
1874
-     * @throws EE_Error
1875
-     * @throws ReflectionException
1876
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md for $query_params values
1877
-     */
1878
-    public function get_col($query_params = [], $field_to_select = null)
1879
-    {
1880
-        if ($field_to_select) {
1881
-            $field = $this->field_settings_for($field_to_select);
1882
-        } elseif ($this->has_primary_key_field()) {
1883
-            $field = $this->get_primary_key_field();
1884
-        } else {
1885
-            $field_settings = $this->field_settings();
1886
-            // no primary key, just grab the first column
1887
-            $field = reset($field_settings);
1888
-            // don't need this array now
1889
-            unset($field_settings);
1890
-        }
1891
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892
-        $select_expressions = $field->get_qualified_column();
1893
-        $SQL                =
1894
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1895
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * Returns a single column value for a single row from the database
1901
-     *
1902
-     * @param array  $query_params    @see
1903
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1904
-     * @param string $field_to_select @see EEM_Base::get_col()
1905
-     * @return string
1906
-     * @throws EE_Error
1907
-     * @throws ReflectionException
1908
-     */
1909
-    public function get_var($query_params = [], $field_to_select = null)
1910
-    {
1911
-        $query_params['limit'] = 1;
1912
-        $col                   = $this->get_col($query_params, $field_to_select);
1913
-        if (! empty($col)) {
1914
-            return reset($col);
1915
-        }
1916
-        return null;
1917
-    }
1918
-
1919
-
1920
-    /**
1921
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1922
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1923
-     * injection, but currently no further filtering is done
1924
-     *
1925
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1926
-     *                               be updated to in the DB
1927
-     * @return string of SQL
1928
-     * @throws EE_Error
1929
-     * @global      $wpdb
1930
-     */
1931
-    public function _construct_update_sql($fields_n_values)
1932
-    {
1933
-        /** @type WPDB $wpdb */
1934
-        global $wpdb;
1935
-        $cols_n_values = [];
1936
-        foreach ($fields_n_values as $field_name => $value) {
1937
-            $field_obj = $this->field_settings_for($field_name);
1938
-            // if the value is NULL, we want to assign the value to that.
1939
-            // wpdb->prepare doesn't really handle that properly
1940
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1941
-            $value_sql       = $prepared_value === null
1942
-                ? 'NULL'
1943
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1945
-        }
1946
-        return implode(",", $cols_n_values);
1947
-    }
1948
-
1949
-
1950
-    /**
1951
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1952
-     * Performs a HARD delete, meaning the database row should always be removed,
1953
-     * not just have a flag field on it switched
1954
-     * Wrapper for EEM_Base::delete_permanently()
1955
-     *
1956
-     * @param mixed   $id
1957
-     * @param boolean $allow_blocking
1958
-     * @return int the number of rows deleted
1959
-     * @throws EE_Error
1960
-     * @throws ReflectionException
1961
-     */
1962
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1963
-    {
1964
-        return $this->delete_permanently(
1965
-            [
1966
-                [$this->get_primary_key_field()->get_name() => $id],
1967
-                'limit' => 1,
1968
-            ],
1969
-            $allow_blocking
1970
-        );
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1976
-     * Wrapper for EEM_Base::delete()
1977
-     *
1978
-     * @param mixed   $id
1979
-     * @param boolean $allow_blocking
1980
-     * @return int the number of rows deleted
1981
-     * @throws EE_Error
1982
-     * @throws ReflectionException
1983
-     */
1984
-    public function delete_by_ID($id, $allow_blocking = true)
1985
-    {
1986
-        return $this->delete(
1987
-            [
1988
-                [$this->get_primary_key_field()->get_name() => $id],
1989
-                'limit' => 1,
1990
-            ],
1991
-            $allow_blocking
1992
-        );
1993
-    }
1994
-
1995
-
1996
-    /**
1997
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1998
-     * meaning if the model has a field that indicates its been "trashed" or
1999
-     * "soft deleted", we will just set that instead of actually deleting the rows.
2000
-     *
2001
-     * @param array   $query_params
2002
-     * @param boolean $allow_blocking
2003
-     * @return int how many rows got deleted
2004
-     * @throws EE_Error
2005
-     * @throws ReflectionException
2006
-     * @see EEM_Base::delete_permanently
2007
-     */
2008
-    public function delete($query_params, $allow_blocking = true)
2009
-    {
2010
-        return $this->delete_permanently($query_params, $allow_blocking);
2011
-    }
2012
-
2013
-
2014
-    /**
2015
-     * Deletes the model objects that meet the query params. Note: this method is overridden
2016
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2017
-     * as archived, not actually deleted
2018
-     *
2019
-     * @param array   $query_params   @see
2020
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2021
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
2022
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
2023
-     *                                deletes regardless of other objects which may depend on it. Its generally
2024
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
2025
-     *                                DB
2026
-     * @return int how many rows got deleted
2027
-     * @throws EE_Error
2028
-     * @throws ReflectionException
2029
-     */
2030
-    public function delete_permanently($query_params, $allow_blocking = true)
2031
-    {
2032
-        /**
2033
-         * Action called just before performing a real deletion query. You can use the
2034
-         * model and its $query_params to find exactly which items will be deleted
2035
-         *
2036
-         * @param EEM_Base $model
2037
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2038
-         * @param boolean  $allow_blocking whether or not to allow related model objects
2039
-         *                                 to block (prevent) this deletion
2040
-         */
2041
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2042
-        // some MySQL databases may be running safe mode, which may restrict
2043
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2044
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2045
-        // to delete them
2046
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2047
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2048
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2049
-            $columns_and_ids_for_deleting
2050
-        );
2051
-        /**
2052
-         * Allows client code to act on the items being deleted before the query is actually executed.
2053
-         *
2054
-         * @param EEM_Base $this                            The model instance being acted on.
2055
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2056
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2057
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2058
-         *                                                  derived from the incoming query parameters.
2059
-         * @see details on the structure of this array in the phpdocs
2060
-         *                                                  for the `_get_ids_for_delete_method`
2061
-         */
2062
-        do_action(
2063
-            'AHEE__EEM_Base__delete__before_query',
2064
-            $this,
2065
-            $query_params,
2066
-            $allow_blocking,
2067
-            $columns_and_ids_for_deleting
2068
-        );
2069
-        $rows_deleted = 0;
2070
-        if ($deletion_where_query_part) {
2071
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2072
-            $table_aliases    = array_keys($this->_tables);
2073
-            $SQL              = "DELETE "
2074
-                                . implode(", ", $table_aliases)
2075
-                                . " FROM "
2076
-                                . $model_query_info->get_full_join_sql()
2077
-                                . " WHERE "
2078
-                                . $deletion_where_query_part;
2079
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2080
-        }
2081
-
2082
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2083
-        // there was no error with the delete query.
2084
-        if (
2085
-            $this->has_primary_key_field()
2086
-            && $rows_deleted !== false
2087
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2088
-        ) {
2089
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2090
-            foreach ($ids_for_removal as $id) {
2091
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2092
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2093
-                }
2094
-            }
2095
-
2096
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2097
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2098
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2099
-            // (although it is possible).
2100
-            // Note this can be skipped by using the provided filter and returning false.
2101
-            if (
2102
-                apply_filters(
2103
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2104
-                    ! $this instanceof EEM_Extra_Meta,
2105
-                    $this
2106
-                )
2107
-            ) {
2108
-                EEM_Extra_Meta::instance()->delete_permanently(
2109
-                    [
2110
-                        0 => [
2111
-                            'EXM_type' => $this->get_this_model_name(),
2112
-                            'OBJ_ID'   => [
2113
-                                'IN',
2114
-                                $ids_for_removal,
2115
-                            ],
2116
-                        ],
2117
-                    ]
2118
-                );
2119
-            }
2120
-        }
2121
-
2122
-        /**
2123
-         * Action called just after performing a real deletion query. Although at this point the
2124
-         * items should have been deleted
2125
-         *
2126
-         * @param EEM_Base $model
2127
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2128
-         * @param int      $rows_deleted
2129
-         */
2130
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2131
-        return (int) $rows_deleted;// how many supposedly got deleted
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     * Checks all the relations that throw error messages when there are blocking related objects
2137
-     * for related model objects. If there are any related model objects on those relations,
2138
-     * adds an EE_Error, and return true
2139
-     *
2140
-     * @param EE_Base_Class|int $this_model_obj_or_id
2141
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2142
-     *                                                 should be ignored when determining whether there are related
2143
-     *                                                 model objects which block this model object's deletion. Useful
2144
-     *                                                 if you know A is related to B and are considering deleting A,
2145
-     *                                                 but want to see if A has any other objects blocking its deletion
2146
-     *                                                 before removing the relation between A and B
2147
-     * @return boolean
2148
-     * @throws EE_Error
2149
-     * @throws ReflectionException
2150
-     */
2151
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2152
-    {
2153
-        // first, if $ignore_this_model_obj was supplied, get its model
2154
-        $ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2155
-            ? $ignore_this_model_obj->get_model()
2156
-            : null;
2157
-        // now check all the relations of $this_model_obj_or_id and see if there
2158
-        // are any related model objects blocking it?
2159
-        $is_blocked = false;
2160
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2161
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2162
-                // if $ignore_this_model_obj was supplied, then for the query
2163
-                // on that model needs to be told to ignore $ignore_this_model_obj
2164
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2165
-                    $related_model_objects = $relation_obj->get_all_related(
2166
-                        $this_model_obj_or_id,
2167
-                        [
2168
-                            [
2169
-                                $ignored_model->get_primary_key_field()->get_name() => [
2170
-                                    '!=',
2171
-                                    $ignore_this_model_obj->ID(),
2172
-                                ],
2173
-                            ],
2174
-                        ]
2175
-                    );
2176
-                } else {
2177
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2178
-                }
2179
-                if ($related_model_objects) {
2180
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2181
-                    $is_blocked = true;
2182
-                }
2183
-            }
2184
-        }
2185
-        return $is_blocked;
2186
-    }
2187
-
2188
-
2189
-    /**
2190
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2191
-     *
2192
-     * @param array $row_results_for_deleting
2193
-     * @param bool  $allow_blocking
2194
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2195
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2196
-     *                              dimension array where the key is the fully qualified primary key column and the
2197
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2198
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2199
-     *                              be a two dimensional array where each element is a group of columns and values that
2200
-     *                              get deleted. Example: array(
2201
-     *                              0 => array(
2202
-     *                              'Term_Relationship.object_id' => 1
2203
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2204
-     *                              ),
2205
-     *                              1 => array(
2206
-     *                              'Term_Relationship.object_id' => 1
2207
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2208
-     *                              )
2209
-     *                              )
2210
-     * @throws EE_Error
2211
-     * @throws ReflectionException
2212
-     */
2213
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2214
-    {
2215
-        $ids_to_delete_indexed_by_column = [];
2216
-        if ($this->has_primary_key_field()) {
2217
-            $primary_table = $this->_get_main_table();
2218
-            // following lines are commented out because the variables were not being used
2219
-            // not deleting because unsure if calls were intentionally causing side effects
2220
-            // $primary_table_pk_field          =
2221
-            //     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2222
-            // $other_tables                    = $this->_get_other_tables();
2223
-            $ids_to_delete_indexed_by_column = $query = [];
2224
-            foreach ($row_results_for_deleting as $item_to_delete) {
2225
-                // before we mark this item for deletion,
2226
-                // make sure there's no related entities blocking its deletion (if we're checking)
2227
-                if (
2228
-                    $allow_blocking
2229
-                    && $this->delete_is_blocked_by_related_models(
2230
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2231
-                    )
2232
-                ) {
2233
-                    continue;
2234
-                }
2235
-                // primary table deletes
2236
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2237
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2238
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2239
-                }
2240
-            }
2241
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2242
-            $fields = $this->get_combined_primary_key_fields();
2243
-            foreach ($row_results_for_deleting as $item_to_delete) {
2244
-                $ids_to_delete_indexed_by_column_for_row = [];
2245
-                foreach ($fields as $cpk_field) {
2246
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2247
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2248
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2249
-                    }
2250
-                }
2251
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2252
-            }
2253
-        } else {
2254
-            // so there's no primary key and no combined key...
2255
-            // sorry, can't help you
2256
-            throw new EE_Error(
2257
-                sprintf(
2258
-                    esc_html__(
2259
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2260
-                        "event_espresso"
2261
-                    ),
2262
-                    get_class($this)
2263
-                )
2264
-            );
2265
-        }
2266
-        return $ids_to_delete_indexed_by_column;
2267
-    }
2268
-
2269
-
2270
-    /**
2271
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2272
-     * the corresponding query_part for the query performing the delete.
2273
-     *
2274
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2275
-     * @return string
2276
-     * @throws EE_Error
2277
-     */
2278
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2279
-    {
2280
-        $query_part = '';
2281
-        if (empty($ids_to_delete_indexed_by_column)) {
2282
-            return $query_part;
2283
-        } elseif ($this->has_primary_key_field()) {
2284
-            $query = [];
2285
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2286
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2287
-            }
2288
-            $query_part = ! empty($query)
2289
-                ? implode(' AND ', $query)
2290
-                : $query_part;
2291
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2292
-            $ways_to_identify_a_row = [];
2293
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2294
-                $values_for_each_combined_primary_key_for_a_row = [];
2295
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2296
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2297
-                }
2298
-                $ways_to_identify_a_row[] = '('
2299
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2300
-                                            . ')';
2301
-            }
2302
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2303
-        }
2304
-        return $query_part;
2305
-    }
2306
-
2307
-
2308
-    /**
2309
-     * Gets the model field by the fully qualified name
2310
-     *
2311
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2312
-     * @return EE_Model_Field_Base
2313
-     * @throws EE_Error
2314
-     * @throws EE_Error
2315
-     */
2316
-    public function get_field_by_column($qualified_column_name)
2317
-    {
2318
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2319
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2320
-                return $field_obj;
2321
-            }
2322
-        }
2323
-        throw new EE_Error(
2324
-            sprintf(
2325
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2326
-                $this->get_this_model_name(),
2327
-                $qualified_column_name
2328
-            )
2329
-        );
2330
-    }
2331
-
2332
-
2333
-    /**
2334
-     * Count all the rows that match criteria the model query params.
2335
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2336
-     * column
2337
-     *
2338
-     * @param array  $query_params   @see
2339
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2340
-     * @param string $field_to_count field on model to count by (not column name)
2341
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2342
-     *                               that by the setting $distinct to TRUE;
2343
-     * @return int
2344
-     * @throws EE_Error
2345
-     * @throws ReflectionException
2346
-     */
2347
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2348
-    {
2349
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2350
-        if ($field_to_count) {
2351
-            $field_obj       = $this->field_settings_for($field_to_count);
2352
-            $column_to_count = $field_obj->get_qualified_column();
2353
-        } elseif ($this->has_primary_key_field()) {
2354
-            $pk_field_obj    = $this->get_primary_key_field();
2355
-            $column_to_count = $pk_field_obj->get_qualified_column();
2356
-        } else {
2357
-            // there's no primary key
2358
-            // if we're counting distinct items, and there's no primary key,
2359
-            // we need to list out the columns for distinction;
2360
-            // otherwise we can just use star
2361
-            if ($distinct) {
2362
-                $columns_to_use = [];
2363
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2364
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2365
-                }
2366
-                $column_to_count = implode(',', $columns_to_use);
2367
-            } else {
2368
-                $column_to_count = '*';
2369
-            }
2370
-        }
2371
-        $column_to_count = $distinct
2372
-            ? "DISTINCT " . $column_to_count
2373
-            : $column_to_count;
2374
-        $SQL             =
2375
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2376
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2377
-    }
2378
-
2379
-
2380
-    /**
2381
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2382
-     *
2383
-     * @param array  $query_params @see
2384
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2385
-     * @param string $field_to_sum name of field (array key in $_fields array)
2386
-     * @return float
2387
-     * @throws EE_Error
2388
-     * @throws ReflectionException
2389
-     */
2390
-    public function sum($query_params, $field_to_sum = null)
2391
-    {
2392
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2393
-        if ($field_to_sum) {
2394
-            $field_obj = $this->field_settings_for($field_to_sum);
2395
-        } else {
2396
-            $field_obj = $this->get_primary_key_field();
2397
-        }
2398
-        $column_to_count = $field_obj->get_qualified_column();
2399
-        $SQL             =
2400
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2401
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2402
-        $data_type       = $field_obj->get_wpdb_data_type();
2403
-        if ($data_type === '%d' || $data_type === '%s') {
2404
-            return (float) $return_value;
2405
-        }
2406
-        // must be %f
2407
-        return (float) $return_value;
2408
-    }
2409
-
2410
-
2411
-    /**
2412
-     * Just calls the specified method on $wpdb with the given arguments
2413
-     * Consolidates a little extra error handling code
2414
-     *
2415
-     * @param string $wpdb_method
2416
-     * @param array  $arguments_to_provide
2417
-     * @return mixed
2418
-     * @throws EE_Error
2419
-     * @global wpdb  $wpdb
2420
-     */
2421
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2422
-    {
2423
-        // if we're in maintenance mode level 2, DON'T run any queries
2424
-        // because level 2 indicates the database needs updating and
2425
-        // is probably out of sync with the code
2426
-        if (DbStatus::isOffline()) {
2427
-            throw new RuntimeException(
2428
-                esc_html__(
2429
-                    "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.",
2430
-                    "event_espresso"
2431
-                )
2432
-            );
2433
-        }
2434
-        /** @type WPDB $wpdb */
2435
-        global $wpdb;
2436
-        if (! method_exists($wpdb, $wpdb_method)) {
2437
-            throw new DomainException(
2438
-                sprintf(
2439
-                    esc_html__(
2440
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2441
-                        'event_espresso'
2442
-                    ),
2443
-                    $wpdb_method
2444
-                )
2445
-            );
2446
-        }
2447
-        $old_show_errors_value = $wpdb->show_errors;
2448
-        if (defined('WP_DEBUG') && WP_DEBUG) {
2449
-            $wpdb->show_errors(false);
2450
-        }
2451
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2452
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2453
-        if (defined('WP_DEBUG') && WP_DEBUG) {
2454
-            $wpdb->show_errors($old_show_errors_value);
2455
-            if (! empty($wpdb->last_error)) {
2456
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2457
-            }
2458
-            if ($result === false) {
2459
-                throw new EE_Error(
2460
-                    sprintf(
2461
-                        esc_html__(
2462
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2463
-                            'event_espresso'
2464
-                        ),
2465
-                        $wpdb_method,
2466
-                        var_export($arguments_to_provide, true)
2467
-                    )
2468
-                );
2469
-            }
2470
-        } elseif ($result === false) {
2471
-            EE_Error::add_error(
2472
-                sprintf(
2473
-                    esc_html__(
2474
-                        '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"',
2475
-                        'event_espresso'
2476
-                    ),
2477
-                    $wpdb_method,
2478
-                    var_export($arguments_to_provide, true),
2479
-                    $wpdb->last_error
2480
-                ),
2481
-                __FILE__,
2482
-                __FUNCTION__,
2483
-                __LINE__
2484
-            );
2485
-        }
2486
-        return $result;
2487
-    }
2488
-
2489
-
2490
-    /**
2491
-     * Attempts to run the indicated WPDB method with the provided arguments,
2492
-     * and if there's an error tries to verify the DB is correct. Uses
2493
-     * the static property EEM_Base::$_db_verification_level to determine whether
2494
-     * we should try to fix the EE core db, the addons, or just give up
2495
-     *
2496
-     * @param string $wpdb_method
2497
-     * @param array  $arguments_to_provide
2498
-     * @return mixed
2499
-     */
2500
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2501
-    {
2502
-        /** @type WPDB $wpdb */
2503
-        global $wpdb;
2504
-        $wpdb->last_error = null;
2505
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2506
-        // was there an error running the query? but we don't care on new activations
2507
-        // (we're going to setup the DB anyway on new activations)
2508
-        if (
2509
-            ($result === false || ! empty($wpdb->last_error))
2510
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2511
-        ) {
2512
-            switch (EEM_Base::$_db_verification_level) {
2513
-                case EEM_Base::db_verified_none:
2514
-                    // let's double-check core's DB
2515
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2516
-                    break;
2517
-                case EEM_Base::db_verified_core:
2518
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2519
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2520
-                    break;
2521
-                case EEM_Base::db_verified_addons:
2522
-                    // ummmm... you in trouble
2523
-                    return $result;
2524
-            }
2525
-            if (! empty($error_message)) {
2526
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2527
-                trigger_error($error_message);
2528
-            }
2529
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2530
-        }
2531
-        return $result;
2532
-    }
2533
-
2534
-
2535
-    /**
2536
-     * Verifies the EE core database is up-to-date and records that we've done it on
2537
-     * EEM_Base::$_db_verification_level
2538
-     *
2539
-     * @param string $wpdb_method
2540
-     * @param array  $arguments_to_provide
2541
-     * @return string
2542
-     * @throws EE_Error
2543
-     * @throws ReflectionException
2544
-     */
2545
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2546
-    {
2547
-        /** @type WPDB $wpdb */
2548
-        global $wpdb;
2549
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2550
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2551
-        $error_message                    = sprintf(
2552
-            esc_html__(
2553
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2554
-                'event_espresso'
2555
-            ),
2556
-            $wpdb->last_error,
2557
-            $wpdb_method,
2558
-            wp_json_encode($arguments_to_provide)
2559
-        );
2560
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2561
-        return $error_message;
2562
-    }
2563
-
2564
-
2565
-    /**
2566
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2567
-     * EEM_Base::$_db_verification_level
2568
-     *
2569
-     * @param $wpdb_method
2570
-     * @param $arguments_to_provide
2571
-     * @return string
2572
-     * @throws EE_Error
2573
-     * @throws ReflectionException
2574
-     */
2575
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2576
-    {
2577
-        /** @type WPDB $wpdb */
2578
-        global $wpdb;
2579
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2580
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2581
-        $error_message                    = sprintf(
2582
-            esc_html__(
2583
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2584
-                'event_espresso'
2585
-            ),
2586
-            $wpdb->last_error,
2587
-            $wpdb_method,
2588
-            wp_json_encode($arguments_to_provide)
2589
-        );
2590
-        EE_System::instance()->initialize_addons();
2591
-        return $error_message;
2592
-    }
2593
-
2594
-
2595
-    /**
2596
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2597
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2598
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2599
-     * ..."
2600
-     *
2601
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2602
-     * @return string
2603
-     */
2604
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2605
-    {
2606
-        return " FROM " . $model_query_info->get_full_join_sql() .
2607
-               $model_query_info->get_where_sql() .
2608
-               $model_query_info->get_group_by_sql() .
2609
-               $model_query_info->get_having_sql() .
2610
-               $model_query_info->get_order_by_sql() .
2611
-               $model_query_info->get_limit_sql();
2612
-    }
2613
-
2614
-
2615
-    /**
2616
-     * Set to easily debug the next X queries ran from this model.
2617
-     *
2618
-     * @param int $count
2619
-     */
2620
-    public function show_next_x_db_queries($count = 1)
2621
-    {
2622
-        $this->_show_next_x_db_queries = $count;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * @param $sql_query
2628
-     */
2629
-    public function show_db_query_if_previously_requested($sql_query)
2630
-    {
2631
-        if ($this->_show_next_x_db_queries > 0) {
2632
-            $left = is_admin() ? '12rem' : '2rem';
2633
-            echo "
42
+	/**
43
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
46
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
+	 *
48
+	 * @var boolean
49
+	 */
50
+	private $_values_already_prepared_by_model_object = 0;
51
+
52
+	/**
53
+	 * when $_values_already_prepared_by_model_object equals this, we assume
54
+	 * the data is just like form input that needs to have the model fields'
55
+	 * prepare_for_set and prepare_for_use_in_db called on it
56
+	 */
57
+	const not_prepared_by_model_object = 0;
58
+
59
+	/**
60
+	 * when $_values_already_prepared_by_model_object equals this, we
61
+	 * assume this value is coming from a model object and doesn't need to have
62
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
63
+	 */
64
+	const prepared_by_model_object = 1;
65
+
66
+	/**
67
+	 * when $_values_already_prepared_by_model_object equals this, we assume
68
+	 * the values are already to be used in the database (ie no processing is done
69
+	 * on them by the model's fields)
70
+	 */
71
+	const prepared_for_use_in_db = 2;
72
+
73
+
74
+	protected $singular_item = 'Item';
75
+
76
+	protected $plural_item   = 'Items';
77
+
78
+	/**
79
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
+	 */
81
+	protected $_tables;
82
+
83
+	/**
84
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
+	 *
88
+	 * @var EE_Model_Field_Base[][] $_fields
89
+	 */
90
+	protected $_fields;
91
+
92
+	/**
93
+	 * array of different kinds of relations
94
+	 *
95
+	 * @var EE_Model_Relation_Base[] $_model_relations
96
+	 */
97
+	protected $_model_relations = [];
98
+
99
+	/**
100
+	 * @var EE_Index[] $_indexes
101
+	 */
102
+	protected $_indexes = [];
103
+
104
+	/**
105
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
106
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
+	 * by setting the same columns as used in these queries in the query yourself.
108
+	 *
109
+	 * @var EE_Default_Where_Conditions
110
+	 */
111
+	protected $_default_where_conditions_strategy;
112
+
113
+	/**
114
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
+	 * This is particularly useful when you want something between 'none' and 'default'
116
+	 *
117
+	 * @var EE_Default_Where_Conditions
118
+	 */
119
+	protected $_minimum_where_conditions_strategy;
120
+
121
+	/**
122
+	 * String describing how to find the "owner" of this model's objects.
123
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
+	 * But when there isn't, this indicates which related model, or transiently-related model,
125
+	 * has the foreign key to the wp_users table.
126
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
+	 * related to events, and events have a foreign key to wp_users.
128
+	 * On EEM_Transaction, this would be 'Transaction.Event'
129
+	 *
130
+	 * @var string
131
+	 */
132
+	protected $_model_chain_to_wp_user = '';
133
+
134
+	/**
135
+	 * String describing how to find the model with a password controlling access to this model. This property has the
136
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
+	 * This value is the path of models to follow to arrive at the model with the password field.
138
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
+	 * model with a password that should affect reading this on the front-end.
140
+	 * Eg this is an empty string for the Event model because it has a password.
141
+	 * This is null for the Registration model, because its event's password has no bearing on whether
142
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
+	 * should hide tickets for datetimes for events that have a password set.
145
+	 *
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = [
178
+		self::caps_read       => [],
179
+		self::caps_read_admin => [],
180
+		self::caps_edit       => [],
181
+		self::caps_delete     => [],
182
+	];
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = [];
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in the capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = [
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	];
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = [];
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 *
298
+	 * @var boolean
299
+	 */
300
+	protected $_wp_core_model = false;
301
+
302
+	/**
303
+	 * @var bool stores whether this model has a password field or not.
304
+	 * null until initialized by hasPasswordField()
305
+	 */
306
+	protected $has_password_field;
307
+
308
+	/**
309
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
+	 */
311
+	protected $password_field;
312
+
313
+	/**
314
+	 *    List of valid operators that can be used for querying.
315
+	 * The keys are all operators we'll accept, the values are the real SQL
316
+	 * operators used
317
+	 *
318
+	 * @var array
319
+	 */
320
+	protected $_valid_operators = [
321
+		'='           => '=',
322
+		'<='          => '<=',
323
+		'<'           => '<',
324
+		'>='          => '>=',
325
+		'>'           => '>',
326
+		'!='          => '!=',
327
+		'LIKE'        => 'LIKE',
328
+		'like'        => 'LIKE',
329
+		'NOT_LIKE'    => 'NOT LIKE',
330
+		'not_like'    => 'NOT LIKE',
331
+		'NOT LIKE'    => 'NOT LIKE',
332
+		'not like'    => 'NOT LIKE',
333
+		'IN'          => 'IN',
334
+		'in'          => 'IN',
335
+		'NOT_IN'      => 'NOT IN',
336
+		'not_in'      => 'NOT IN',
337
+		'NOT IN'      => 'NOT IN',
338
+		'not in'      => 'NOT IN',
339
+		'between'     => 'BETWEEN',
340
+		'BETWEEN'     => 'BETWEEN',
341
+		'IS_NOT_NULL' => 'IS NOT NULL',
342
+		'is_not_null' => 'IS NOT NULL',
343
+		'IS NOT NULL' => 'IS NOT NULL',
344
+		'is not null' => 'IS NOT NULL',
345
+		'IS_NULL'     => 'IS NULL',
346
+		'is_null'     => 'IS NULL',
347
+		'IS NULL'     => 'IS NULL',
348
+		'is null'     => 'IS NULL',
349
+		'REGEXP'      => 'REGEXP',
350
+		'regexp'      => 'REGEXP',
351
+		'NOT_REGEXP'  => 'NOT REGEXP',
352
+		'not_regexp'  => 'NOT REGEXP',
353
+		'NOT REGEXP'  => 'NOT REGEXP',
354
+		'not regexp'  => 'NOT REGEXP',
355
+	];
356
+
357
+	/**
358
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
+	 *
360
+	 * @var array
361
+	 */
362
+	protected $_in_style_operators = ['IN', 'NOT IN'];
363
+
364
+	/**
365
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
+	 * '12-31-2012'"
367
+	 *
368
+	 * @var array
369
+	 */
370
+	protected $_between_style_operators = ['BETWEEN'];
371
+
372
+	/**
373
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
+
379
+	/**
380
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
+	 * on a join table.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
+
387
+	/**
388
+	 * Allowed values for $query_params['order'] for ordering in queries
389
+	 *
390
+	 * @var array
391
+	 */
392
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
+
394
+	/**
395
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
+
402
+	/**
403
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
405
+	 *
406
+	 * @var array
407
+	 */
408
+	private $_allowed_query_params = [
409
+		0,
410
+		'limit',
411
+		'order_by',
412
+		'group_by',
413
+		'having',
414
+		'force_join',
415
+		'order',
416
+		'on_join_limit',
417
+		'default_where_conditions',
418
+		'caps',
419
+		'extra_selects',
420
+		'exclude_protected',
421
+	];
422
+
423
+	/**
424
+	 * All the data types that can be used in $wpdb->prepare statements.
425
+	 *
426
+	 * @var array
427
+	 */
428
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
+
430
+	/**
431
+	 * @var EE_Registry $EE
432
+	 */
433
+	protected $EE = null;
434
+
435
+
436
+	/**
437
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
+	 *
439
+	 * @var int
440
+	 */
441
+	protected $_show_next_x_db_queries = 0;
442
+
443
+	/**
444
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
+	 * WHERE, GROUP_BY, etc.
447
+	 *
448
+	 * @var CustomSelects
449
+	 */
450
+	protected $_custom_selections = [];
451
+
452
+	/**
453
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
+	 * caches every model object we've fetched from the DB on this request
455
+	 *
456
+	 * @var array
457
+	 */
458
+	protected $_entity_map;
459
+
460
+	/**
461
+	 * @var LoaderInterface
462
+	 */
463
+	protected static $loader;
464
+
465
+	/**
466
+	 * @var Mirror
467
+	 */
468
+	private static $mirror;
469
+
470
+
471
+	/**
472
+	 * constant used to show EEM_Base has not yet verified the db on this http request
473
+	 */
474
+	const db_verified_none = 0;
475
+
476
+	/**
477
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
478
+	 * but not the addons' dbs
479
+	 */
480
+	const db_verified_core = 1;
481
+
482
+	/**
483
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
+	 * the EE core db too)
485
+	 */
486
+	const db_verified_addons = 2;
487
+
488
+	/**
489
+	 * indicates whether an EEM_Base child has already re-verified the DB
490
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
491
+	 * looking like EEM_Base::db_verified_*
492
+	 *
493
+	 * @var int - 0 = none, 1 = core, 2 = addons
494
+	 */
495
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
496
+
497
+	/**
498
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
499
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
500
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
501
+	 */
502
+	const default_where_conditions_all = 'all';
503
+
504
+	/**
505
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
506
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
507
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
508
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
509
+	 *        models which share tables with other models, this can return data for the wrong model.
510
+	 */
511
+	const default_where_conditions_this_only = 'this_model_only';
512
+
513
+	/**
514
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
515
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
516
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
517
+	 */
518
+	const default_where_conditions_others_only = 'other_models_only';
519
+
520
+	/**
521
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
522
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
523
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
524
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
525
+	 *        (regardless of whether those events and venues are trashed)
526
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
527
+	 *        events.
528
+	 */
529
+	const default_where_conditions_minimum_all = 'minimum';
530
+
531
+	/**
532
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
533
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
534
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
535
+	 *        not)
536
+	 */
537
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
538
+
539
+	/**
540
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
541
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
542
+	 *        it's possible it will return table entries for other models. You should use
543
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
544
+	 */
545
+	const default_where_conditions_none = 'none';
546
+
547
+
548
+	/**
549
+	 * About all child constructors:
550
+	 * they should define the _tables, _fields and _model_relations arrays.
551
+	 * Should ALWAYS be called after child constructor.
552
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
553
+	 * finalizes constructing all the object's attributes.
554
+	 * Generally, rather than requiring a child to code
555
+	 * $this->_tables = array(
556
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
557
+	 *        ...);
558
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
559
+	 * each EE_Table has a function to set the table's alias after the constructor, using
560
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
561
+	 * do something similar.
562
+	 *
563
+	 * @param string|null $timezone
564
+	 * @throws EE_Error
565
+	 * @throws Exception
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'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.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
599
+			}
600
+		}
601
+		/**
602
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
603
+		 * EE_Register_Model_Extension
604
+		 *
605
+		 * @param EE_Model_Field_Base[] $_fields
606
+		 */
607
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+		$this->_invalidate_field_caches();
609
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
610
+			if (! array_key_exists($table_alias, $this->_tables)) {
611
+				throw new EE_Error(
612
+					sprintf(
613
+						esc_html__(
614
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
615
+							'event_espresso'
616
+						),
617
+						$table_alias,
618
+						implode(",", $this->_fields)
619
+					)
620
+				);
621
+			}
622
+			foreach ($fields_for_table as $field_name => $field_obj) {
623
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
624
+				// primary key field base has a slightly different _construct_finalize
625
+				/** @var $field_obj EE_Model_Field_Base */
626
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
627
+			}
628
+		}
629
+		// everything is related to Extra_Meta
630
+		if (get_class($this) !== 'EEM_Extra_Meta') {
631
+			// make extra meta related to everything, but don't block deleting things just
632
+			// because they have related extra meta info. For now just orphan those extra meta
633
+			// in the future we should automatically delete them
634
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
635
+		}
636
+		// and change logs
637
+		if (get_class($this) !== 'EEM_Change_Log') {
638
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
639
+		}
640
+		/**
641
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
642
+		 * EE_Register_Model_Extension
643
+		 *
644
+		 * @param EE_Model_Relation_Base[] $_model_relations
645
+		 */
646
+		$this->_model_relations = (array) apply_filters(
647
+			'FHEE__' . get_class($this) . '__construct__model_relations',
648
+			$this->_model_relations
649
+		);
650
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
651
+			/** @var $relation_obj EE_Model_Relation_Base */
652
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
653
+		}
654
+		foreach ($this->_indexes as $index_name => $index_obj) {
655
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
656
+		}
657
+		$this->set_timezone($timezone);
658
+		// finalize default where condition strategy, or set default
659
+		if (! $this->_default_where_conditions_strategy) {
660
+			// nothing was set during child constructor, so set default
661
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662
+		}
663
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
664
+		if (! $this->_minimum_where_conditions_strategy) {
665
+			// nothing was set during child constructor, so set default
666
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667
+		}
668
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
669
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
670
+		// to indicate to NOT set it, set it to the logical default
671
+		if ($this->_caps_slug === null) {
672
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
673
+		}
674
+		// initialize the standard cap restriction generators if none were specified by the child constructor
675
+		if (is_array($this->_cap_restriction_generators)) {
676
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
679
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680
+						new EE_Restriction_Generator_Protected(),
681
+						$cap_context,
682
+						$this
683
+					);
684
+				}
685
+			}
686
+		}
687
+		// if there are cap restriction generators, use them to make the default cap restrictions
688
+		if (is_array($this->_cap_restriction_generators)) {
689
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
+				if (! $generator_object) {
691
+					continue;
692
+				}
693
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+					throw new EE_Error(
695
+						sprintf(
696
+							esc_html__(
697
+								'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.',
698
+								'event_espresso'
699
+							),
700
+							$context,
701
+							$this->get_this_model_name()
702
+						)
703
+					);
704
+				}
705
+				$action = $this->cap_action_for_context($context);
706
+				if (! $generator_object->construction_finalized()) {
707
+					$generator_object->_construct_finalize($this, $action);
708
+				}
709
+			}
710
+		}
711
+		do_action('AHEE__' . get_class($this) . '__construct__end');
712
+	}
713
+
714
+
715
+	/**
716
+	 * @return LoaderInterface
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	protected static function getLoader(): LoaderInterface
722
+	{
723
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
724
+			EEM_Base::$loader = LoaderFactory::getLoader();
725
+		}
726
+		return EEM_Base::$loader;
727
+	}
728
+
729
+
730
+	/**
731
+	 * @return Mirror
732
+	 * @since   5.0.0.p
733
+	 */
734
+	private static function getMirror(): Mirror
735
+	{
736
+		if (! EEM_Base::$mirror instanceof Mirror) {
737
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738
+		}
739
+		return EEM_Base::$mirror;
740
+	}
741
+
742
+
743
+	/**
744
+	 * @param string $model_class_Name
745
+	 * @param string $timezone
746
+	 * @return array
747
+	 * @throws ReflectionException
748
+	 * @since   5.0.0.p
749
+	 */
750
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
751
+	{
752
+		$arguments = [$timezone];
753
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
754
+		if (count($params) > 1) {
755
+			if ($params[1]->getName() === 'model_field_factory') {
756
+				$arguments = [
757
+					$timezone,
758
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
759
+				];
760
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
761
+				$arguments = [
762
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
763
+					$timezone,
764
+				];
765
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
766
+				$arguments = [
767
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
768
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
769
+					$timezone,
770
+				];
771
+			}
772
+		}
773
+		return $arguments;
774
+	}
775
+
776
+
777
+	/**
778
+	 * This function is a singleton method used to instantiate the Espresso_model object
779
+	 *
780
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
781
+	 *                                (and any incoming timezone data that gets saved).
782
+	 *                                Note this just sends the timezone info to the date time model field objects.
783
+	 *                                Default is NULL
784
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
785
+	 * @return static (as in the concrete child class)
786
+	 * @throws EE_Error
787
+	 * @throws ReflectionException
788
+	 */
789
+	public static function instance($timezone = '')
790
+	{
791
+		// check if instance of Espresso_model already exists
792
+		if (! static::$_instance instanceof static) {
793
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794
+			$model     = new static(...$arguments);
795
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
796
+			static::$_instance = $model;
797
+		}
798
+		// we might have a timezone set, let set_timezone decide what to do with it
799
+		if ($timezone) {
800
+			static::$_instance->set_timezone($timezone);
801
+		}
802
+		// Espresso_model object
803
+		return static::$_instance;
804
+	}
805
+
806
+
807
+	/**
808
+	 * resets the model and returns it
809
+	 *
810
+	 * @param string|null $timezone
811
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
812
+	 * all its properties reset; if it wasn't instantiated, returns null)
813
+	 * @throws EE_Error
814
+	 * @throws ReflectionException
815
+	 * @throws InvalidArgumentException
816
+	 * @throws InvalidDataTypeException
817
+	 * @throws InvalidInterfaceException
818
+	 */
819
+	public static function reset($timezone = '')
820
+	{
821
+		if (! static::$_instance instanceof EEM_Base) {
822
+			return null;
823
+		}
824
+		// Let's NOT swap out the current instance for a new one
825
+		// because if someone has a reference to it, we can't remove their reference.
826
+		// It's best to keep using the same reference but change the original object instead,
827
+		// so reset all its properties to their original values as defined in the class.
828
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
829
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830
+			// don't set instance to null like it was originally,
831
+			// but it's static anyways, and we're ignoring static properties (for now at least)
832
+			if (! isset($static_properties[ $property ])) {
833
+				static::$_instance->{$property} = $value;
834
+			}
835
+		}
836
+		// and then directly call its constructor again, like we would if we were creating a new one
837
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
838
+		static::$_instance->__construct(...$arguments);
839
+		return self::instance();
840
+	}
841
+
842
+
843
+	/**
844
+	 * Used to set the $_model_query_blog_id static property.
845
+	 *
846
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
847
+	 *                      value for get_current_blog_id() will be used.
848
+	 */
849
+	public static function set_model_query_blog_id($blog_id = 0)
850
+	{
851
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
852
+			? (int) $blog_id
853
+			: get_current_blog_id();
854
+	}
855
+
856
+
857
+	/**
858
+	 * Returns whatever is set as the internal $model_query_blog_id.
859
+	 *
860
+	 * @return int
861
+	 */
862
+	public static function get_model_query_blog_id()
863
+	{
864
+		return EEM_Base::$_model_query_blog_id;
865
+	}
866
+
867
+
868
+	/**
869
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
870
+	 *
871
+	 * @param boolean $translated return localized strings or JUST the array.
872
+	 * @return array
873
+	 * @throws EE_Error
874
+	 * @throws InvalidArgumentException
875
+	 * @throws InvalidDataTypeException
876
+	 * @throws InvalidInterfaceException
877
+	 * @throws ReflectionException
878
+	 */
879
+	public function status_array($translated = false)
880
+	{
881
+		if (! array_key_exists('Status', $this->_model_relations)) {
882
+			return [];
883
+		}
884
+		$model_name   = $this->get_this_model_name();
885
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
886
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887
+		$status_array = [];
888
+		foreach ($stati as $status) {
889
+			$status_array[ $status->ID() ] = $status->get('STS_code');
890
+		}
891
+		return $translated
892
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
893
+			: $status_array;
894
+	}
895
+
896
+
897
+	/**
898
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
899
+	 *
900
+	 * @param array $query_params             @see
901
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 *                                        or if you have the development copy of EE you can view this at the path:
903
+	 *                                        /docs/G--Model-System/model-query-params.md
904
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
905
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
906
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
907
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
908
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
909
+	 *                                        'OR'=>array(
910
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
911
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
912
+	 *                                        )
913
+	 *                                        ),
914
+	 *                                        'limit'=>10,
915
+	 *                                        'group_by'=>'TXN_ID'
916
+	 *                                        ));
917
+	 *                                        get all the answers to the question titled "shirt size" for event with id
918
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
919
+	 *                                        'Question.QST_display_text'=>'shirt size',
920
+	 *                                        'Registration.Event.EVT_ID'=>12
921
+	 *                                        ),
922
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
923
+	 *                                        ));
924
+	 * @throws EE_Error
925
+	 * @throws ReflectionException
926
+	 */
927
+	public function get_all($query_params = [])
928
+	{
929
+		if (
930
+			isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
936
+	}
937
+
938
+
939
+	/**
940
+	 * Modifies the query parameters so we only get back model objects
941
+	 * that "belong" to the current user
942
+	 *
943
+	 * @param array $query_params @see
944
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
+	 * @return array @see
946
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
947
+	 * @throws ReflectionException
948
+	 * @throws ReflectionException
949
+	 */
950
+	public function alter_query_params_to_only_include_mine($query_params = [])
951
+	{
952
+		$wp_user_field_name = $this->wp_user_field_name();
953
+		if ($wp_user_field_name) {
954
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
955
+		}
956
+		return $query_params;
957
+	}
958
+
959
+
960
+	/**
961
+	 * Returns the name of the field's name that points to the WP_User table
962
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
963
+	 * foreign key to the WP_User table)
964
+	 *
965
+	 * @return string|boolean string on success, boolean false when there is no
966
+	 * foreign key to the WP_User table
967
+	 * @throws ReflectionException
968
+	 * @throws ReflectionException
969
+	 */
970
+	public function wp_user_field_name()
971
+	{
972
+		try {
973
+			if (! empty($this->_model_chain_to_wp_user)) {
974
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975
+				$last_model_name              = end($models_to_follow_to_wp_users);
976
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
978
+			} else {
979
+				$model_with_fk_to_wp_users = $this;
980
+				$model_chain_to_wp_user    = '';
981
+			}
982
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
984
+		} catch (EE_Error $e) {
985
+			return false;
986
+		}
987
+	}
988
+
989
+
990
+	/**
991
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
992
+	 * (or transiently-related model) has a foreign key to the wp_users table;
993
+	 * useful for finding if model objects of this type are 'owned' by the current user.
994
+	 * This is an empty string when the foreign key is on this model and when it isn't,
995
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
996
+	 * (or transiently-related model)
997
+	 *
998
+	 * @return string
999
+	 */
1000
+	public function model_chain_to_wp_user()
1001
+	{
1002
+		return $this->_model_chain_to_wp_user;
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1008
+	 * like how registrations don't have a foreign key to wp_users, but the
1009
+	 * events they are for are), or is unrelated to wp users.
1010
+	 * generally available
1011
+	 *
1012
+	 * @return boolean
1013
+	 */
1014
+	public function is_owned()
1015
+	{
1016
+		if ($this->model_chain_to_wp_user()) {
1017
+			return true;
1018
+		}
1019
+		try {
1020
+			$this->get_foreign_key_to('WP_User');
1021
+			return true;
1022
+		} catch (EE_Error $e) {
1023
+			return false;
1024
+		}
1025
+	}
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      @see
1034
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws EE_Error
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws ReflectionException
1048
+	 */
1049
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1050
+	{
1051
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1052
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions       = $columns_to_select === null
1054
+			? $this->_construct_default_select_sql($model_query_info)
1055
+			: '';
1056
+		if ($this->_custom_selections instanceof CustomSelects) {
1057
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058
+			$select_expressions .= $select_expressions
1059
+				? ', ' . $custom_expressions
1060
+				: $custom_expressions;
1061
+		}
1062
+
1063
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1064
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1070
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1071
+	 * method of including extra select information.
1072
+	 *
1073
+	 * @param array             $query_params
1074
+	 * @param null|array|string $columns_to_select
1075
+	 * @return null|CustomSelects
1076
+	 * @throws InvalidArgumentException
1077
+	 */
1078
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079
+	{
1080
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081
+			return null;
1082
+		}
1083
+		$selects = $query_params['extra_selects'] ?? $columns_to_select;
1084
+		$selects = is_string($selects)
1085
+			? explode(',', $selects)
1086
+			: $selects;
1087
+		return new CustomSelects($selects);
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1093
+	 * but you can use the model query params to more easily
1094
+	 * take care of joins, field preparation etc.
1095
+	 *
1096
+	 * @param array  $query_params      @see
1097
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1098
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1099
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1101
+	 *                                  override this and set the select to "*", or a specific column name, like
1102
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1103
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1104
+	 *                                  the aliases used to refer to this selection, and values are to be
1105
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1106
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1107
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1108
+	 * @throws EE_Error
1109
+	 * @throws ReflectionException
1110
+	 */
1111
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1112
+	{
1113
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * For creating a custom select statement
1119
+	 *
1120
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1121
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1122
+	 *                                 SQL, and 1=>is the datatype
1123
+	 * @return string
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	private function _construct_select_from_input($columns_to_select)
1127
+	{
1128
+		if (is_array($columns_to_select)) {
1129
+			$select_sql_array = [];
1130
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
+					throw new EE_Error(
1133
+						sprintf(
1134
+							esc_html__(
1135
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1136
+								'event_espresso'
1137
+							),
1138
+							$selection_and_datatype,
1139
+							$alias
1140
+						)
1141
+					);
1142
+				}
1143
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144
+					throw new EE_Error(
1145
+						sprintf(
1146
+							esc_html__(
1147
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1148
+								'event_espresso'
1149
+							),
1150
+							$selection_and_datatype[1],
1151
+							$selection_and_datatype[0],
1152
+							$alias,
1153
+							implode(', ', $this->_valid_wpdb_data_types)
1154
+						)
1155
+					);
1156
+				}
1157
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1158
+			}
1159
+			$columns_to_select_string = implode(', ', $select_sql_array);
1160
+		} else {
1161
+			$columns_to_select_string = $columns_to_select;
1162
+		}
1163
+		return $columns_to_select_string;
1164
+	}
1165
+
1166
+
1167
+	/**
1168
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1169
+	 *
1170
+	 * @return string
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function primary_key_name()
1174
+	{
1175
+		return $this->get_primary_key_field()->get_name();
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1181
+	 * If there is no primary key on this model, $id is treated as primary key string
1182
+	 *
1183
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1184
+	 * @return EE_Base_Class|mixed|null
1185
+	 * @throws EE_Error
1186
+	 * @throws ReflectionException
1187
+	 */
1188
+	public function get_one_by_ID($id)
1189
+	{
1190
+		// since entities with no ID can still have properties, we need to check the cache for them
1191
+		$cached_value = $this->get_from_entity_map($id);
1192
+		if ($cached_value) {
1193
+			return $cached_value;
1194
+		}
1195
+		// but if no cahced property AND no id is passed, just return null
1196
+		if (empty($id)) {
1197
+			return null;
1198
+		}
1199
+		$model_object = $this->get_one(
1200
+			$this->alter_query_params_to_restrict_by_ID(
1201
+				$id,
1202
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203
+			)
1204
+		);
1205
+		$className    = $this->_get_class_name();
1206
+		if ($model_object instanceof $className) {
1207
+			// make sure valid objects get added to the entity map
1208
+			// so that the next call to this method doesn't trigger another trip to the db
1209
+			$this->add_to_entity_map($model_object);
1210
+		}
1211
+		return $model_object;
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Alters query parameters to only get items with this ID are returned.
1217
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1218
+	 * or could just be a simple primary key ID
1219
+	 *
1220
+	 * @param int   $id
1221
+	 * @param array $query_params
1222
+	 * @return array of normal query params, @see
1223
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1224
+	 * @throws EE_Error
1225
+	 */
1226
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227
+	{
1228
+		if (! isset($query_params[0])) {
1229
+			$query_params[0] = [];
1230
+		}
1231
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1232
+		if ($conditions_from_id === null) {
1233
+			$query_params[0][ $this->primary_key_name() ] = $id;
1234
+		} else {
1235
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1236
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1237
+		}
1238
+		return $query_params;
1239
+	}
1240
+
1241
+
1242
+	/**
1243
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1244
+	 * array. If no item is found, null is returned.
1245
+	 *
1246
+	 * @param array $query_params like EEM_Base's $query_params variable.
1247
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1248
+	 * @throws EE_Error
1249
+	 * @throws ReflectionException
1250
+	 */
1251
+	public function get_one($query_params = [])
1252
+	{
1253
+		if (! is_array($query_params)) {
1254
+			EE_Error::doing_it_wrong(
1255
+				'EEM_Base::get_one',
1256
+				sprintf(
1257
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1258
+					gettype($query_params)
1259
+				),
1260
+				'4.6.0'
1261
+			);
1262
+			$query_params = [];
1263
+		}
1264
+		$query_params['limit'] = 1;
1265
+		$items                 = $this->get_all($query_params);
1266
+		if (empty($items)) {
1267
+			return null;
1268
+		}
1269
+		return array_shift($items);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Returns the next x number of items in sequence from the given value as
1275
+	 * found in the database matching the given query conditions.
1276
+	 *
1277
+	 * @param mixed $current_field_value    Value used for the reference point.
1278
+	 * @param null  $field_to_order_by      What field is used for the
1279
+	 *                                      reference point.
1280
+	 * @param int   $limit                  How many to return.
1281
+	 * @param array $query_params           Extra conditions on the query.
1282
+	 * @param null  $columns_to_select      If left null, then an array of
1283
+	 *                                      EE_Base_Class objects is returned,
1284
+	 *                                      otherwise you can indicate just the
1285
+	 *                                      columns you want returned.
1286
+	 * @return EE_Base_Class[]|array
1287
+	 * @throws EE_Error
1288
+	 * @throws ReflectionException
1289
+	 */
1290
+	public function next_x(
1291
+		$current_field_value,
1292
+		$field_to_order_by = null,
1293
+		$limit = 1,
1294
+		$query_params = [],
1295
+		$columns_to_select = null
1296
+	) {
1297
+		return $this->_get_consecutive(
1298
+			$current_field_value,
1299
+			'>',
1300
+			$field_to_order_by,
1301
+			$limit,
1302
+			$query_params,
1303
+			$columns_to_select
1304
+		);
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * Returns the previous x number of items in sequence from the given value
1310
+	 * as found in the database matching the given query conditions.
1311
+	 *
1312
+	 * @param mixed $current_field_value    Value used for the reference point.
1313
+	 * @param null  $field_to_order_by      What field is used for the
1314
+	 *                                      reference point.
1315
+	 * @param int   $limit                  How many to return.
1316
+	 * @param array $query_params           Extra conditions on the query.
1317
+	 * @param null  $columns_to_select      If left null, then an array of
1318
+	 *                                      EE_Base_Class objects is returned,
1319
+	 *                                      otherwise you can indicate just the
1320
+	 *                                      columns you want returned.
1321
+	 * @return EE_Base_Class[]|array
1322
+	 * @throws EE_Error
1323
+	 * @throws ReflectionException
1324
+	 */
1325
+	public function previous_x(
1326
+		$current_field_value,
1327
+		$field_to_order_by = null,
1328
+		$limit = 1,
1329
+		$query_params = [],
1330
+		$columns_to_select = null
1331
+	) {
1332
+		return $this->_get_consecutive(
1333
+			$current_field_value,
1334
+			'<',
1335
+			$field_to_order_by,
1336
+			$limit,
1337
+			$query_params,
1338
+			$columns_to_select
1339
+		);
1340
+	}
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the next item in sequence from the given value as found in the
1345
+	 * database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed $current_field_value    Value used for the reference point.
1348
+	 * @param null  $field_to_order_by      What field is used for the
1349
+	 *                                      reference point.
1350
+	 * @param array $query_params           Extra conditions on the query.
1351
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1352
+	 *                                      object is returned, otherwise you
1353
+	 *                                      can indicate just the columns you
1354
+	 *                                      want and a single array indexed by
1355
+	 *                                      the columns will be returned.
1356
+	 * @return EE_Base_Class|null|array()
1357
+	 * @throws EE_Error
1358
+	 * @throws ReflectionException
1359
+	 */
1360
+	public function next(
1361
+		$current_field_value,
1362
+		$field_to_order_by = null,
1363
+		$query_params = [],
1364
+		$columns_to_select = null
1365
+	) {
1366
+		$results = $this->_get_consecutive(
1367
+			$current_field_value,
1368
+			'>',
1369
+			$field_to_order_by,
1370
+			1,
1371
+			$query_params,
1372
+			$columns_to_select
1373
+		);
1374
+		return empty($results)
1375
+			? null
1376
+			: reset($results);
1377
+	}
1378
+
1379
+
1380
+	/**
1381
+	 * Returns the previous item in sequence from the given value as found in
1382
+	 * the database matching the given query conditions.
1383
+	 *
1384
+	 * @param mixed $current_field_value    Value used for the reference point.
1385
+	 * @param null  $field_to_order_by      What field is used for the
1386
+	 *                                      reference point.
1387
+	 * @param array $query_params           Extra conditions on the query.
1388
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
+	 *                                      object is returned, otherwise you
1390
+	 *                                      can indicate just the columns you
1391
+	 *                                      want and a single array indexed by
1392
+	 *                                      the columns will be returned.
1393
+	 * @return EE_Base_Class|null|array()
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function previous(
1398
+		$current_field_value,
1399
+		$field_to_order_by = null,
1400
+		$query_params = [],
1401
+		$columns_to_select = null
1402
+	) {
1403
+		$results = $this->_get_consecutive(
1404
+			$current_field_value,
1405
+			'<',
1406
+			$field_to_order_by,
1407
+			1,
1408
+			$query_params,
1409
+			$columns_to_select
1410
+		);
1411
+		return empty($results)
1412
+			? null
1413
+			: reset($results);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Returns the a consecutive number of items in sequence from the given
1419
+	 * value as found in the database matching the given query conditions.
1420
+	 *
1421
+	 * @param mixed  $current_field_value   Value used for the reference point.
1422
+	 * @param string $operand               What operand is used for the sequence.
1423
+	 * @param string $field_to_order_by     What field is used for the reference point.
1424
+	 * @param int    $limit                 How many to return.
1425
+	 * @param array  $query_params          Extra conditions on the query.
1426
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1427
+	 *                                      otherwise you can indicate just the columns you want returned.
1428
+	 * @return EE_Base_Class[]|array
1429
+	 * @throws EE_Error
1430
+	 * @throws ReflectionException
1431
+	 */
1432
+	protected function _get_consecutive(
1433
+		$current_field_value,
1434
+		$operand = '>',
1435
+		$field_to_order_by = null,
1436
+		$limit = 1,
1437
+		$query_params = [],
1438
+		$columns_to_select = null
1439
+	) {
1440
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1441
+		if (empty($field_to_order_by)) {
1442
+			if ($this->has_primary_key_field()) {
1443
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1444
+			} else {
1445
+				if (defined('WP_DEBUG') && WP_DEBUG) {
1446
+					throw new EE_Error(
1447
+						esc_html__(
1448
+							'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).',
1449
+							'event_espresso'
1450
+						)
1451
+					);
1452
+				}
1453
+				EE_Error::add_error(
1454
+					esc_html__('There was an error with the query.', 'event_espresso'),
1455
+					__FILE__,
1456
+					__FUNCTION__,
1457
+					__LINE__
1458
+				);
1459
+				return [];
1460
+			}
1461
+		}
1462
+		if (! is_array($query_params)) {
1463
+			EE_Error::doing_it_wrong(
1464
+				'EEM_Base::_get_consecutive',
1465
+				sprintf(
1466
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1467
+					gettype($query_params)
1468
+				),
1469
+				'4.6.0'
1470
+			);
1471
+			$query_params = [];
1472
+		}
1473
+		// let's add the where query param for consecutive look up.
1474
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1475
+		$query_params['limit']                 = $limit;
1476
+		// set direction
1477
+		$incoming_orderby         = isset($query_params['order_by'])
1478
+			? (array) $query_params['order_by']
1479
+			: [];
1480
+		$query_params['order_by'] = $operand === '>'
1481
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1482
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1483
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1484
+		if (empty($columns_to_select)) {
1485
+			return $this->get_all($query_params);
1486
+		}
1487
+		// getting just the fields
1488
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1489
+	}
1490
+
1491
+
1492
+	/**
1493
+	 * This sets the _timezone property after model object has been instantiated.
1494
+	 *
1495
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1496
+	 * @throws Exception
1497
+	 */
1498
+	public function set_timezone(?string $timezone = '')
1499
+	{
1500
+		if (! $timezone) {
1501
+			return;
1502
+		}
1503
+		$this->_timezone = $timezone;
1504
+		// note we need to loop through relations and set the timezone on those objects as well.
1505
+		foreach ($this->_model_relations as $relation) {
1506
+			$relation->set_timezone($timezone);
1507
+		}
1508
+		// and finally we do the same for any datetime fields
1509
+		foreach ($this->_fields as $field) {
1510
+			if ($field instanceof EE_Datetime_Field) {
1511
+				$field->set_timezone($timezone);
1512
+			}
1513
+		}
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * This just returns whatever is set for the current timezone.
1519
+	 *
1520
+	 * @access public
1521
+	 * @return string
1522
+	 * @throws Exception
1523
+	 */
1524
+	public function get_timezone()
1525
+	{
1526
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1527
+		if (empty($this->_timezone)) {
1528
+			foreach ($this->_fields as $field) {
1529
+				if ($field instanceof EE_Datetime_Field) {
1530
+					$this->set_timezone($field->get_timezone());
1531
+					break;
1532
+				}
1533
+			}
1534
+		}
1535
+		// if timezone STILL empty then return the default timezone for the site.
1536
+		if (empty($this->_timezone)) {
1537
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1538
+		}
1539
+		return $this->_timezone;
1540
+	}
1541
+
1542
+
1543
+	/**
1544
+	 * This returns the date formats set for the given field name and also ensures that
1545
+	 * $this->_timezone property is set correctly.
1546
+	 *
1547
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1548
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1549
+	 * @return array formats in an array with the date format first, and the time format last.
1550
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1551
+	 * @since 4.6.x
1552
+	 */
1553
+	public function get_formats_for($field_name, $pretty = false)
1554
+	{
1555
+		$field_settings = $this->field_settings_for($field_name);
1556
+		// if not a valid EE_Datetime_Field then throw error
1557
+		if (! $field_settings instanceof EE_Datetime_Field) {
1558
+			throw new EE_Error(
1559
+				sprintf(
1560
+					esc_html__(
1561
+						'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.',
1562
+						'event_espresso'
1563
+					),
1564
+					$field_name
1565
+				)
1566
+			);
1567
+		}
1568
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1569
+		// the field.
1570
+		$this->_timezone = $field_settings->get_timezone();
1571
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1572
+	}
1573
+
1574
+
1575
+	/**
1576
+	 * This returns the current time in a format setup for a query on this model.
1577
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1578
+	 * it will return:
1579
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1580
+	 *  NOW
1581
+	 *  - or a unix timestamp (equivalent to time())
1582
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1583
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1584
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1585
+	 *
1586
+	 * @param string $field_name       The field the current time is needed for.
1587
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1588
+	 *                                 formatted string matching the set format for the field in the set timezone will
1589
+	 *                                 be returned.
1590
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1591
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1592
+	 *                                 exception is triggered.
1593
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1594
+	 * @throws Exception
1595
+	 * @since 4.6.x
1596
+	 */
1597
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1598
+	{
1599
+		$formats  = $this->get_formats_for($field_name);
1600
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1601
+		if ($timestamp) {
1602
+			return $DateTime->format('U');
1603
+		}
1604
+		// not returning timestamp, so return formatted string in timezone.
1605
+		switch ($what) {
1606
+			case 'time':
1607
+				return $DateTime->format($formats[1]);
1608
+			case 'date':
1609
+				return $DateTime->format($formats[0]);
1610
+			default:
1611
+				return $DateTime->format(implode(' ', $formats));
1612
+		}
1613
+	}
1614
+
1615
+
1616
+	/**
1617
+	 * This receives a time string for a given field and ensures
1618
+	 * that it is set up to match what the internal settings for the model are.
1619
+	 * Returns a DateTime object.
1620
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1621
+	 * (functionally the equivalent of UTC+0).
1622
+	 * So when you send it in, whatever timezone string you include is ignored.
1623
+	 *
1624
+	 * @param string      $field_name      The field being setup.
1625
+	 * @param string      $timestring      The date time string being used.
1626
+	 * @param string      $incoming_format The format for the time string.
1627
+	 * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1628
+	 *                                     the blog.  If this is not the case, then it can be specified here.  If
1629
+	 *                                     incoming format is
1630
+	 *                                     'U', this is ignored.
1631
+	 * @return DbSafeDateTime
1632
+	 * @throws EE_Error
1633
+	 * @throws Exception
1634
+	 */
1635
+	public function convert_datetime_for_query(
1636
+		string $field_name,
1637
+		string $timestring,
1638
+		string $incoming_format,
1639
+		?string $timezone_string = ''
1640
+	): DbSafeDateTime {
1641
+		// just using this to ensure the timezone is set correctly internally
1642
+		$this->get_formats_for($field_name);
1643
+		// load EEH_DTT_Helper
1644
+		$timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647
+		return DbSafeDateTime::createFromDateTime($incomingDateTime);
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1653
+	 *
1654
+	 * @return EE_Table_Base[]
1655
+	 */
1656
+	public function get_tables()
1657
+	{
1658
+		return $this->_tables;
1659
+	}
1660
+
1661
+
1662
+	/**
1663
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1664
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1665
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1666
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1667
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1668
+	 * model object with EVT_ID = 1
1669
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1670
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1671
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1672
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1673
+	 * are not specified)
1674
+	 *
1675
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1676
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1677
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1678
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1679
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1680
+	 *                                         ID=34, we'd use this method as follows:
1681
+	 *                                         EEM_Transaction::instance()->update(
1682
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1683
+	 *                                         array(array('TXN_ID'=>34)));
1684
+	 * @param array   $query_params            @see
1685
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1686
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1687
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1688
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1689
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1690
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1691
+	 *                                         TRUE, it is assumed that you've already called
1692
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1693
+	 *                                         malicious javascript. However, if
1694
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1695
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1696
+	 *                                         and every other field, before insertion. We provide this parameter
1697
+	 *                                         because model objects perform their prepare_for_set function on all
1698
+	 *                                         their values, and so don't need to be called again (and in many cases,
1699
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1700
+	 *                                         prepare_for_set method...)
1701
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1702
+	 *                                         in this model's entity map according to $fields_n_values that match
1703
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1704
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1705
+	 *                                         could get out-of-sync with the database
1706
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1707
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1708
+	 *                                         bad)
1709
+	 * @throws EE_Error
1710
+	 * @throws ReflectionException
1711
+	 */
1712
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713
+	{
1714
+		if (! is_array($query_params)) {
1715
+			EE_Error::doing_it_wrong(
1716
+				'EEM_Base::update',
1717
+				sprintf(
1718
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1719
+					gettype($query_params)
1720
+				),
1721
+				'4.6.0'
1722
+			);
1723
+			$query_params = [];
1724
+		}
1725
+		/**
1726
+		 * Action called before a model update call has been made.
1727
+		 *
1728
+		 * @param EEM_Base $model
1729
+		 * @param array    $fields_n_values the updated fields and their new values
1730
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1731
+		 */
1732
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1733
+		/**
1734
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1735
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1736
+		 *
1737
+		 * @param array    $fields_n_values fields and their new values
1738
+		 * @param EEM_Base $model           the model being queried
1739
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1740
+		 */
1741
+		$fields_n_values = (array) apply_filters(
1742
+			'FHEE__EEM_Base__update__fields_n_values',
1743
+			$fields_n_values,
1744
+			$this,
1745
+			$query_params
1746
+		);
1747
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1748
+		// to do that, for each table, verify that it's PK isn't null.
1749
+		$tables = $this->get_tables();
1750
+		// 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
1751
+		// NOTE: we should make this code more efficient by NOT querying twice
1752
+		// before the real update, but that needs to first go through ALPHA testing
1753
+		// as it's dangerous. says Mike August 8 2014
1754
+		// we want to make sure the default_where strategy is ignored
1755
+		$this->_ignore_where_strategy = true;
1756
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1757
+		foreach ($wpdb_select_results as $wpdb_result) {
1758
+			// type cast stdClass as array
1759
+			$wpdb_result = (array) $wpdb_result;
1760
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761
+			if ($this->has_primary_key_field()) {
1762
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1763
+			} else {
1764
+				// 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)
1765
+				$main_table_pk_value = null;
1766
+			}
1767
+			// 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
1768
+			// 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
1769
+			if (count($tables) > 1) {
1770
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1771
+				// in that table, and so we'll want to insert one
1772
+				foreach ($tables as $table_obj) {
1773
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1774
+					// if there is no private key for this table on the results, it means there's no entry
1775
+					// in this table, right? so insert a row in the current table, using any fields available
1776
+					if (
1777
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
+						   && $wpdb_result[ $this_table_pk_column ])
1779
+					) {
1780
+						$success = $this->_insert_into_specific_table(
1781
+							$table_obj,
1782
+							$fields_n_values,
1783
+							$main_table_pk_value
1784
+						);
1785
+						// if we died here, report the error
1786
+						if (! $success) {
1787
+							return false;
1788
+						}
1789
+					}
1790
+				}
1791
+			}
1792
+			//              //and now check that if we have cached any models by that ID on the model, that
1793
+			//              //they also get updated properly
1794
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1795
+			//              if( $model_object ){
1796
+			//                  foreach( $fields_n_values as $field => $value ){
1797
+			//                      $model_object->set($field, $value);
1798
+			// let's make sure default_where strategy is followed now
1799
+			$this->_ignore_where_strategy = false;
1800
+		}
1801
+		// if we want to keep model objects in sync, AND
1802
+		// if this wasn't called from a model object (to update itself)
1803
+		// then we want to make sure we keep all the existing
1804
+		// model objects in sync with the db
1805
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1806
+			if ($this->has_primary_key_field()) {
1807
+				$model_objs_affected_ids = $this->get_col($query_params);
1808
+			} else {
1809
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1810
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1811
+				$model_objs_affected_ids     = [];
1812
+				foreach ($models_affected_key_columns as $row) {
1813
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1814
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1815
+				}
1816
+			}
1817
+			if (! $model_objs_affected_ids) {
1818
+				// wait wait wait- if nothing was affected let's stop here
1819
+				return 0;
1820
+			}
1821
+			foreach ($model_objs_affected_ids as $id) {
1822
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1823
+				if ($model_obj_in_entity_map) {
1824
+					foreach ($fields_n_values as $field => $new_value) {
1825
+						$model_obj_in_entity_map->set($field, $new_value);
1826
+					}
1827
+				}
1828
+			}
1829
+			// if there is a primary key on this model, we can now do a slight optimization
1830
+			if ($this->has_primary_key_field()) {
1831
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1832
+				$query_params = [
1833
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1834
+					'limit'                    => count($model_objs_affected_ids),
1835
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1836
+				];
1837
+			}
1838
+		}
1839
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1840
+
1841
+		// note: the following query doesn't use _construct_2nd_half_of_select_query()
1842
+		// because it doesn't accept LIMIT, ORDER BY, etc.
1843
+		$rows_affected = $this->_do_wpdb_query(
1844
+			'query',
1845
+			[
1846
+				"UPDATE " . $model_query_info->get_full_join_sql()
1847
+				. " SET " . $this->_construct_update_sql($fields_n_values)
1848
+				. $model_query_info->get_where_sql(),
1849
+			]
1850
+		);
1851
+
1852
+		/**
1853
+		 * Action called after a model update call has been made.
1854
+		 *
1855
+		 * @param EEM_Base $model
1856
+		 * @param array    $fields_n_values the updated fields and their new values
1857
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1858
+		 * @param int      $rows_affected
1859
+		 */
1860
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
+		return $rows_affected;// how many supposedly got updated
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where the values
1867
+	 * are the values of the field specified (or by default the primary key field)
1868
+	 * that matched the query params. Note that you should pass the name of the
1869
+	 * model FIELD, not the database table's column name.
1870
+	 *
1871
+	 * @param array  $query_params 
1872
+	 * @param string $field_to_select
1873
+	 * @return array just like $wpdb->get_col()
1874
+	 * @throws EE_Error
1875
+	 * @throws ReflectionException
1876
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md for $query_params values
1877
+	 */
1878
+	public function get_col($query_params = [], $field_to_select = null)
1879
+	{
1880
+		if ($field_to_select) {
1881
+			$field = $this->field_settings_for($field_to_select);
1882
+		} elseif ($this->has_primary_key_field()) {
1883
+			$field = $this->get_primary_key_field();
1884
+		} else {
1885
+			$field_settings = $this->field_settings();
1886
+			// no primary key, just grab the first column
1887
+			$field = reset($field_settings);
1888
+			// don't need this array now
1889
+			unset($field_settings);
1890
+		}
1891
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892
+		$select_expressions = $field->get_qualified_column();
1893
+		$SQL                =
1894
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1895
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * Returns a single column value for a single row from the database
1901
+	 *
1902
+	 * @param array  $query_params    @see
1903
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1904
+	 * @param string $field_to_select @see EEM_Base::get_col()
1905
+	 * @return string
1906
+	 * @throws EE_Error
1907
+	 * @throws ReflectionException
1908
+	 */
1909
+	public function get_var($query_params = [], $field_to_select = null)
1910
+	{
1911
+		$query_params['limit'] = 1;
1912
+		$col                   = $this->get_col($query_params, $field_to_select);
1913
+		if (! empty($col)) {
1914
+			return reset($col);
1915
+		}
1916
+		return null;
1917
+	}
1918
+
1919
+
1920
+	/**
1921
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1922
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1923
+	 * injection, but currently no further filtering is done
1924
+	 *
1925
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1926
+	 *                               be updated to in the DB
1927
+	 * @return string of SQL
1928
+	 * @throws EE_Error
1929
+	 * @global      $wpdb
1930
+	 */
1931
+	public function _construct_update_sql($fields_n_values)
1932
+	{
1933
+		/** @type WPDB $wpdb */
1934
+		global $wpdb;
1935
+		$cols_n_values = [];
1936
+		foreach ($fields_n_values as $field_name => $value) {
1937
+			$field_obj = $this->field_settings_for($field_name);
1938
+			// if the value is NULL, we want to assign the value to that.
1939
+			// wpdb->prepare doesn't really handle that properly
1940
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1941
+			$value_sql       = $prepared_value === null
1942
+				? 'NULL'
1943
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1945
+		}
1946
+		return implode(",", $cols_n_values);
1947
+	}
1948
+
1949
+
1950
+	/**
1951
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1952
+	 * Performs a HARD delete, meaning the database row should always be removed,
1953
+	 * not just have a flag field on it switched
1954
+	 * Wrapper for EEM_Base::delete_permanently()
1955
+	 *
1956
+	 * @param mixed   $id
1957
+	 * @param boolean $allow_blocking
1958
+	 * @return int the number of rows deleted
1959
+	 * @throws EE_Error
1960
+	 * @throws ReflectionException
1961
+	 */
1962
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1963
+	{
1964
+		return $this->delete_permanently(
1965
+			[
1966
+				[$this->get_primary_key_field()->get_name() => $id],
1967
+				'limit' => 1,
1968
+			],
1969
+			$allow_blocking
1970
+		);
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1976
+	 * Wrapper for EEM_Base::delete()
1977
+	 *
1978
+	 * @param mixed   $id
1979
+	 * @param boolean $allow_blocking
1980
+	 * @return int the number of rows deleted
1981
+	 * @throws EE_Error
1982
+	 * @throws ReflectionException
1983
+	 */
1984
+	public function delete_by_ID($id, $allow_blocking = true)
1985
+	{
1986
+		return $this->delete(
1987
+			[
1988
+				[$this->get_primary_key_field()->get_name() => $id],
1989
+				'limit' => 1,
1990
+			],
1991
+			$allow_blocking
1992
+		);
1993
+	}
1994
+
1995
+
1996
+	/**
1997
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1998
+	 * meaning if the model has a field that indicates its been "trashed" or
1999
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
2000
+	 *
2001
+	 * @param array   $query_params
2002
+	 * @param boolean $allow_blocking
2003
+	 * @return int how many rows got deleted
2004
+	 * @throws EE_Error
2005
+	 * @throws ReflectionException
2006
+	 * @see EEM_Base::delete_permanently
2007
+	 */
2008
+	public function delete($query_params, $allow_blocking = true)
2009
+	{
2010
+		return $this->delete_permanently($query_params, $allow_blocking);
2011
+	}
2012
+
2013
+
2014
+	/**
2015
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
2016
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2017
+	 * as archived, not actually deleted
2018
+	 *
2019
+	 * @param array   $query_params   @see
2020
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2021
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
2022
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
2023
+	 *                                deletes regardless of other objects which may depend on it. Its generally
2024
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
2025
+	 *                                DB
2026
+	 * @return int how many rows got deleted
2027
+	 * @throws EE_Error
2028
+	 * @throws ReflectionException
2029
+	 */
2030
+	public function delete_permanently($query_params, $allow_blocking = true)
2031
+	{
2032
+		/**
2033
+		 * Action called just before performing a real deletion query. You can use the
2034
+		 * model and its $query_params to find exactly which items will be deleted
2035
+		 *
2036
+		 * @param EEM_Base $model
2037
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2038
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
2039
+		 *                                 to block (prevent) this deletion
2040
+		 */
2041
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
2042
+		// some MySQL databases may be running safe mode, which may restrict
2043
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2044
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2045
+		// to delete them
2046
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2047
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2048
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2049
+			$columns_and_ids_for_deleting
2050
+		);
2051
+		/**
2052
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2053
+		 *
2054
+		 * @param EEM_Base $this                            The model instance being acted on.
2055
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2056
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2057
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2058
+		 *                                                  derived from the incoming query parameters.
2059
+		 * @see details on the structure of this array in the phpdocs
2060
+		 *                                                  for the `_get_ids_for_delete_method`
2061
+		 */
2062
+		do_action(
2063
+			'AHEE__EEM_Base__delete__before_query',
2064
+			$this,
2065
+			$query_params,
2066
+			$allow_blocking,
2067
+			$columns_and_ids_for_deleting
2068
+		);
2069
+		$rows_deleted = 0;
2070
+		if ($deletion_where_query_part) {
2071
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2072
+			$table_aliases    = array_keys($this->_tables);
2073
+			$SQL              = "DELETE "
2074
+								. implode(", ", $table_aliases)
2075
+								. " FROM "
2076
+								. $model_query_info->get_full_join_sql()
2077
+								. " WHERE "
2078
+								. $deletion_where_query_part;
2079
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2080
+		}
2081
+
2082
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2083
+		// there was no error with the delete query.
2084
+		if (
2085
+			$this->has_primary_key_field()
2086
+			&& $rows_deleted !== false
2087
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2088
+		) {
2089
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2090
+			foreach ($ids_for_removal as $id) {
2091
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2092
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2093
+				}
2094
+			}
2095
+
2096
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2097
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2098
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2099
+			// (although it is possible).
2100
+			// Note this can be skipped by using the provided filter and returning false.
2101
+			if (
2102
+				apply_filters(
2103
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2104
+					! $this instanceof EEM_Extra_Meta,
2105
+					$this
2106
+				)
2107
+			) {
2108
+				EEM_Extra_Meta::instance()->delete_permanently(
2109
+					[
2110
+						0 => [
2111
+							'EXM_type' => $this->get_this_model_name(),
2112
+							'OBJ_ID'   => [
2113
+								'IN',
2114
+								$ids_for_removal,
2115
+							],
2116
+						],
2117
+					]
2118
+				);
2119
+			}
2120
+		}
2121
+
2122
+		/**
2123
+		 * Action called just after performing a real deletion query. Although at this point the
2124
+		 * items should have been deleted
2125
+		 *
2126
+		 * @param EEM_Base $model
2127
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2128
+		 * @param int      $rows_deleted
2129
+		 */
2130
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2131
+		return (int) $rows_deleted;// how many supposedly got deleted
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 * Checks all the relations that throw error messages when there are blocking related objects
2137
+	 * for related model objects. If there are any related model objects on those relations,
2138
+	 * adds an EE_Error, and return true
2139
+	 *
2140
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2141
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2142
+	 *                                                 should be ignored when determining whether there are related
2143
+	 *                                                 model objects which block this model object's deletion. Useful
2144
+	 *                                                 if you know A is related to B and are considering deleting A,
2145
+	 *                                                 but want to see if A has any other objects blocking its deletion
2146
+	 *                                                 before removing the relation between A and B
2147
+	 * @return boolean
2148
+	 * @throws EE_Error
2149
+	 * @throws ReflectionException
2150
+	 */
2151
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2152
+	{
2153
+		// first, if $ignore_this_model_obj was supplied, get its model
2154
+		$ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2155
+			? $ignore_this_model_obj->get_model()
2156
+			: null;
2157
+		// now check all the relations of $this_model_obj_or_id and see if there
2158
+		// are any related model objects blocking it?
2159
+		$is_blocked = false;
2160
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2161
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2162
+				// if $ignore_this_model_obj was supplied, then for the query
2163
+				// on that model needs to be told to ignore $ignore_this_model_obj
2164
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2165
+					$related_model_objects = $relation_obj->get_all_related(
2166
+						$this_model_obj_or_id,
2167
+						[
2168
+							[
2169
+								$ignored_model->get_primary_key_field()->get_name() => [
2170
+									'!=',
2171
+									$ignore_this_model_obj->ID(),
2172
+								],
2173
+							],
2174
+						]
2175
+					);
2176
+				} else {
2177
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2178
+				}
2179
+				if ($related_model_objects) {
2180
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2181
+					$is_blocked = true;
2182
+				}
2183
+			}
2184
+		}
2185
+		return $is_blocked;
2186
+	}
2187
+
2188
+
2189
+	/**
2190
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2191
+	 *
2192
+	 * @param array $row_results_for_deleting
2193
+	 * @param bool  $allow_blocking
2194
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2195
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2196
+	 *                              dimension array where the key is the fully qualified primary key column and the
2197
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2198
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2199
+	 *                              be a two dimensional array where each element is a group of columns and values that
2200
+	 *                              get deleted. Example: array(
2201
+	 *                              0 => array(
2202
+	 *                              'Term_Relationship.object_id' => 1
2203
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2204
+	 *                              ),
2205
+	 *                              1 => array(
2206
+	 *                              'Term_Relationship.object_id' => 1
2207
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2208
+	 *                              )
2209
+	 *                              )
2210
+	 * @throws EE_Error
2211
+	 * @throws ReflectionException
2212
+	 */
2213
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2214
+	{
2215
+		$ids_to_delete_indexed_by_column = [];
2216
+		if ($this->has_primary_key_field()) {
2217
+			$primary_table = $this->_get_main_table();
2218
+			// following lines are commented out because the variables were not being used
2219
+			// not deleting because unsure if calls were intentionally causing side effects
2220
+			// $primary_table_pk_field          =
2221
+			//     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2222
+			// $other_tables                    = $this->_get_other_tables();
2223
+			$ids_to_delete_indexed_by_column = $query = [];
2224
+			foreach ($row_results_for_deleting as $item_to_delete) {
2225
+				// before we mark this item for deletion,
2226
+				// make sure there's no related entities blocking its deletion (if we're checking)
2227
+				if (
2228
+					$allow_blocking
2229
+					&& $this->delete_is_blocked_by_related_models(
2230
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2231
+					)
2232
+				) {
2233
+					continue;
2234
+				}
2235
+				// primary table deletes
2236
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2237
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2238
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2239
+				}
2240
+			}
2241
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2242
+			$fields = $this->get_combined_primary_key_fields();
2243
+			foreach ($row_results_for_deleting as $item_to_delete) {
2244
+				$ids_to_delete_indexed_by_column_for_row = [];
2245
+				foreach ($fields as $cpk_field) {
2246
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2247
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2248
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2249
+					}
2250
+				}
2251
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2252
+			}
2253
+		} else {
2254
+			// so there's no primary key and no combined key...
2255
+			// sorry, can't help you
2256
+			throw new EE_Error(
2257
+				sprintf(
2258
+					esc_html__(
2259
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2260
+						"event_espresso"
2261
+					),
2262
+					get_class($this)
2263
+				)
2264
+			);
2265
+		}
2266
+		return $ids_to_delete_indexed_by_column;
2267
+	}
2268
+
2269
+
2270
+	/**
2271
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2272
+	 * the corresponding query_part for the query performing the delete.
2273
+	 *
2274
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2275
+	 * @return string
2276
+	 * @throws EE_Error
2277
+	 */
2278
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2279
+	{
2280
+		$query_part = '';
2281
+		if (empty($ids_to_delete_indexed_by_column)) {
2282
+			return $query_part;
2283
+		} elseif ($this->has_primary_key_field()) {
2284
+			$query = [];
2285
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2286
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2287
+			}
2288
+			$query_part = ! empty($query)
2289
+				? implode(' AND ', $query)
2290
+				: $query_part;
2291
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2292
+			$ways_to_identify_a_row = [];
2293
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2294
+				$values_for_each_combined_primary_key_for_a_row = [];
2295
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2296
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2297
+				}
2298
+				$ways_to_identify_a_row[] = '('
2299
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2300
+											. ')';
2301
+			}
2302
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2303
+		}
2304
+		return $query_part;
2305
+	}
2306
+
2307
+
2308
+	/**
2309
+	 * Gets the model field by the fully qualified name
2310
+	 *
2311
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2312
+	 * @return EE_Model_Field_Base
2313
+	 * @throws EE_Error
2314
+	 * @throws EE_Error
2315
+	 */
2316
+	public function get_field_by_column($qualified_column_name)
2317
+	{
2318
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2319
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2320
+				return $field_obj;
2321
+			}
2322
+		}
2323
+		throw new EE_Error(
2324
+			sprintf(
2325
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2326
+				$this->get_this_model_name(),
2327
+				$qualified_column_name
2328
+			)
2329
+		);
2330
+	}
2331
+
2332
+
2333
+	/**
2334
+	 * Count all the rows that match criteria the model query params.
2335
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2336
+	 * column
2337
+	 *
2338
+	 * @param array  $query_params   @see
2339
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2340
+	 * @param string $field_to_count field on model to count by (not column name)
2341
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2342
+	 *                               that by the setting $distinct to TRUE;
2343
+	 * @return int
2344
+	 * @throws EE_Error
2345
+	 * @throws ReflectionException
2346
+	 */
2347
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2348
+	{
2349
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2350
+		if ($field_to_count) {
2351
+			$field_obj       = $this->field_settings_for($field_to_count);
2352
+			$column_to_count = $field_obj->get_qualified_column();
2353
+		} elseif ($this->has_primary_key_field()) {
2354
+			$pk_field_obj    = $this->get_primary_key_field();
2355
+			$column_to_count = $pk_field_obj->get_qualified_column();
2356
+		} else {
2357
+			// there's no primary key
2358
+			// if we're counting distinct items, and there's no primary key,
2359
+			// we need to list out the columns for distinction;
2360
+			// otherwise we can just use star
2361
+			if ($distinct) {
2362
+				$columns_to_use = [];
2363
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2364
+					$columns_to_use[] = $field_obj->get_qualified_column();
2365
+				}
2366
+				$column_to_count = implode(',', $columns_to_use);
2367
+			} else {
2368
+				$column_to_count = '*';
2369
+			}
2370
+		}
2371
+		$column_to_count = $distinct
2372
+			? "DISTINCT " . $column_to_count
2373
+			: $column_to_count;
2374
+		$SQL             =
2375
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2376
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2377
+	}
2378
+
2379
+
2380
+	/**
2381
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2382
+	 *
2383
+	 * @param array  $query_params @see
2384
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2385
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2386
+	 * @return float
2387
+	 * @throws EE_Error
2388
+	 * @throws ReflectionException
2389
+	 */
2390
+	public function sum($query_params, $field_to_sum = null)
2391
+	{
2392
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2393
+		if ($field_to_sum) {
2394
+			$field_obj = $this->field_settings_for($field_to_sum);
2395
+		} else {
2396
+			$field_obj = $this->get_primary_key_field();
2397
+		}
2398
+		$column_to_count = $field_obj->get_qualified_column();
2399
+		$SQL             =
2400
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2401
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2402
+		$data_type       = $field_obj->get_wpdb_data_type();
2403
+		if ($data_type === '%d' || $data_type === '%s') {
2404
+			return (float) $return_value;
2405
+		}
2406
+		// must be %f
2407
+		return (float) $return_value;
2408
+	}
2409
+
2410
+
2411
+	/**
2412
+	 * Just calls the specified method on $wpdb with the given arguments
2413
+	 * Consolidates a little extra error handling code
2414
+	 *
2415
+	 * @param string $wpdb_method
2416
+	 * @param array  $arguments_to_provide
2417
+	 * @return mixed
2418
+	 * @throws EE_Error
2419
+	 * @global wpdb  $wpdb
2420
+	 */
2421
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2422
+	{
2423
+		// if we're in maintenance mode level 2, DON'T run any queries
2424
+		// because level 2 indicates the database needs updating and
2425
+		// is probably out of sync with the code
2426
+		if (DbStatus::isOffline()) {
2427
+			throw new RuntimeException(
2428
+				esc_html__(
2429
+					"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.",
2430
+					"event_espresso"
2431
+				)
2432
+			);
2433
+		}
2434
+		/** @type WPDB $wpdb */
2435
+		global $wpdb;
2436
+		if (! method_exists($wpdb, $wpdb_method)) {
2437
+			throw new DomainException(
2438
+				sprintf(
2439
+					esc_html__(
2440
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2441
+						'event_espresso'
2442
+					),
2443
+					$wpdb_method
2444
+				)
2445
+			);
2446
+		}
2447
+		$old_show_errors_value = $wpdb->show_errors;
2448
+		if (defined('WP_DEBUG') && WP_DEBUG) {
2449
+			$wpdb->show_errors(false);
2450
+		}
2451
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2452
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2453
+		if (defined('WP_DEBUG') && WP_DEBUG) {
2454
+			$wpdb->show_errors($old_show_errors_value);
2455
+			if (! empty($wpdb->last_error)) {
2456
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2457
+			}
2458
+			if ($result === false) {
2459
+				throw new EE_Error(
2460
+					sprintf(
2461
+						esc_html__(
2462
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2463
+							'event_espresso'
2464
+						),
2465
+						$wpdb_method,
2466
+						var_export($arguments_to_provide, true)
2467
+					)
2468
+				);
2469
+			}
2470
+		} elseif ($result === false) {
2471
+			EE_Error::add_error(
2472
+				sprintf(
2473
+					esc_html__(
2474
+						'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"',
2475
+						'event_espresso'
2476
+					),
2477
+					$wpdb_method,
2478
+					var_export($arguments_to_provide, true),
2479
+					$wpdb->last_error
2480
+				),
2481
+				__FILE__,
2482
+				__FUNCTION__,
2483
+				__LINE__
2484
+			);
2485
+		}
2486
+		return $result;
2487
+	}
2488
+
2489
+
2490
+	/**
2491
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2492
+	 * and if there's an error tries to verify the DB is correct. Uses
2493
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2494
+	 * we should try to fix the EE core db, the addons, or just give up
2495
+	 *
2496
+	 * @param string $wpdb_method
2497
+	 * @param array  $arguments_to_provide
2498
+	 * @return mixed
2499
+	 */
2500
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2501
+	{
2502
+		/** @type WPDB $wpdb */
2503
+		global $wpdb;
2504
+		$wpdb->last_error = null;
2505
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2506
+		// was there an error running the query? but we don't care on new activations
2507
+		// (we're going to setup the DB anyway on new activations)
2508
+		if (
2509
+			($result === false || ! empty($wpdb->last_error))
2510
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2511
+		) {
2512
+			switch (EEM_Base::$_db_verification_level) {
2513
+				case EEM_Base::db_verified_none:
2514
+					// let's double-check core's DB
2515
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2516
+					break;
2517
+				case EEM_Base::db_verified_core:
2518
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2519
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2520
+					break;
2521
+				case EEM_Base::db_verified_addons:
2522
+					// ummmm... you in trouble
2523
+					return $result;
2524
+			}
2525
+			if (! empty($error_message)) {
2526
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2527
+				trigger_error($error_message);
2528
+			}
2529
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2530
+		}
2531
+		return $result;
2532
+	}
2533
+
2534
+
2535
+	/**
2536
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2537
+	 * EEM_Base::$_db_verification_level
2538
+	 *
2539
+	 * @param string $wpdb_method
2540
+	 * @param array  $arguments_to_provide
2541
+	 * @return string
2542
+	 * @throws EE_Error
2543
+	 * @throws ReflectionException
2544
+	 */
2545
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2546
+	{
2547
+		/** @type WPDB $wpdb */
2548
+		global $wpdb;
2549
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2550
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2551
+		$error_message                    = sprintf(
2552
+			esc_html__(
2553
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2554
+				'event_espresso'
2555
+			),
2556
+			$wpdb->last_error,
2557
+			$wpdb_method,
2558
+			wp_json_encode($arguments_to_provide)
2559
+		);
2560
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2561
+		return $error_message;
2562
+	}
2563
+
2564
+
2565
+	/**
2566
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2567
+	 * EEM_Base::$_db_verification_level
2568
+	 *
2569
+	 * @param $wpdb_method
2570
+	 * @param $arguments_to_provide
2571
+	 * @return string
2572
+	 * @throws EE_Error
2573
+	 * @throws ReflectionException
2574
+	 */
2575
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2576
+	{
2577
+		/** @type WPDB $wpdb */
2578
+		global $wpdb;
2579
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2580
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2581
+		$error_message                    = sprintf(
2582
+			esc_html__(
2583
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2584
+				'event_espresso'
2585
+			),
2586
+			$wpdb->last_error,
2587
+			$wpdb_method,
2588
+			wp_json_encode($arguments_to_provide)
2589
+		);
2590
+		EE_System::instance()->initialize_addons();
2591
+		return $error_message;
2592
+	}
2593
+
2594
+
2595
+	/**
2596
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2597
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2598
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2599
+	 * ..."
2600
+	 *
2601
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2602
+	 * @return string
2603
+	 */
2604
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2605
+	{
2606
+		return " FROM " . $model_query_info->get_full_join_sql() .
2607
+			   $model_query_info->get_where_sql() .
2608
+			   $model_query_info->get_group_by_sql() .
2609
+			   $model_query_info->get_having_sql() .
2610
+			   $model_query_info->get_order_by_sql() .
2611
+			   $model_query_info->get_limit_sql();
2612
+	}
2613
+
2614
+
2615
+	/**
2616
+	 * Set to easily debug the next X queries ran from this model.
2617
+	 *
2618
+	 * @param int $count
2619
+	 */
2620
+	public function show_next_x_db_queries($count = 1)
2621
+	{
2622
+		$this->_show_next_x_db_queries = $count;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * @param $sql_query
2628
+	 */
2629
+	public function show_db_query_if_previously_requested($sql_query)
2630
+	{
2631
+		if ($this->_show_next_x_db_queries > 0) {
2632
+			$left = is_admin() ? '12rem' : '2rem';
2633
+			echo "
2634 2634
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2635 2635
                 " . esc_html($sql_query) . "
2636 2636
             </div>";
2637
-            $this->_show_next_x_db_queries--;
2638
-        }
2639
-    }
2640
-
2641
-
2642
-    /**
2643
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2644
-     * There are the 3 cases:
2645
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2646
-     * $otherModelObject has no ID, it is first saved.
2647
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2648
-     * has no ID, it is first saved.
2649
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2650
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2651
-     * join table
2652
-     *
2653
-     * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2654
-     * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2655
-     * @param string            $relationName                     , key in EEM_Base::_relations
2656
-     *                                                            an attendee to a group, you also want to specify
2657
-     *                                                            which role they will have in that group. So you would
2658
-     *                                                            use this parameter to specify
2659
-     *                                                            array('role-column-name'=>'role-id')
2660
-     * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2661
-     *                                                            relation to for relation to methods that allow you to
2662
-     *                                                            further specify extra columns to join by (such as
2663
-     *                                                            HABTM).  Keep in mind that the only acceptable
2664
-     *                                                            query_params is strict "col" => "value" pairs because
2665
-     *                                                            these will be inserted in any new rows created as
2666
-     *                                                            well.
2667
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function add_relationship_to(
2671
-        $id_or_obj,
2672
-        $other_model_id_or_obj,
2673
-        $relationName,
2674
-        $extra_join_model_fields_n_values = []
2675
-    ) {
2676
-        $relation_obj = $this->related_settings_for($relationName);
2677
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2678
-    }
2679
-
2680
-
2681
-    /**
2682
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2683
-     * There are the 3 cases:
2684
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2685
-     * error
2686
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2687
-     * an error
2688
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2689
-     *
2690
-     * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2691
-     * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2692
-     * @param string            $relationName          key in EEM_Base::_relations
2693
-     * @param array|null        $where_query           This allows you to enter further query params for the relation
2694
-     *                                                 to for relation to methods that allow you to further specify
2695
-     *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2696
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2697
-     *                                                 because these will be inserted in any new rows created as well.
2698
-     * @return EE_Base_Class
2699
-     * @throws EE_Error
2700
-     */
2701
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2702
-    {
2703
-        $relation_obj = $this->related_settings_for($relationName);
2704
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2705
-    }
2706
-
2707
-
2708
-    /**
2709
-     * @param mixed       $id_or_obj
2710
-     * @param string      $relationName
2711
-     * @param array|null  $where_query_params
2712
-     * @return EE_Base_Class[]
2713
-     * @throws EE_Error
2714
-     * @throws ReflectionException
2715
-     */
2716
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2717
-    {
2718
-        $relation_obj = $this->related_settings_for($relationName);
2719
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2720
-    }
2721
-
2722
-
2723
-    /**
2724
-     * Gets all the related items of the specified $model_name, using $query_params.
2725
-     * Note: by default, we remove the "default query params"
2726
-     * because we want to get even deleted items etc.
2727
-     *
2728
-     * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2729
-     * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2730
-     * @param array|null  $query_params @see
2731
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
-     * @return EE_Base_Class[]
2733
-     * @throws EE_Error
2734
-     * @throws ReflectionException
2735
-     */
2736
-    public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2737
-    {
2738
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2739
-        $relation_settings = $this->related_settings_for($model_name);
2740
-        return $relation_settings->get_all_related($model_obj, $query_params);
2741
-    }
2742
-
2743
-
2744
-    /**
2745
-     * Deletes all the model objects across the relation indicated by $model_name
2746
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2747
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2748
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2749
-     *
2750
-     * @param EE_Base_Class|int|string $id_or_obj
2751
-     * @param string                   $model_name
2752
-     * @param array|null               $query_params
2753
-     * @return int how many deleted
2754
-     * @throws EE_Error
2755
-     * @throws ReflectionException
2756
-     */
2757
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2758
-    {
2759
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2760
-        $relation_settings = $this->related_settings_for($model_name);
2761
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2762
-    }
2763
-
2764
-
2765
-    /**
2766
-     * Hard deletes all the model objects across the relation indicated by $model_name
2767
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2768
-     * the model objects can't be hard deleted because of blocking related model objects,
2769
-     * just does a soft-delete on them instead.
2770
-     *
2771
-     * @param EE_Base_Class|int|string $id_or_obj
2772
-     * @param string                   $model_name
2773
-     * @param array|null               $query_params
2774
-     * @return int how many deleted
2775
-     * @throws EE_Error
2776
-     * @throws ReflectionException
2777
-     */
2778
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2779
-    {
2780
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2781
-        $relation_settings = $this->related_settings_for($model_name);
2782
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2783
-    }
2784
-
2785
-
2786
-    /**
2787
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2788
-     * unless otherwise specified in the $query_params
2789
-     *
2790
-     * @param EE_Base_Class|int|string $id_or_obj
2791
-     * @param string                   $model_name     like 'Event', or 'Registration'
2792
-     * @param array|null               $query_params   @see
2793
-     *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2794
-     * @param string                   $field_to_count name of field to count by. By default, uses primary key
2795
-     * @param bool                     $distinct       if we want to only count the distinct values for the column then
2796
-     *                                                 you can trigger that by the setting $distinct to TRUE;
2797
-     * @return int
2798
-     * @throws EE_Error
2799
-     * @throws ReflectionException
2800
-     */
2801
-    public function count_related(
2802
-        $id_or_obj,
2803
-        $model_name,
2804
-        $query_params = [],
2805
-        $field_to_count = null,
2806
-        $distinct = false
2807
-    ) {
2808
-        $related_model = $this->get_related_model_obj($model_name);
2809
-        // we're just going to use the query params on the related model's normal get_all query,
2810
-        // except add a condition to say to match the current mod
2811
-        if (! isset($query_params['default_where_conditions'])) {
2812
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2813
-        }
2814
-        $this_model_name                                                 = $this->get_this_model_name();
2815
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2816
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2817
-        return $related_model->count($query_params, $field_to_count, $distinct);
2818
-    }
2819
-
2820
-
2821
-    /**
2822
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2823
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2824
-     *
2825
-     * @param EE_Base_Class|int|string $id_or_obj
2826
-     * @param string                   $model_name   like 'Event', or 'Registration'
2827
-     * @param array|null               $query_params @see
2828
-     *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2829
-     * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2830
-     * @return float
2831
-     * @throws EE_Error
2832
-     * @throws ReflectionException
2833
-     */
2834
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2835
-    {
2836
-        $related_model = $this->get_related_model_obj($model_name);
2837
-        if (! is_array($query_params)) {
2838
-            EE_Error::doing_it_wrong(
2839
-                'EEM_Base::sum_related',
2840
-                sprintf(
2841
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2842
-                    gettype($query_params)
2843
-                ),
2844
-                '4.6.0'
2845
-            );
2846
-            $query_params = [];
2847
-        }
2848
-        // we're just going to use the query params on the related model's normal get_all query,
2849
-        // except add a condition to say to match the current mod
2850
-        if (! isset($query_params['default_where_conditions'])) {
2851
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2852
-        }
2853
-        $this_model_name                                                 = $this->get_this_model_name();
2854
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2855
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2856
-        return $related_model->sum($query_params, $field_to_sum);
2857
-    }
2858
-
2859
-
2860
-    /**
2861
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2862
-     * $modelObject
2863
-     *
2864
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2865
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2866
-     * @param array|null          $query_params     @see
2867
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2868
-     * @return EE_Base_Class
2869
-     * @throws EE_Error
2870
-     * @throws ReflectionException
2871
-     */
2872
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2873
-    {
2874
-        $query_params['limit'] = 1;
2875
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2876
-        if ($results) {
2877
-            return array_shift($results);
2878
-        }
2879
-        return null;
2880
-    }
2881
-
2882
-
2883
-    /**
2884
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2885
-     *
2886
-     * @return string
2887
-     */
2888
-    public function get_this_model_name()
2889
-    {
2890
-        return str_replace("EEM_", "", get_class($this));
2891
-    }
2892
-
2893
-
2894
-    /**
2895
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2896
-     *
2897
-     * @return EE_Any_Foreign_Model_Name_Field
2898
-     * @throws EE_Error
2899
-     */
2900
-    public function get_field_containing_related_model_name()
2901
-    {
2902
-        foreach ($this->field_settings(true) as $field) {
2903
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2904
-                $field_with_model_name = $field;
2905
-            }
2906
-        }
2907
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2908
-            throw new EE_Error(
2909
-                sprintf(
2910
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2911
-                    $this->get_this_model_name()
2912
-                )
2913
-            );
2914
-        }
2915
-        return $field_with_model_name;
2916
-    }
2917
-
2918
-
2919
-    /**
2920
-     * Inserts a new entry into the database, for each table.
2921
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2922
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2923
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2924
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2925
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2926
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2927
-     *
2928
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2929
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2930
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2931
-     *                              of EEM_Base)
2932
-     * @return int|string new primary key on main table that got inserted
2933
-     * @throws EE_Error
2934
-     * @throws ReflectionException
2935
-     */
2936
-    public function insert($field_n_values)
2937
-    {
2938
-        /**
2939
-         * Filters the fields and their values before inserting an item using the models
2940
-         *
2941
-         * @param array    $fields_n_values keys are the fields and values are their new values
2942
-         * @param EEM_Base $model           the model used
2943
-         */
2944
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2945
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2946
-            $main_table = $this->_get_main_table();
2947
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2948
-            if ($new_id !== false) {
2949
-                foreach ($this->_get_other_tables() as $other_table) {
2950
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2951
-                }
2952
-            }
2953
-            /**
2954
-             * Done just after attempting to insert a new model object
2955
-             *
2956
-             * @param EEM_Base $model           used
2957
-             * @param array    $fields_n_values fields and their values
2958
-             * @param int|string the              ID of the newly-inserted model object
2959
-             */
2960
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2961
-            return $new_id;
2962
-        }
2963
-        return false;
2964
-    }
2965
-
2966
-
2967
-    /**
2968
-     * Checks that the result would satisfy the unique indexes on this model
2969
-     *
2970
-     * @param array  $field_n_values
2971
-     * @param string $action
2972
-     * @return boolean
2973
-     * @throws EE_Error
2974
-     * @throws ReflectionException
2975
-     */
2976
-    protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2977
-    {
2978
-        foreach ($this->unique_indexes() as $index_name => $index) {
2979
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2980
-            if ($this->exists([$uniqueness_where_params])) {
2981
-                EE_Error::add_error(
2982
-                    sprintf(
2983
-                        esc_html__(
2984
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2985
-                            "event_espresso"
2986
-                        ),
2987
-                        $action,
2988
-                        $this->_get_class_name(),
2989
-                        $index_name,
2990
-                        implode(",", $index->field_names()),
2991
-                        http_build_query($uniqueness_where_params)
2992
-                    ),
2993
-                    __FILE__,
2994
-                    __FUNCTION__,
2995
-                    __LINE__
2996
-                );
2997
-                return false;
2998
-            }
2999
-        }
3000
-        return true;
3001
-    }
3002
-
3003
-
3004
-    /**
3005
-     * Checks the database for an item that conflicts (ie, if this item were
3006
-     * saved to the DB would break some uniqueness requirement, like a primary key
3007
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
3008
-     * can be either an EE_Base_Class or an array of fields n values
3009
-     *
3010
-     * @param EE_Base_Class|array $obj_or_fields_array
3011
-     * @param boolean             $include_primary_key whether to use the model object's primary key
3012
-     *                                                 when looking for conflicts
3013
-     *                                                 (ie, if false, we ignore the model object's primary key
3014
-     *                                                 when finding "conflicts". If true, it's also considered).
3015
-     *                                                 Only works for INT primary key,
3016
-     *                                                 STRING primary keys cannot be ignored
3017
-     * @return EE_Base_Class|array
3018
-     * @throws EE_Error
3019
-     * @throws ReflectionException
3020
-     */
3021
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3022
-    {
3023
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
3024
-            $fields_n_values = $obj_or_fields_array->model_field_array();
3025
-        } elseif (is_array($obj_or_fields_array)) {
3026
-            $fields_n_values = $obj_or_fields_array;
3027
-        } else {
3028
-            throw new EE_Error(
3029
-                sprintf(
3030
-                    esc_html__(
3031
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3032
-                        "event_espresso"
3033
-                    ),
3034
-                    get_class($this),
3035
-                    $obj_or_fields_array
3036
-                )
3037
-            );
3038
-        }
3039
-        $query_params = [];
3040
-        if (
3041
-            $this->has_primary_key_field()
3042
-            && ($include_primary_key
3043
-                || $this->get_primary_key_field()
3044
-                   instanceof
3045
-                   EE_Primary_Key_String_Field)
3046
-            && isset($fields_n_values[ $this->primary_key_name() ])
3047
-        ) {
3048
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3049
-        }
3050
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3051
-            $uniqueness_where_params                              =
3052
-                array_intersect_key($fields_n_values, $unique_index->fields());
3053
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3054
-        }
3055
-        // if there is nothing to base this search on, then we shouldn't find anything
3056
-        if (empty($query_params)) {
3057
-            return [];
3058
-        }
3059
-        return $this->get_one($query_params);
3060
-    }
3061
-
3062
-
3063
-    /**
3064
-     * Like count, but is optimized and returns a boolean instead of an int
3065
-     *
3066
-     * @param array $query_params
3067
-     * @return boolean
3068
-     * @throws EE_Error
3069
-     * @throws ReflectionException
3070
-     */
3071
-    public function exists($query_params)
3072
-    {
3073
-        $query_params['limit'] = 1;
3074
-        return $this->count($query_params) > 0;
3075
-    }
3076
-
3077
-
3078
-    /**
3079
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3080
-     *
3081
-     * @param int|string $id
3082
-     * @return boolean
3083
-     * @throws EE_Error
3084
-     * @throws ReflectionException
3085
-     */
3086
-    public function exists_by_ID($id)
3087
-    {
3088
-        return $this->exists(
3089
-            [
3090
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3091
-                [
3092
-                    $this->primary_key_name() => $id,
3093
-                ],
3094
-            ]
3095
-        );
3096
-    }
3097
-
3098
-
3099
-    /**
3100
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3101
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3102
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3103
-     * on the main table)
3104
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3105
-     * cases where we want to call it directly rather than via insert().
3106
-     *
3107
-     * @access   protected
3108
-     * @param EE_Table_Base $table
3109
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3110
-     *                                       float
3111
-     * @param int           $new_id          for now we assume only int keys
3112
-     * @return int ID of new row inserted, or FALSE on failure
3113
-     * @throws EE_Error
3114
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3115
-     */
3116
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3117
-    {
3118
-        global $wpdb;
3119
-        $insertion_col_n_values = [];
3120
-        $format_for_insertion   = [];
3121
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3122
-        foreach ($fields_on_table as $field_obj) {
3123
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3124
-            if ($field_obj->is_auto_increment()) {
3125
-                continue;
3126
-            }
3127
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3128
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3129
-            if ($prepared_value !== null) {
3130
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3131
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3132
-            }
3133
-        }
3134
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3135
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3136
-            // so add the fk to the main table as a column
3137
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3138
-            $format_for_insertion[]                              =
3139
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3140
-        }
3141
-
3142
-        // insert the new entry
3143
-        $result = $this->_do_wpdb_query(
3144
-            'insert',
3145
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3146
-        );
3147
-        if ($result === false) {
3148
-            return false;
3149
-        }
3150
-        // ok, now what do we return for the ID of the newly-inserted thing?
3151
-        if ($this->has_primary_key_field()) {
3152
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3153
-                return $wpdb->insert_id;
3154
-            }
3155
-            // it's not an auto-increment primary key, so
3156
-            // it must have been supplied
3157
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3158
-        }
3159
-        // we can't return a  primary key because there is none. instead return
3160
-        // a unique string indicating this model
3161
-        return $this->get_index_primary_key_string($fields_n_values);
3162
-    }
3163
-
3164
-
3165
-    /**
3166
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3167
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3168
-     * and there is no default, we pass it along. WPDB will take care of it)
3169
-     *
3170
-     * @param EE_Model_Field_Base $field_obj
3171
-     * @param array               $fields_n_values
3172
-     * @return mixed string|int|float depending on what the table column will be expecting
3173
-     * @throws EE_Error
3174
-     */
3175
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3176
-    {
3177
-        $field_name = $field_obj->get_name();
3178
-        // if this field doesn't allow nullable, don't allow it
3179
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3180
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3181
-        }
3182
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3183
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3184
-    }
3185
-
3186
-
3187
-    /**
3188
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3189
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3190
-     * the field's prepare_for_set() method.
3191
-     *
3192
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3193
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3194
-     *                                   top of file)
3195
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3196
-     *                                   $value is a custom selection
3197
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3198
-     */
3199
-    private function _prepare_value_for_use_in_db($value, $field)
3200
-    {
3201
-        if ($field instanceof EE_Model_Field_Base) {
3202
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3203
-            switch ($this->_values_already_prepared_by_model_object) {
3204
-                /** @noinspection PhpMissingBreakStatementInspection */
3205
-                case self::not_prepared_by_model_object:
3206
-                    $value = $field->prepare_for_set($value);
3207
-                // purposefully left out "return"
3208
-                // no break
3209
-                case self::prepared_by_model_object:
3210
-                    /** @noinspection SuspiciousAssignmentsInspection */
3211
-                    $value = $field->prepare_for_use_in_db($value);
3212
-                // no break
3213
-                case self::prepared_for_use_in_db:
3214
-                    // leave the value alone
3215
-            }
3216
-            // phpcs:enable
3217
-        }
3218
-        return $value;
3219
-    }
3220
-
3221
-
3222
-    /**
3223
-     * Returns the main table on this model
3224
-     *
3225
-     * @return EE_Primary_Table
3226
-     * @throws EE_Error
3227
-     */
3228
-    protected function _get_main_table()
3229
-    {
3230
-        foreach ($this->_tables as $table) {
3231
-            if ($table instanceof EE_Primary_Table) {
3232
-                return $table;
3233
-            }
3234
-        }
3235
-        throw new EE_Error(
3236
-            sprintf(
3237
-                esc_html__(
3238
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3239
-                    'event_espresso'
3240
-                ),
3241
-                get_class($this)
3242
-            )
3243
-        );
3244
-    }
3245
-
3246
-
3247
-    /**
3248
-     * table
3249
-     * returns EE_Primary_Table table name
3250
-     *
3251
-     * @return string
3252
-     * @throws EE_Error
3253
-     */
3254
-    public function table()
3255
-    {
3256
-        return $this->_get_main_table()->get_table_name();
3257
-    }
3258
-
3259
-
3260
-    /**
3261
-     * table
3262
-     * returns first EE_Secondary_Table table name
3263
-     *
3264
-     * @return string
3265
-     */
3266
-    public function second_table()
3267
-    {
3268
-        // grab second table from tables array
3269
-        $second_table = end($this->_tables);
3270
-        return $second_table instanceof EE_Secondary_Table
3271
-            ? $second_table->get_table_name()
3272
-            : null;
3273
-    }
3274
-
3275
-
3276
-    /**
3277
-     * get_table_obj_by_alias
3278
-     * returns table name given it's alias
3279
-     *
3280
-     * @param string $table_alias
3281
-     * @return EE_Primary_Table | EE_Secondary_Table
3282
-     */
3283
-    public function get_table_obj_by_alias($table_alias = '')
3284
-    {
3285
-        return $this->_tables[ $table_alias ] ?? null;
3286
-    }
3287
-
3288
-
3289
-    /**
3290
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3291
-     *
3292
-     * @return EE_Secondary_Table[]
3293
-     */
3294
-    protected function _get_other_tables()
3295
-    {
3296
-        $other_tables = [];
3297
-        foreach ($this->_tables as $table_alias => $table) {
3298
-            if ($table instanceof EE_Secondary_Table) {
3299
-                $other_tables[ $table_alias ] = $table;
3300
-            }
3301
-        }
3302
-        return $other_tables;
3303
-    }
3304
-
3305
-
3306
-    /**
3307
-     * Finds all the fields that correspond to the given table
3308
-     *
3309
-     * @param string $table_alias , array key in EEM_Base::_tables
3310
-     * @return EE_Model_Field_Base[]
3311
-     */
3312
-    public function _get_fields_for_table($table_alias)
3313
-    {
3314
-        return $this->_fields[ $table_alias ];
3315
-    }
3316
-
3317
-
3318
-    /**
3319
-     * Recurses through all the where parameters, and finds all the related models we'll need
3320
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3321
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3322
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3323
-     * related Registration, Transaction, and Payment models.
3324
-     *
3325
-     * @param array $query_params @see
3326
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3327
-     * @return EE_Model_Query_Info_Carrier
3328
-     * @throws EE_Error
3329
-     */
3330
-    public function _extract_related_models_from_query($query_params)
3331
-    {
3332
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3333
-        if (array_key_exists(0, $query_params)) {
3334
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3335
-        }
3336
-        if (array_key_exists('group_by', $query_params)) {
3337
-            if (is_array($query_params['group_by'])) {
3338
-                $this->_extract_related_models_from_sub_params_array_values(
3339
-                    $query_params['group_by'],
3340
-                    $query_info_carrier,
3341
-                    'group_by'
3342
-                );
3343
-            } elseif (! empty($query_params['group_by'])) {
3344
-                $this->_extract_related_model_info_from_query_param(
3345
-                    $query_params['group_by'],
3346
-                    $query_info_carrier,
3347
-                    'group_by'
3348
-                );
3349
-            }
3350
-        }
3351
-        if (array_key_exists('having', $query_params)) {
3352
-            $this->_extract_related_models_from_sub_params_array_keys(
3353
-                $query_params[0],
3354
-                $query_info_carrier,
3355
-                'having'
3356
-            );
3357
-        }
3358
-        if (array_key_exists('order_by', $query_params)) {
3359
-            if (is_array($query_params['order_by'])) {
3360
-                $this->_extract_related_models_from_sub_params_array_keys(
3361
-                    $query_params['order_by'],
3362
-                    $query_info_carrier,
3363
-                    'order_by'
3364
-                );
3365
-            } elseif (! empty($query_params['order_by'])) {
3366
-                $this->_extract_related_model_info_from_query_param(
3367
-                    $query_params['order_by'],
3368
-                    $query_info_carrier,
3369
-                    'order_by'
3370
-                );
3371
-            }
3372
-        }
3373
-        if (array_key_exists('force_join', $query_params)) {
3374
-            $this->_extract_related_models_from_sub_params_array_values(
3375
-                $query_params['force_join'],
3376
-                $query_info_carrier,
3377
-                'force_join'
3378
-            );
3379
-        }
3380
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3381
-        return $query_info_carrier;
3382
-    }
3383
-
3384
-
3385
-    /**
3386
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3387
-     *
3388
-     * @param array                       $sub_query_params
3389
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3390
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3391
-     * @return EE_Model_Query_Info_Carrier
3392
-     * @throws EE_Error
3393
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3394
-     */
3395
-    private function _extract_related_models_from_sub_params_array_keys(
3396
-        $sub_query_params,
3397
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3398
-        $query_param_type
3399
-    ) {
3400
-        if (! empty($sub_query_params)) {
3401
-            $sub_query_params = (array) $sub_query_params;
3402
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3403
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
-                $this->_extract_related_model_info_from_query_param(
3405
-                    $param,
3406
-                    $model_query_info_carrier,
3407
-                    $query_param_type
3408
-                );
3409
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3410
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3411
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3412
-                // of array('Registration.TXN_ID'=>23)
3413
-                $query_param_sans_stars =
3414
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3415
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3416
-                    if (! is_array($possibly_array_of_params)) {
3417
-                        throw new EE_Error(
3418
-                            sprintf(
3419
-                                esc_html__(
3420
-                                    "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'))",
3421
-                                    "event_espresso"
3422
-                                ),
3423
-                                $param,
3424
-                                $possibly_array_of_params
3425
-                            )
3426
-                        );
3427
-                    }
3428
-                    $this->_extract_related_models_from_sub_params_array_keys(
3429
-                        $possibly_array_of_params,
3430
-                        $model_query_info_carrier,
3431
-                        $query_param_type
3432
-                    );
3433
-                } elseif (
3434
-                    $query_param_type === 0 // ie WHERE
3435
-                    && is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3436
-                    && isset($possibly_array_of_params[2])
3437
-                    && $possibly_array_of_params[2]
3438
-                ) {
3439
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3440
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3441
-                    // from which we should extract query parameters!
3442
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3443
-                        throw new EE_Error(
3444
-                            sprintf(
3445
-                                esc_html__(
3446
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3447
-                                    "event_espresso"
3448
-                                ),
3449
-                                $query_param_type,
3450
-                                implode(",", $possibly_array_of_params)
3451
-                            )
3452
-                        );
3453
-                    }
3454
-                    $this->_extract_related_model_info_from_query_param(
3455
-                        $possibly_array_of_params[1],
3456
-                        $model_query_info_carrier,
3457
-                        $query_param_type
3458
-                    );
3459
-                }
3460
-            }
3461
-        }
3462
-        return $model_query_info_carrier;
3463
-    }
3464
-
3465
-
3466
-    /**
3467
-     * For extracting related models from forced_joins, where the array values contain the info about what
3468
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3469
-     *
3470
-     * @param array                       $sub_query_params @see
3471
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3472
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3473
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3474
-     * @return EE_Model_Query_Info_Carrier
3475
-     * @throws EE_Error
3476
-     */
3477
-    private function _extract_related_models_from_sub_params_array_values(
3478
-        $sub_query_params,
3479
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3480
-        $query_param_type
3481
-    ) {
3482
-        if (! empty($sub_query_params)) {
3483
-            if (! is_array($sub_query_params)) {
3484
-                throw new EE_Error(
3485
-                    sprintf(
3486
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3487
-                        $sub_query_params
3488
-                    )
3489
-                );
3490
-            }
3491
-            foreach ($sub_query_params as $param) {
3492
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3493
-                $this->_extract_related_model_info_from_query_param(
3494
-                    $param,
3495
-                    $model_query_info_carrier,
3496
-                    $query_param_type
3497
-                );
3498
-            }
3499
-        }
3500
-        return $model_query_info_carrier;
3501
-    }
3502
-
3503
-
3504
-    /**
3505
-     * Extract all the query parts from  model query params
3506
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3507
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3508
-     * but use them in a different order. Eg, we need to know what models we are querying
3509
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3510
-     * other models before we can finalize the where clause SQL.
3511
-     *
3512
-     * @param array $query_params
3513
-     * @return EE_Model_Query_Info_Carrier
3514
-     * @throws EE_Error
3515
-     * @throws ModelConfigurationException
3516
-     * @throws ReflectionException
3517
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3518
-     */
3519
-    public function _create_model_query_info_carrier($query_params)
3520
-    {
3521
-        if (! is_array($query_params)) {
3522
-            EE_Error::doing_it_wrong(
3523
-                'EEM_Base::_create_model_query_info_carrier',
3524
-                sprintf(
3525
-                    esc_html__(
3526
-                        '$query_params should be an array, you passed a variable of type %s',
3527
-                        'event_espresso'
3528
-                    ),
3529
-                    gettype($query_params)
3530
-                ),
3531
-                '4.6.0'
3532
-            );
3533
-            $query_params = [];
3534
-        }
3535
-        $query_params[0] = $query_params[0] ?? [];
3536
-        // first check if we should alter the query to account for caps or not
3537
-        // because the caps might require us to do extra joins
3538
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3539
-            $query_params[0] = array_replace_recursive(
3540
-                $query_params[0],
3541
-                $this->caps_where_conditions($query_params['caps'])
3542
-            );
3543
-        }
3544
-
3545
-        // check if we should alter the query to remove data related to protected
3546
-        // custom post types
3547
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3548
-            $where_param_key_for_password = $this->modelChainAndPassword();
3549
-            // only include if related to a cpt where no password has been set
3550
-            $query_params[0]['OR*nopassword'] = [
3551
-                $where_param_key_for_password       => '',
3552
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3553
-            ];
3554
-        }
3555
-        $query_object = $this->_extract_related_models_from_query($query_params);
3556
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3557
-        foreach ($query_params[0] as $key => $value) {
3558
-            if (is_int($key)) {
3559
-                throw new EE_Error(
3560
-                    sprintf(
3561
-                        esc_html__(
3562
-                            "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.",
3563
-                            "event_espresso"
3564
-                        ),
3565
-                        $key,
3566
-                        var_export($value, true),
3567
-                        var_export($query_params, true),
3568
-                        get_class($this)
3569
-                    )
3570
-                );
3571
-            }
3572
-        }
3573
-        if (
3574
-            array_key_exists('default_where_conditions', $query_params)
3575
-            && ! empty($query_params['default_where_conditions'])
3576
-        ) {
3577
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3578
-        } else {
3579
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3580
-        }
3581
-        $query_params[0] = array_merge(
3582
-            $this->_get_default_where_conditions_for_models_in_query(
3583
-                $query_object,
3584
-                $use_default_where_conditions,
3585
-                $query_params[0]
3586
-            ),
3587
-            $query_params[0]
3588
-        );
3589
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3590
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3591
-        // So we need to setup a subquery and use that for the main join.
3592
-        // Note for now this only works on the primary table for the model.
3593
-        // So for instance, you could set the limit array like this:
3594
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3595
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3596
-            $query_object->set_main_model_join_sql(
3597
-                $this->_construct_limit_join_select(
3598
-                    $query_params['on_join_limit'][0],
3599
-                    $query_params['on_join_limit'][1]
3600
-                )
3601
-            );
3602
-        }
3603
-        // set limit
3604
-        if (array_key_exists('limit', $query_params)) {
3605
-            if (is_array($query_params['limit'])) {
3606
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3607
-                    $e = sprintf(
3608
-                        esc_html__(
3609
-                            "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)",
3610
-                            "event_espresso"
3611
-                        ),
3612
-                        http_build_query($query_params['limit'])
3613
-                    );
3614
-                    throw new EE_Error($e . "|" . $e);
3615
-                }
3616
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3617
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3618
-            } elseif (! empty($query_params['limit'])) {
3619
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3620
-            }
3621
-        }
3622
-        // set order by
3623
-        if (array_key_exists('order_by', $query_params)) {
3624
-            if (is_array($query_params['order_by'])) {
3625
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3626
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3627
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3628
-                if (array_key_exists('order', $query_params)) {
3629
-                    throw new EE_Error(
3630
-                        sprintf(
3631
-                            esc_html__(
3632
-                                "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 ",
3633
-                                "event_espresso"
3634
-                            ),
3635
-                            get_class($this),
3636
-                            implode(", ", array_keys($query_params['order_by'])),
3637
-                            implode(", ", $query_params['order_by']),
3638
-                            $query_params['order']
3639
-                        )
3640
-                    );
3641
-                }
3642
-                $this->_extract_related_models_from_sub_params_array_keys(
3643
-                    $query_params['order_by'],
3644
-                    $query_object,
3645
-                    'order_by'
3646
-                );
3647
-                // assume it's an array of fields to order by
3648
-                $order_array = [];
3649
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3650
-                    $order         = $this->_extract_order($order);
3651
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3652
-                }
3653
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3654
-            } elseif (! empty($query_params['order_by'])) {
3655
-                $this->_extract_related_model_info_from_query_param(
3656
-                    $query_params['order_by'],
3657
-                    $query_object,
3658
-                    'order',
3659
-                    $query_params['order_by']
3660
-                );
3661
-                $order = isset($query_params['order'])
3662
-                    ? $this->_extract_order($query_params['order'])
3663
-                    : 'DESC';
3664
-                $query_object->set_order_by_sql(
3665
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3666
-                );
3667
-            }
3668
-        }
3669
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3670
-        if (
3671
-            ! array_key_exists('order_by', $query_params)
3672
-            && array_key_exists('order', $query_params)
3673
-            && ! empty($query_params['order'])
3674
-        ) {
3675
-            $pk_field = $this->get_primary_key_field();
3676
-            $order    = $this->_extract_order($query_params['order']);
3677
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3678
-        }
3679
-        // set group by
3680
-        if (array_key_exists('group_by', $query_params)) {
3681
-            if (is_array($query_params['group_by'])) {
3682
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3683
-                $group_by_array = [];
3684
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3685
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3686
-                }
3687
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3688
-            } elseif (! empty($query_params['group_by'])) {
3689
-                $query_object->set_group_by_sql(
3690
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3691
-                );
3692
-            }
3693
-        }
3694
-        // set having
3695
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3696
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3697
-        }
3698
-        // now, just verify they didn't pass anything wack
3699
-        foreach ($query_params as $query_key => $query_value) {
3700
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3701
-                throw new EE_Error(
3702
-                    sprintf(
3703
-                        esc_html__(
3704
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3705
-                            'event_espresso'
3706
-                        ),
3707
-                        $query_key,
3708
-                        get_class($this),
3709
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3710
-                        implode(',', $this->_allowed_query_params)
3711
-                    )
3712
-                );
3713
-            }
3714
-        }
3715
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3716
-        if (empty($main_model_join_sql)) {
3717
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3718
-        }
3719
-        return $query_object;
3720
-    }
3721
-
3722
-
3723
-    /**
3724
-     * Gets the where conditions that should be imposed on the query based on the
3725
-     * context (eg reading frontend, backend, edit or delete).
3726
-     *
3727
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3728
-     * @return array @see
3729
-     *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3730
-     * @throws EE_Error
3731
-     */
3732
-    public function caps_where_conditions($context = self::caps_read)
3733
-    {
3734
-        EEM_Base::verify_is_valid_cap_context($context);
3735
-        $cap_where_conditions = [];
3736
-        $cap_restrictions     = $this->caps_missing($context);
3737
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3738
-            $cap_where_conditions = array_replace_recursive(
3739
-                $cap_where_conditions,
3740
-                $restriction_if_no_cap->get_default_where_conditions()
3741
-            );
3742
-        }
3743
-        return apply_filters(
3744
-            'FHEE__EEM_Base__caps_where_conditions__return',
3745
-            $cap_where_conditions,
3746
-            $this,
3747
-            $context,
3748
-            $cap_restrictions
3749
-        );
3750
-    }
3751
-
3752
-
3753
-    /**
3754
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3755
-     * otherwise throws an exception
3756
-     *
3757
-     * @param string $should_be_order_string
3758
-     * @return string either ASC, asc, DESC or desc
3759
-     * @throws EE_Error
3760
-     */
3761
-    private function _extract_order($should_be_order_string)
3762
-    {
3763
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3764
-            return $should_be_order_string;
3765
-        }
3766
-        throw new EE_Error(
3767
-            sprintf(
3768
-                esc_html__(
3769
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3770
-                    "event_espresso"
3771
-                ),
3772
-                get_class($this),
3773
-                $should_be_order_string
3774
-            )
3775
-        );
3776
-    }
3777
-
3778
-
3779
-    /**
3780
-     * Looks at all the models which are included in this query, and asks each
3781
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3782
-     * so they can be merged
3783
-     *
3784
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3785
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3786
-     *                                                                  'none' means NO default where conditions will
3787
-     *                                                                  be used AT ALL during this query.
3788
-     *                                                                  'other_models_only' means default where
3789
-     *                                                                  conditions from other models will be used, but
3790
-     *                                                                  not for this primary model. 'all', the default,
3791
-     *                                                                  means default where conditions will apply as
3792
-     *                                                                  normal
3793
-     * @param array                       $where_query_params
3794
-     * @return array
3795
-     * @throws EE_Error
3796
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3797
-     *                                                                  .md#0-where-conditions
3798
-     */
3799
-    private function _get_default_where_conditions_for_models_in_query(
3800
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3801
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3802
-        $where_query_params = []
3803
-    ) {
3804
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3805
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3806
-            throw new EE_Error(
3807
-                sprintf(
3808
-                    esc_html__(
3809
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3810
-                        "event_espresso"
3811
-                    ),
3812
-                    $use_default_where_conditions,
3813
-                    implode(", ", $allowed_used_default_where_conditions_values)
3814
-                )
3815
-            );
3816
-        }
3817
-        $universal_query_params = [];
3818
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3819
-            $universal_query_params = $this->_get_default_where_conditions();
3820
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3821
-            $universal_query_params = $this->_get_minimum_where_conditions();
3822
-        }
3823
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3824
-            $related_model = $this->get_related_model_obj($model_name);
3825
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3826
-                $related_model_universal_where_params =
3827
-                    $related_model->_get_default_where_conditions($model_relation_path);
3828
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3829
-                $related_model_universal_where_params =
3830
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3831
-            } else {
3832
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3833
-                continue;
3834
-            }
3835
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3836
-                $related_model_universal_where_params,
3837
-                $where_query_params,
3838
-                $related_model,
3839
-                $model_relation_path
3840
-            );
3841
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3842
-                $universal_query_params,
3843
-                $overrides
3844
-            );
3845
-        }
3846
-        return $universal_query_params;
3847
-    }
3848
-
3849
-
3850
-    /**
3851
-     * Determines whether or not we should use default where conditions for the model in question
3852
-     * (this model, or other related models).
3853
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3854
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3855
-     * We should use default where conditions on related models when they requested to use default where conditions
3856
-     * on all models, or specifically just on other related models
3857
-     *
3858
-     * @param      $default_where_conditions_value
3859
-     * @param bool $for_this_model false means this is for OTHER related models
3860
-     * @return bool
3861
-     */
3862
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3863
-    {
3864
-        return (
3865
-                   $for_this_model
3866
-                   && in_array(
3867
-                       $default_where_conditions_value,
3868
-                       [
3869
-                           EEM_Base::default_where_conditions_all,
3870
-                           EEM_Base::default_where_conditions_this_only,
3871
-                           EEM_Base::default_where_conditions_minimum_others,
3872
-                       ],
3873
-                       true
3874
-                   )
3875
-               )
3876
-               || (
3877
-                   ! $for_this_model
3878
-                   && in_array(
3879
-                       $default_where_conditions_value,
3880
-                       [
3881
-                           EEM_Base::default_where_conditions_all,
3882
-                           EEM_Base::default_where_conditions_others_only,
3883
-                       ],
3884
-                       true
3885
-                   )
3886
-               );
3887
-    }
3888
-
3889
-
3890
-    /**
3891
-     * Determines whether or not we should use default minimum conditions for the model in question
3892
-     * (this model, or other related models).
3893
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3894
-     * where conditions.
3895
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3896
-     * on this model or others
3897
-     *
3898
-     * @param      $default_where_conditions_value
3899
-     * @param bool $for_this_model false means this is for OTHER related models
3900
-     * @return bool
3901
-     */
3902
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3903
-    {
3904
-        return (
3905
-                   $for_this_model
3906
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3907
-               )
3908
-               || (
3909
-                   ! $for_this_model
3910
-                   && in_array(
3911
-                       $default_where_conditions_value,
3912
-                       [
3913
-                           EEM_Base::default_where_conditions_minimum_others,
3914
-                           EEM_Base::default_where_conditions_minimum_all,
3915
-                       ],
3916
-                       true
3917
-                   )
3918
-               );
3919
-    }
3920
-
3921
-
3922
-    /**
3923
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3924
-     * then we also add a special where condition which allows for that model's primary key
3925
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3926
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3927
-     *
3928
-     * @param array    $default_where_conditions
3929
-     * @param array    $provided_where_conditions
3930
-     * @param EEM_Base $model
3931
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3932
-     * @return array @see
3933
-     *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3934
-     * @throws EE_Error
3935
-     */
3936
-    private function _override_defaults_or_make_null_friendly(
3937
-        $default_where_conditions,
3938
-        $provided_where_conditions,
3939
-        $model,
3940
-        $model_relation_path
3941
-    ) {
3942
-        $null_friendly_where_conditions = [];
3943
-        $none_overridden                = true;
3944
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3945
-        foreach ($default_where_conditions as $key => $val) {
3946
-            if (isset($provided_where_conditions[ $key ])) {
3947
-                $none_overridden = false;
3948
-            } else {
3949
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3950
-            }
3951
-        }
3952
-        if ($none_overridden && $default_where_conditions) {
3953
-            if ($model->has_primary_key_field()) {
3954
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3955
-                                                                                   . "."
3956
-                                                                                   . $model->primary_key_name() ] =
3957
-                    ['IS NULL'];
3958
-            }/*else{
2637
+			$this->_show_next_x_db_queries--;
2638
+		}
2639
+	}
2640
+
2641
+
2642
+	/**
2643
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2644
+	 * There are the 3 cases:
2645
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2646
+	 * $otherModelObject has no ID, it is first saved.
2647
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2648
+	 * has no ID, it is first saved.
2649
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2650
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2651
+	 * join table
2652
+	 *
2653
+	 * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2654
+	 * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2655
+	 * @param string            $relationName                     , key in EEM_Base::_relations
2656
+	 *                                                            an attendee to a group, you also want to specify
2657
+	 *                                                            which role they will have in that group. So you would
2658
+	 *                                                            use this parameter to specify
2659
+	 *                                                            array('role-column-name'=>'role-id')
2660
+	 * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2661
+	 *                                                            relation to for relation to methods that allow you to
2662
+	 *                                                            further specify extra columns to join by (such as
2663
+	 *                                                            HABTM).  Keep in mind that the only acceptable
2664
+	 *                                                            query_params is strict "col" => "value" pairs because
2665
+	 *                                                            these will be inserted in any new rows created as
2666
+	 *                                                            well.
2667
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function add_relationship_to(
2671
+		$id_or_obj,
2672
+		$other_model_id_or_obj,
2673
+		$relationName,
2674
+		$extra_join_model_fields_n_values = []
2675
+	) {
2676
+		$relation_obj = $this->related_settings_for($relationName);
2677
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2678
+	}
2679
+
2680
+
2681
+	/**
2682
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2683
+	 * There are the 3 cases:
2684
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2685
+	 * error
2686
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2687
+	 * an error
2688
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2689
+	 *
2690
+	 * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2691
+	 * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2692
+	 * @param string            $relationName          key in EEM_Base::_relations
2693
+	 * @param array|null        $where_query           This allows you to enter further query params for the relation
2694
+	 *                                                 to for relation to methods that allow you to further specify
2695
+	 *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2696
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2697
+	 *                                                 because these will be inserted in any new rows created as well.
2698
+	 * @return EE_Base_Class
2699
+	 * @throws EE_Error
2700
+	 */
2701
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2702
+	{
2703
+		$relation_obj = $this->related_settings_for($relationName);
2704
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2705
+	}
2706
+
2707
+
2708
+	/**
2709
+	 * @param mixed       $id_or_obj
2710
+	 * @param string      $relationName
2711
+	 * @param array|null  $where_query_params
2712
+	 * @return EE_Base_Class[]
2713
+	 * @throws EE_Error
2714
+	 * @throws ReflectionException
2715
+	 */
2716
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2717
+	{
2718
+		$relation_obj = $this->related_settings_for($relationName);
2719
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2720
+	}
2721
+
2722
+
2723
+	/**
2724
+	 * Gets all the related items of the specified $model_name, using $query_params.
2725
+	 * Note: by default, we remove the "default query params"
2726
+	 * because we want to get even deleted items etc.
2727
+	 *
2728
+	 * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2729
+	 * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2730
+	 * @param array|null  $query_params @see
2731
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
+	 * @return EE_Base_Class[]
2733
+	 * @throws EE_Error
2734
+	 * @throws ReflectionException
2735
+	 */
2736
+	public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2737
+	{
2738
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2739
+		$relation_settings = $this->related_settings_for($model_name);
2740
+		return $relation_settings->get_all_related($model_obj, $query_params);
2741
+	}
2742
+
2743
+
2744
+	/**
2745
+	 * Deletes all the model objects across the relation indicated by $model_name
2746
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2747
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2748
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2749
+	 *
2750
+	 * @param EE_Base_Class|int|string $id_or_obj
2751
+	 * @param string                   $model_name
2752
+	 * @param array|null               $query_params
2753
+	 * @return int how many deleted
2754
+	 * @throws EE_Error
2755
+	 * @throws ReflectionException
2756
+	 */
2757
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2758
+	{
2759
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2760
+		$relation_settings = $this->related_settings_for($model_name);
2761
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2762
+	}
2763
+
2764
+
2765
+	/**
2766
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2767
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2768
+	 * the model objects can't be hard deleted because of blocking related model objects,
2769
+	 * just does a soft-delete on them instead.
2770
+	 *
2771
+	 * @param EE_Base_Class|int|string $id_or_obj
2772
+	 * @param string                   $model_name
2773
+	 * @param array|null               $query_params
2774
+	 * @return int how many deleted
2775
+	 * @throws EE_Error
2776
+	 * @throws ReflectionException
2777
+	 */
2778
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2779
+	{
2780
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2781
+		$relation_settings = $this->related_settings_for($model_name);
2782
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2783
+	}
2784
+
2785
+
2786
+	/**
2787
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2788
+	 * unless otherwise specified in the $query_params
2789
+	 *
2790
+	 * @param EE_Base_Class|int|string $id_or_obj
2791
+	 * @param string                   $model_name     like 'Event', or 'Registration'
2792
+	 * @param array|null               $query_params   @see
2793
+	 *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2794
+	 * @param string                   $field_to_count name of field to count by. By default, uses primary key
2795
+	 * @param bool                     $distinct       if we want to only count the distinct values for the column then
2796
+	 *                                                 you can trigger that by the setting $distinct to TRUE;
2797
+	 * @return int
2798
+	 * @throws EE_Error
2799
+	 * @throws ReflectionException
2800
+	 */
2801
+	public function count_related(
2802
+		$id_or_obj,
2803
+		$model_name,
2804
+		$query_params = [],
2805
+		$field_to_count = null,
2806
+		$distinct = false
2807
+	) {
2808
+		$related_model = $this->get_related_model_obj($model_name);
2809
+		// we're just going to use the query params on the related model's normal get_all query,
2810
+		// except add a condition to say to match the current mod
2811
+		if (! isset($query_params['default_where_conditions'])) {
2812
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2813
+		}
2814
+		$this_model_name                                                 = $this->get_this_model_name();
2815
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2816
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2817
+		return $related_model->count($query_params, $field_to_count, $distinct);
2818
+	}
2819
+
2820
+
2821
+	/**
2822
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2823
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2824
+	 *
2825
+	 * @param EE_Base_Class|int|string $id_or_obj
2826
+	 * @param string                   $model_name   like 'Event', or 'Registration'
2827
+	 * @param array|null               $query_params @see
2828
+	 *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2829
+	 * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2830
+	 * @return float
2831
+	 * @throws EE_Error
2832
+	 * @throws ReflectionException
2833
+	 */
2834
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2835
+	{
2836
+		$related_model = $this->get_related_model_obj($model_name);
2837
+		if (! is_array($query_params)) {
2838
+			EE_Error::doing_it_wrong(
2839
+				'EEM_Base::sum_related',
2840
+				sprintf(
2841
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2842
+					gettype($query_params)
2843
+				),
2844
+				'4.6.0'
2845
+			);
2846
+			$query_params = [];
2847
+		}
2848
+		// we're just going to use the query params on the related model's normal get_all query,
2849
+		// except add a condition to say to match the current mod
2850
+		if (! isset($query_params['default_where_conditions'])) {
2851
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2852
+		}
2853
+		$this_model_name                                                 = $this->get_this_model_name();
2854
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2855
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2856
+		return $related_model->sum($query_params, $field_to_sum);
2857
+	}
2858
+
2859
+
2860
+	/**
2861
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2862
+	 * $modelObject
2863
+	 *
2864
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2865
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2866
+	 * @param array|null          $query_params     @see
2867
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2868
+	 * @return EE_Base_Class
2869
+	 * @throws EE_Error
2870
+	 * @throws ReflectionException
2871
+	 */
2872
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2873
+	{
2874
+		$query_params['limit'] = 1;
2875
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2876
+		if ($results) {
2877
+			return array_shift($results);
2878
+		}
2879
+		return null;
2880
+	}
2881
+
2882
+
2883
+	/**
2884
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2885
+	 *
2886
+	 * @return string
2887
+	 */
2888
+	public function get_this_model_name()
2889
+	{
2890
+		return str_replace("EEM_", "", get_class($this));
2891
+	}
2892
+
2893
+
2894
+	/**
2895
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2896
+	 *
2897
+	 * @return EE_Any_Foreign_Model_Name_Field
2898
+	 * @throws EE_Error
2899
+	 */
2900
+	public function get_field_containing_related_model_name()
2901
+	{
2902
+		foreach ($this->field_settings(true) as $field) {
2903
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2904
+				$field_with_model_name = $field;
2905
+			}
2906
+		}
2907
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2908
+			throw new EE_Error(
2909
+				sprintf(
2910
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2911
+					$this->get_this_model_name()
2912
+				)
2913
+			);
2914
+		}
2915
+		return $field_with_model_name;
2916
+	}
2917
+
2918
+
2919
+	/**
2920
+	 * Inserts a new entry into the database, for each table.
2921
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2922
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2923
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2924
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2925
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2926
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2927
+	 *
2928
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2929
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2930
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2931
+	 *                              of EEM_Base)
2932
+	 * @return int|string new primary key on main table that got inserted
2933
+	 * @throws EE_Error
2934
+	 * @throws ReflectionException
2935
+	 */
2936
+	public function insert($field_n_values)
2937
+	{
2938
+		/**
2939
+		 * Filters the fields and their values before inserting an item using the models
2940
+		 *
2941
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2942
+		 * @param EEM_Base $model           the model used
2943
+		 */
2944
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2945
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2946
+			$main_table = $this->_get_main_table();
2947
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2948
+			if ($new_id !== false) {
2949
+				foreach ($this->_get_other_tables() as $other_table) {
2950
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2951
+				}
2952
+			}
2953
+			/**
2954
+			 * Done just after attempting to insert a new model object
2955
+			 *
2956
+			 * @param EEM_Base $model           used
2957
+			 * @param array    $fields_n_values fields and their values
2958
+			 * @param int|string the              ID of the newly-inserted model object
2959
+			 */
2960
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2961
+			return $new_id;
2962
+		}
2963
+		return false;
2964
+	}
2965
+
2966
+
2967
+	/**
2968
+	 * Checks that the result would satisfy the unique indexes on this model
2969
+	 *
2970
+	 * @param array  $field_n_values
2971
+	 * @param string $action
2972
+	 * @return boolean
2973
+	 * @throws EE_Error
2974
+	 * @throws ReflectionException
2975
+	 */
2976
+	protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2977
+	{
2978
+		foreach ($this->unique_indexes() as $index_name => $index) {
2979
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2980
+			if ($this->exists([$uniqueness_where_params])) {
2981
+				EE_Error::add_error(
2982
+					sprintf(
2983
+						esc_html__(
2984
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2985
+							"event_espresso"
2986
+						),
2987
+						$action,
2988
+						$this->_get_class_name(),
2989
+						$index_name,
2990
+						implode(",", $index->field_names()),
2991
+						http_build_query($uniqueness_where_params)
2992
+					),
2993
+					__FILE__,
2994
+					__FUNCTION__,
2995
+					__LINE__
2996
+				);
2997
+				return false;
2998
+			}
2999
+		}
3000
+		return true;
3001
+	}
3002
+
3003
+
3004
+	/**
3005
+	 * Checks the database for an item that conflicts (ie, if this item were
3006
+	 * saved to the DB would break some uniqueness requirement, like a primary key
3007
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
3008
+	 * can be either an EE_Base_Class or an array of fields n values
3009
+	 *
3010
+	 * @param EE_Base_Class|array $obj_or_fields_array
3011
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
3012
+	 *                                                 when looking for conflicts
3013
+	 *                                                 (ie, if false, we ignore the model object's primary key
3014
+	 *                                                 when finding "conflicts". If true, it's also considered).
3015
+	 *                                                 Only works for INT primary key,
3016
+	 *                                                 STRING primary keys cannot be ignored
3017
+	 * @return EE_Base_Class|array
3018
+	 * @throws EE_Error
3019
+	 * @throws ReflectionException
3020
+	 */
3021
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3022
+	{
3023
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
3024
+			$fields_n_values = $obj_or_fields_array->model_field_array();
3025
+		} elseif (is_array($obj_or_fields_array)) {
3026
+			$fields_n_values = $obj_or_fields_array;
3027
+		} else {
3028
+			throw new EE_Error(
3029
+				sprintf(
3030
+					esc_html__(
3031
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3032
+						"event_espresso"
3033
+					),
3034
+					get_class($this),
3035
+					$obj_or_fields_array
3036
+				)
3037
+			);
3038
+		}
3039
+		$query_params = [];
3040
+		if (
3041
+			$this->has_primary_key_field()
3042
+			&& ($include_primary_key
3043
+				|| $this->get_primary_key_field()
3044
+				   instanceof
3045
+				   EE_Primary_Key_String_Field)
3046
+			&& isset($fields_n_values[ $this->primary_key_name() ])
3047
+		) {
3048
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3049
+		}
3050
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3051
+			$uniqueness_where_params                              =
3052
+				array_intersect_key($fields_n_values, $unique_index->fields());
3053
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3054
+		}
3055
+		// if there is nothing to base this search on, then we shouldn't find anything
3056
+		if (empty($query_params)) {
3057
+			return [];
3058
+		}
3059
+		return $this->get_one($query_params);
3060
+	}
3061
+
3062
+
3063
+	/**
3064
+	 * Like count, but is optimized and returns a boolean instead of an int
3065
+	 *
3066
+	 * @param array $query_params
3067
+	 * @return boolean
3068
+	 * @throws EE_Error
3069
+	 * @throws ReflectionException
3070
+	 */
3071
+	public function exists($query_params)
3072
+	{
3073
+		$query_params['limit'] = 1;
3074
+		return $this->count($query_params) > 0;
3075
+	}
3076
+
3077
+
3078
+	/**
3079
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3080
+	 *
3081
+	 * @param int|string $id
3082
+	 * @return boolean
3083
+	 * @throws EE_Error
3084
+	 * @throws ReflectionException
3085
+	 */
3086
+	public function exists_by_ID($id)
3087
+	{
3088
+		return $this->exists(
3089
+			[
3090
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3091
+				[
3092
+					$this->primary_key_name() => $id,
3093
+				],
3094
+			]
3095
+		);
3096
+	}
3097
+
3098
+
3099
+	/**
3100
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3101
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3102
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3103
+	 * on the main table)
3104
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3105
+	 * cases where we want to call it directly rather than via insert().
3106
+	 *
3107
+	 * @access   protected
3108
+	 * @param EE_Table_Base $table
3109
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3110
+	 *                                       float
3111
+	 * @param int           $new_id          for now we assume only int keys
3112
+	 * @return int ID of new row inserted, or FALSE on failure
3113
+	 * @throws EE_Error
3114
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3115
+	 */
3116
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3117
+	{
3118
+		global $wpdb;
3119
+		$insertion_col_n_values = [];
3120
+		$format_for_insertion   = [];
3121
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3122
+		foreach ($fields_on_table as $field_obj) {
3123
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3124
+			if ($field_obj->is_auto_increment()) {
3125
+				continue;
3126
+			}
3127
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3128
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3129
+			if ($prepared_value !== null) {
3130
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3131
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3132
+			}
3133
+		}
3134
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3135
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3136
+			// so add the fk to the main table as a column
3137
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3138
+			$format_for_insertion[]                              =
3139
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3140
+		}
3141
+
3142
+		// insert the new entry
3143
+		$result = $this->_do_wpdb_query(
3144
+			'insert',
3145
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3146
+		);
3147
+		if ($result === false) {
3148
+			return false;
3149
+		}
3150
+		// ok, now what do we return for the ID of the newly-inserted thing?
3151
+		if ($this->has_primary_key_field()) {
3152
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3153
+				return $wpdb->insert_id;
3154
+			}
3155
+			// it's not an auto-increment primary key, so
3156
+			// it must have been supplied
3157
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3158
+		}
3159
+		// we can't return a  primary key because there is none. instead return
3160
+		// a unique string indicating this model
3161
+		return $this->get_index_primary_key_string($fields_n_values);
3162
+	}
3163
+
3164
+
3165
+	/**
3166
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3167
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3168
+	 * and there is no default, we pass it along. WPDB will take care of it)
3169
+	 *
3170
+	 * @param EE_Model_Field_Base $field_obj
3171
+	 * @param array               $fields_n_values
3172
+	 * @return mixed string|int|float depending on what the table column will be expecting
3173
+	 * @throws EE_Error
3174
+	 */
3175
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3176
+	{
3177
+		$field_name = $field_obj->get_name();
3178
+		// if this field doesn't allow nullable, don't allow it
3179
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3180
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3181
+		}
3182
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3183
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3184
+	}
3185
+
3186
+
3187
+	/**
3188
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3189
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3190
+	 * the field's prepare_for_set() method.
3191
+	 *
3192
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3193
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3194
+	 *                                   top of file)
3195
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3196
+	 *                                   $value is a custom selection
3197
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3198
+	 */
3199
+	private function _prepare_value_for_use_in_db($value, $field)
3200
+	{
3201
+		if ($field instanceof EE_Model_Field_Base) {
3202
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3203
+			switch ($this->_values_already_prepared_by_model_object) {
3204
+				/** @noinspection PhpMissingBreakStatementInspection */
3205
+				case self::not_prepared_by_model_object:
3206
+					$value = $field->prepare_for_set($value);
3207
+				// purposefully left out "return"
3208
+				// no break
3209
+				case self::prepared_by_model_object:
3210
+					/** @noinspection SuspiciousAssignmentsInspection */
3211
+					$value = $field->prepare_for_use_in_db($value);
3212
+				// no break
3213
+				case self::prepared_for_use_in_db:
3214
+					// leave the value alone
3215
+			}
3216
+			// phpcs:enable
3217
+		}
3218
+		return $value;
3219
+	}
3220
+
3221
+
3222
+	/**
3223
+	 * Returns the main table on this model
3224
+	 *
3225
+	 * @return EE_Primary_Table
3226
+	 * @throws EE_Error
3227
+	 */
3228
+	protected function _get_main_table()
3229
+	{
3230
+		foreach ($this->_tables as $table) {
3231
+			if ($table instanceof EE_Primary_Table) {
3232
+				return $table;
3233
+			}
3234
+		}
3235
+		throw new EE_Error(
3236
+			sprintf(
3237
+				esc_html__(
3238
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3239
+					'event_espresso'
3240
+				),
3241
+				get_class($this)
3242
+			)
3243
+		);
3244
+	}
3245
+
3246
+
3247
+	/**
3248
+	 * table
3249
+	 * returns EE_Primary_Table table name
3250
+	 *
3251
+	 * @return string
3252
+	 * @throws EE_Error
3253
+	 */
3254
+	public function table()
3255
+	{
3256
+		return $this->_get_main_table()->get_table_name();
3257
+	}
3258
+
3259
+
3260
+	/**
3261
+	 * table
3262
+	 * returns first EE_Secondary_Table table name
3263
+	 *
3264
+	 * @return string
3265
+	 */
3266
+	public function second_table()
3267
+	{
3268
+		// grab second table from tables array
3269
+		$second_table = end($this->_tables);
3270
+		return $second_table instanceof EE_Secondary_Table
3271
+			? $second_table->get_table_name()
3272
+			: null;
3273
+	}
3274
+
3275
+
3276
+	/**
3277
+	 * get_table_obj_by_alias
3278
+	 * returns table name given it's alias
3279
+	 *
3280
+	 * @param string $table_alias
3281
+	 * @return EE_Primary_Table | EE_Secondary_Table
3282
+	 */
3283
+	public function get_table_obj_by_alias($table_alias = '')
3284
+	{
3285
+		return $this->_tables[ $table_alias ] ?? null;
3286
+	}
3287
+
3288
+
3289
+	/**
3290
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3291
+	 *
3292
+	 * @return EE_Secondary_Table[]
3293
+	 */
3294
+	protected function _get_other_tables()
3295
+	{
3296
+		$other_tables = [];
3297
+		foreach ($this->_tables as $table_alias => $table) {
3298
+			if ($table instanceof EE_Secondary_Table) {
3299
+				$other_tables[ $table_alias ] = $table;
3300
+			}
3301
+		}
3302
+		return $other_tables;
3303
+	}
3304
+
3305
+
3306
+	/**
3307
+	 * Finds all the fields that correspond to the given table
3308
+	 *
3309
+	 * @param string $table_alias , array key in EEM_Base::_tables
3310
+	 * @return EE_Model_Field_Base[]
3311
+	 */
3312
+	public function _get_fields_for_table($table_alias)
3313
+	{
3314
+		return $this->_fields[ $table_alias ];
3315
+	}
3316
+
3317
+
3318
+	/**
3319
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3320
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3321
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3322
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3323
+	 * related Registration, Transaction, and Payment models.
3324
+	 *
3325
+	 * @param array $query_params @see
3326
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3327
+	 * @return EE_Model_Query_Info_Carrier
3328
+	 * @throws EE_Error
3329
+	 */
3330
+	public function _extract_related_models_from_query($query_params)
3331
+	{
3332
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3333
+		if (array_key_exists(0, $query_params)) {
3334
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3335
+		}
3336
+		if (array_key_exists('group_by', $query_params)) {
3337
+			if (is_array($query_params['group_by'])) {
3338
+				$this->_extract_related_models_from_sub_params_array_values(
3339
+					$query_params['group_by'],
3340
+					$query_info_carrier,
3341
+					'group_by'
3342
+				);
3343
+			} elseif (! empty($query_params['group_by'])) {
3344
+				$this->_extract_related_model_info_from_query_param(
3345
+					$query_params['group_by'],
3346
+					$query_info_carrier,
3347
+					'group_by'
3348
+				);
3349
+			}
3350
+		}
3351
+		if (array_key_exists('having', $query_params)) {
3352
+			$this->_extract_related_models_from_sub_params_array_keys(
3353
+				$query_params[0],
3354
+				$query_info_carrier,
3355
+				'having'
3356
+			);
3357
+		}
3358
+		if (array_key_exists('order_by', $query_params)) {
3359
+			if (is_array($query_params['order_by'])) {
3360
+				$this->_extract_related_models_from_sub_params_array_keys(
3361
+					$query_params['order_by'],
3362
+					$query_info_carrier,
3363
+					'order_by'
3364
+				);
3365
+			} elseif (! empty($query_params['order_by'])) {
3366
+				$this->_extract_related_model_info_from_query_param(
3367
+					$query_params['order_by'],
3368
+					$query_info_carrier,
3369
+					'order_by'
3370
+				);
3371
+			}
3372
+		}
3373
+		if (array_key_exists('force_join', $query_params)) {
3374
+			$this->_extract_related_models_from_sub_params_array_values(
3375
+				$query_params['force_join'],
3376
+				$query_info_carrier,
3377
+				'force_join'
3378
+			);
3379
+		}
3380
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3381
+		return $query_info_carrier;
3382
+	}
3383
+
3384
+
3385
+	/**
3386
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3387
+	 *
3388
+	 * @param array                       $sub_query_params
3389
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3390
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3391
+	 * @return EE_Model_Query_Info_Carrier
3392
+	 * @throws EE_Error
3393
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3394
+	 */
3395
+	private function _extract_related_models_from_sub_params_array_keys(
3396
+		$sub_query_params,
3397
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3398
+		$query_param_type
3399
+	) {
3400
+		if (! empty($sub_query_params)) {
3401
+			$sub_query_params = (array) $sub_query_params;
3402
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3403
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
+				$this->_extract_related_model_info_from_query_param(
3405
+					$param,
3406
+					$model_query_info_carrier,
3407
+					$query_param_type
3408
+				);
3409
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3410
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3411
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3412
+				// of array('Registration.TXN_ID'=>23)
3413
+				$query_param_sans_stars =
3414
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3415
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3416
+					if (! is_array($possibly_array_of_params)) {
3417
+						throw new EE_Error(
3418
+							sprintf(
3419
+								esc_html__(
3420
+									"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'))",
3421
+									"event_espresso"
3422
+								),
3423
+								$param,
3424
+								$possibly_array_of_params
3425
+							)
3426
+						);
3427
+					}
3428
+					$this->_extract_related_models_from_sub_params_array_keys(
3429
+						$possibly_array_of_params,
3430
+						$model_query_info_carrier,
3431
+						$query_param_type
3432
+					);
3433
+				} elseif (
3434
+					$query_param_type === 0 // ie WHERE
3435
+					&& is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3436
+					&& isset($possibly_array_of_params[2])
3437
+					&& $possibly_array_of_params[2]
3438
+				) {
3439
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3440
+					// indicating that $possible_array_of_params[1] is actually a field name,
3441
+					// from which we should extract query parameters!
3442
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3443
+						throw new EE_Error(
3444
+							sprintf(
3445
+								esc_html__(
3446
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3447
+									"event_espresso"
3448
+								),
3449
+								$query_param_type,
3450
+								implode(",", $possibly_array_of_params)
3451
+							)
3452
+						);
3453
+					}
3454
+					$this->_extract_related_model_info_from_query_param(
3455
+						$possibly_array_of_params[1],
3456
+						$model_query_info_carrier,
3457
+						$query_param_type
3458
+					);
3459
+				}
3460
+			}
3461
+		}
3462
+		return $model_query_info_carrier;
3463
+	}
3464
+
3465
+
3466
+	/**
3467
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3468
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3469
+	 *
3470
+	 * @param array                       $sub_query_params @see
3471
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3472
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3473
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3474
+	 * @return EE_Model_Query_Info_Carrier
3475
+	 * @throws EE_Error
3476
+	 */
3477
+	private function _extract_related_models_from_sub_params_array_values(
3478
+		$sub_query_params,
3479
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3480
+		$query_param_type
3481
+	) {
3482
+		if (! empty($sub_query_params)) {
3483
+			if (! is_array($sub_query_params)) {
3484
+				throw new EE_Error(
3485
+					sprintf(
3486
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3487
+						$sub_query_params
3488
+					)
3489
+				);
3490
+			}
3491
+			foreach ($sub_query_params as $param) {
3492
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3493
+				$this->_extract_related_model_info_from_query_param(
3494
+					$param,
3495
+					$model_query_info_carrier,
3496
+					$query_param_type
3497
+				);
3498
+			}
3499
+		}
3500
+		return $model_query_info_carrier;
3501
+	}
3502
+
3503
+
3504
+	/**
3505
+	 * Extract all the query parts from  model query params
3506
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3507
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3508
+	 * but use them in a different order. Eg, we need to know what models we are querying
3509
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3510
+	 * other models before we can finalize the where clause SQL.
3511
+	 *
3512
+	 * @param array $query_params
3513
+	 * @return EE_Model_Query_Info_Carrier
3514
+	 * @throws EE_Error
3515
+	 * @throws ModelConfigurationException
3516
+	 * @throws ReflectionException
3517
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3518
+	 */
3519
+	public function _create_model_query_info_carrier($query_params)
3520
+	{
3521
+		if (! is_array($query_params)) {
3522
+			EE_Error::doing_it_wrong(
3523
+				'EEM_Base::_create_model_query_info_carrier',
3524
+				sprintf(
3525
+					esc_html__(
3526
+						'$query_params should be an array, you passed a variable of type %s',
3527
+						'event_espresso'
3528
+					),
3529
+					gettype($query_params)
3530
+				),
3531
+				'4.6.0'
3532
+			);
3533
+			$query_params = [];
3534
+		}
3535
+		$query_params[0] = $query_params[0] ?? [];
3536
+		// first check if we should alter the query to account for caps or not
3537
+		// because the caps might require us to do extra joins
3538
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3539
+			$query_params[0] = array_replace_recursive(
3540
+				$query_params[0],
3541
+				$this->caps_where_conditions($query_params['caps'])
3542
+			);
3543
+		}
3544
+
3545
+		// check if we should alter the query to remove data related to protected
3546
+		// custom post types
3547
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3548
+			$where_param_key_for_password = $this->modelChainAndPassword();
3549
+			// only include if related to a cpt where no password has been set
3550
+			$query_params[0]['OR*nopassword'] = [
3551
+				$where_param_key_for_password       => '',
3552
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3553
+			];
3554
+		}
3555
+		$query_object = $this->_extract_related_models_from_query($query_params);
3556
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3557
+		foreach ($query_params[0] as $key => $value) {
3558
+			if (is_int($key)) {
3559
+				throw new EE_Error(
3560
+					sprintf(
3561
+						esc_html__(
3562
+							"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.",
3563
+							"event_espresso"
3564
+						),
3565
+						$key,
3566
+						var_export($value, true),
3567
+						var_export($query_params, true),
3568
+						get_class($this)
3569
+					)
3570
+				);
3571
+			}
3572
+		}
3573
+		if (
3574
+			array_key_exists('default_where_conditions', $query_params)
3575
+			&& ! empty($query_params['default_where_conditions'])
3576
+		) {
3577
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3578
+		} else {
3579
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3580
+		}
3581
+		$query_params[0] = array_merge(
3582
+			$this->_get_default_where_conditions_for_models_in_query(
3583
+				$query_object,
3584
+				$use_default_where_conditions,
3585
+				$query_params[0]
3586
+			),
3587
+			$query_params[0]
3588
+		);
3589
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3590
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3591
+		// So we need to setup a subquery and use that for the main join.
3592
+		// Note for now this only works on the primary table for the model.
3593
+		// So for instance, you could set the limit array like this:
3594
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3595
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3596
+			$query_object->set_main_model_join_sql(
3597
+				$this->_construct_limit_join_select(
3598
+					$query_params['on_join_limit'][0],
3599
+					$query_params['on_join_limit'][1]
3600
+				)
3601
+			);
3602
+		}
3603
+		// set limit
3604
+		if (array_key_exists('limit', $query_params)) {
3605
+			if (is_array($query_params['limit'])) {
3606
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3607
+					$e = sprintf(
3608
+						esc_html__(
3609
+							"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)",
3610
+							"event_espresso"
3611
+						),
3612
+						http_build_query($query_params['limit'])
3613
+					);
3614
+					throw new EE_Error($e . "|" . $e);
3615
+				}
3616
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3617
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3618
+			} elseif (! empty($query_params['limit'])) {
3619
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3620
+			}
3621
+		}
3622
+		// set order by
3623
+		if (array_key_exists('order_by', $query_params)) {
3624
+			if (is_array($query_params['order_by'])) {
3625
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3626
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3627
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3628
+				if (array_key_exists('order', $query_params)) {
3629
+					throw new EE_Error(
3630
+						sprintf(
3631
+							esc_html__(
3632
+								"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 ",
3633
+								"event_espresso"
3634
+							),
3635
+							get_class($this),
3636
+							implode(", ", array_keys($query_params['order_by'])),
3637
+							implode(", ", $query_params['order_by']),
3638
+							$query_params['order']
3639
+						)
3640
+					);
3641
+				}
3642
+				$this->_extract_related_models_from_sub_params_array_keys(
3643
+					$query_params['order_by'],
3644
+					$query_object,
3645
+					'order_by'
3646
+				);
3647
+				// assume it's an array of fields to order by
3648
+				$order_array = [];
3649
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3650
+					$order         = $this->_extract_order($order);
3651
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3652
+				}
3653
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3654
+			} elseif (! empty($query_params['order_by'])) {
3655
+				$this->_extract_related_model_info_from_query_param(
3656
+					$query_params['order_by'],
3657
+					$query_object,
3658
+					'order',
3659
+					$query_params['order_by']
3660
+				);
3661
+				$order = isset($query_params['order'])
3662
+					? $this->_extract_order($query_params['order'])
3663
+					: 'DESC';
3664
+				$query_object->set_order_by_sql(
3665
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3666
+				);
3667
+			}
3668
+		}
3669
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3670
+		if (
3671
+			! array_key_exists('order_by', $query_params)
3672
+			&& array_key_exists('order', $query_params)
3673
+			&& ! empty($query_params['order'])
3674
+		) {
3675
+			$pk_field = $this->get_primary_key_field();
3676
+			$order    = $this->_extract_order($query_params['order']);
3677
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3678
+		}
3679
+		// set group by
3680
+		if (array_key_exists('group_by', $query_params)) {
3681
+			if (is_array($query_params['group_by'])) {
3682
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3683
+				$group_by_array = [];
3684
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3685
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3686
+				}
3687
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3688
+			} elseif (! empty($query_params['group_by'])) {
3689
+				$query_object->set_group_by_sql(
3690
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3691
+				);
3692
+			}
3693
+		}
3694
+		// set having
3695
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3696
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3697
+		}
3698
+		// now, just verify they didn't pass anything wack
3699
+		foreach ($query_params as $query_key => $query_value) {
3700
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3701
+				throw new EE_Error(
3702
+					sprintf(
3703
+						esc_html__(
3704
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3705
+							'event_espresso'
3706
+						),
3707
+						$query_key,
3708
+						get_class($this),
3709
+						//                      print_r( $this->_allowed_query_params, TRUE )
3710
+						implode(',', $this->_allowed_query_params)
3711
+					)
3712
+				);
3713
+			}
3714
+		}
3715
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3716
+		if (empty($main_model_join_sql)) {
3717
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3718
+		}
3719
+		return $query_object;
3720
+	}
3721
+
3722
+
3723
+	/**
3724
+	 * Gets the where conditions that should be imposed on the query based on the
3725
+	 * context (eg reading frontend, backend, edit or delete).
3726
+	 *
3727
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3728
+	 * @return array @see
3729
+	 *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3730
+	 * @throws EE_Error
3731
+	 */
3732
+	public function caps_where_conditions($context = self::caps_read)
3733
+	{
3734
+		EEM_Base::verify_is_valid_cap_context($context);
3735
+		$cap_where_conditions = [];
3736
+		$cap_restrictions     = $this->caps_missing($context);
3737
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3738
+			$cap_where_conditions = array_replace_recursive(
3739
+				$cap_where_conditions,
3740
+				$restriction_if_no_cap->get_default_where_conditions()
3741
+			);
3742
+		}
3743
+		return apply_filters(
3744
+			'FHEE__EEM_Base__caps_where_conditions__return',
3745
+			$cap_where_conditions,
3746
+			$this,
3747
+			$context,
3748
+			$cap_restrictions
3749
+		);
3750
+	}
3751
+
3752
+
3753
+	/**
3754
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3755
+	 * otherwise throws an exception
3756
+	 *
3757
+	 * @param string $should_be_order_string
3758
+	 * @return string either ASC, asc, DESC or desc
3759
+	 * @throws EE_Error
3760
+	 */
3761
+	private function _extract_order($should_be_order_string)
3762
+	{
3763
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3764
+			return $should_be_order_string;
3765
+		}
3766
+		throw new EE_Error(
3767
+			sprintf(
3768
+				esc_html__(
3769
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3770
+					"event_espresso"
3771
+				),
3772
+				get_class($this),
3773
+				$should_be_order_string
3774
+			)
3775
+		);
3776
+	}
3777
+
3778
+
3779
+	/**
3780
+	 * Looks at all the models which are included in this query, and asks each
3781
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3782
+	 * so they can be merged
3783
+	 *
3784
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3785
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3786
+	 *                                                                  'none' means NO default where conditions will
3787
+	 *                                                                  be used AT ALL during this query.
3788
+	 *                                                                  'other_models_only' means default where
3789
+	 *                                                                  conditions from other models will be used, but
3790
+	 *                                                                  not for this primary model. 'all', the default,
3791
+	 *                                                                  means default where conditions will apply as
3792
+	 *                                                                  normal
3793
+	 * @param array                       $where_query_params
3794
+	 * @return array
3795
+	 * @throws EE_Error
3796
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3797
+	 *                                                                  .md#0-where-conditions
3798
+	 */
3799
+	private function _get_default_where_conditions_for_models_in_query(
3800
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3801
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3802
+		$where_query_params = []
3803
+	) {
3804
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3805
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3806
+			throw new EE_Error(
3807
+				sprintf(
3808
+					esc_html__(
3809
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3810
+						"event_espresso"
3811
+					),
3812
+					$use_default_where_conditions,
3813
+					implode(", ", $allowed_used_default_where_conditions_values)
3814
+				)
3815
+			);
3816
+		}
3817
+		$universal_query_params = [];
3818
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3819
+			$universal_query_params = $this->_get_default_where_conditions();
3820
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3821
+			$universal_query_params = $this->_get_minimum_where_conditions();
3822
+		}
3823
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3824
+			$related_model = $this->get_related_model_obj($model_name);
3825
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3826
+				$related_model_universal_where_params =
3827
+					$related_model->_get_default_where_conditions($model_relation_path);
3828
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3829
+				$related_model_universal_where_params =
3830
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3831
+			} else {
3832
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3833
+				continue;
3834
+			}
3835
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3836
+				$related_model_universal_where_params,
3837
+				$where_query_params,
3838
+				$related_model,
3839
+				$model_relation_path
3840
+			);
3841
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3842
+				$universal_query_params,
3843
+				$overrides
3844
+			);
3845
+		}
3846
+		return $universal_query_params;
3847
+	}
3848
+
3849
+
3850
+	/**
3851
+	 * Determines whether or not we should use default where conditions for the model in question
3852
+	 * (this model, or other related models).
3853
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3854
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3855
+	 * We should use default where conditions on related models when they requested to use default where conditions
3856
+	 * on all models, or specifically just on other related models
3857
+	 *
3858
+	 * @param      $default_where_conditions_value
3859
+	 * @param bool $for_this_model false means this is for OTHER related models
3860
+	 * @return bool
3861
+	 */
3862
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3863
+	{
3864
+		return (
3865
+				   $for_this_model
3866
+				   && in_array(
3867
+					   $default_where_conditions_value,
3868
+					   [
3869
+						   EEM_Base::default_where_conditions_all,
3870
+						   EEM_Base::default_where_conditions_this_only,
3871
+						   EEM_Base::default_where_conditions_minimum_others,
3872
+					   ],
3873
+					   true
3874
+				   )
3875
+			   )
3876
+			   || (
3877
+				   ! $for_this_model
3878
+				   && in_array(
3879
+					   $default_where_conditions_value,
3880
+					   [
3881
+						   EEM_Base::default_where_conditions_all,
3882
+						   EEM_Base::default_where_conditions_others_only,
3883
+					   ],
3884
+					   true
3885
+				   )
3886
+			   );
3887
+	}
3888
+
3889
+
3890
+	/**
3891
+	 * Determines whether or not we should use default minimum conditions for the model in question
3892
+	 * (this model, or other related models).
3893
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3894
+	 * where conditions.
3895
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3896
+	 * on this model or others
3897
+	 *
3898
+	 * @param      $default_where_conditions_value
3899
+	 * @param bool $for_this_model false means this is for OTHER related models
3900
+	 * @return bool
3901
+	 */
3902
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3903
+	{
3904
+		return (
3905
+				   $for_this_model
3906
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3907
+			   )
3908
+			   || (
3909
+				   ! $for_this_model
3910
+				   && in_array(
3911
+					   $default_where_conditions_value,
3912
+					   [
3913
+						   EEM_Base::default_where_conditions_minimum_others,
3914
+						   EEM_Base::default_where_conditions_minimum_all,
3915
+					   ],
3916
+					   true
3917
+				   )
3918
+			   );
3919
+	}
3920
+
3921
+
3922
+	/**
3923
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3924
+	 * then we also add a special where condition which allows for that model's primary key
3925
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3926
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3927
+	 *
3928
+	 * @param array    $default_where_conditions
3929
+	 * @param array    $provided_where_conditions
3930
+	 * @param EEM_Base $model
3931
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3932
+	 * @return array @see
3933
+	 *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3934
+	 * @throws EE_Error
3935
+	 */
3936
+	private function _override_defaults_or_make_null_friendly(
3937
+		$default_where_conditions,
3938
+		$provided_where_conditions,
3939
+		$model,
3940
+		$model_relation_path
3941
+	) {
3942
+		$null_friendly_where_conditions = [];
3943
+		$none_overridden                = true;
3944
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3945
+		foreach ($default_where_conditions as $key => $val) {
3946
+			if (isset($provided_where_conditions[ $key ])) {
3947
+				$none_overridden = false;
3948
+			} else {
3949
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3950
+			}
3951
+		}
3952
+		if ($none_overridden && $default_where_conditions) {
3953
+			if ($model->has_primary_key_field()) {
3954
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3955
+																				   . "."
3956
+																				   . $model->primary_key_name() ] =
3957
+					['IS NULL'];
3958
+			}/*else{
3959 3959
                 //@todo NO PK, use other defaults
3960 3960
             }*/
3961
-        }
3962
-        return $null_friendly_where_conditions;
3963
-    }
3964
-
3965
-
3966
-    /**
3967
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3968
-     * default where conditions on all get_all, update, and delete queries done by this model.
3969
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3970
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3971
-     *
3972
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3973
-     * @return array @see
3974
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3975
-     * @throws EE_Error
3976
-     * @throws EE_Error
3977
-     */
3978
-    private function _get_default_where_conditions($model_relation_path = '')
3979
-    {
3980
-        if ($this->_ignore_where_strategy) {
3981
-            return [];
3982
-        }
3983
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3984
-    }
3985
-
3986
-
3987
-    /**
3988
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3989
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3990
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3991
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3992
-     * Similar to _get_default_where_conditions
3993
-     *
3994
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3995
-     * @return array @see
3996
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3997
-     * @throws EE_Error
3998
-     * @throws EE_Error
3999
-     */
4000
-    protected function _get_minimum_where_conditions($model_relation_path = '')
4001
-    {
4002
-        if ($this->_ignore_where_strategy) {
4003
-            return [];
4004
-        }
4005
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
4006
-    }
4007
-
4008
-
4009
-    /**
4010
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4011
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4012
-     *
4013
-     * @param EE_Model_Query_Info_Carrier $model_query_info
4014
-     * @return string
4015
-     * @throws EE_Error
4016
-     */
4017
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4018
-    {
4019
-        $selects = $this->_get_columns_to_select_for_this_model();
4020
-        foreach (
4021
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4022
-        ) {
4023
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4024
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4025
-            foreach ($other_model_selects as $key => $value) {
4026
-                $selects[] = $value;
4027
-            }
4028
-        }
4029
-        return implode(", ", $selects);
4030
-    }
4031
-
4032
-
4033
-    /**
4034
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4035
-     * So that's going to be the columns for all the fields on the model
4036
-     *
4037
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
4038
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4039
-     */
4040
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4041
-    {
4042
-        $fields                                       = $this->field_settings();
4043
-        $selects                                      = [];
4044
-        $table_alias_with_model_relation_chain_prefix =
4045
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4046
-                $model_relation_chain,
4047
-                $this->get_this_model_name()
4048
-            );
4049
-        foreach ($fields as $field_obj) {
4050
-            $selects[] = $table_alias_with_model_relation_chain_prefix
4051
-                         . $field_obj->get_table_alias()
4052
-                         . "."
4053
-                         . $field_obj->get_table_column()
4054
-                         . " AS '"
4055
-                         . $table_alias_with_model_relation_chain_prefix
4056
-                         . $field_obj->get_table_alias()
4057
-                         . "."
4058
-                         . $field_obj->get_table_column()
4059
-                         . "'";
4060
-        }
4061
-        // make sure we are also getting the PKs of each table
4062
-        $tables = $this->get_tables();
4063
-        if (count($tables) > 1) {
4064
-            foreach ($tables as $table_obj) {
4065
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4066
-                                       . $table_obj->get_fully_qualified_pk_column();
4067
-                if (! in_array($qualified_pk_column, $selects)) {
4068
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4069
-                }
4070
-            }
4071
-        }
4072
-        return $selects;
4073
-    }
4074
-
4075
-
4076
-    /**
4077
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4078
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4079
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4080
-     * SQL for joining, and the data types
4081
-     *
4082
-     * @param null|string                 $original_query_param
4083
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4084
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4085
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4086
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4087
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4088
-     *                                                          or 'Registration's
4089
-     * @param string                      $original_query_param what it originally was (eg
4090
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4091
-     *                                                          matches $query_param
4092
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4093
-     * @throws EE_Error
4094
-     */
4095
-    private function _extract_related_model_info_from_query_param(
4096
-        $query_param,
4097
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4098
-        $query_param_type,
4099
-        $original_query_param = null
4100
-    ) {
4101
-        if ($original_query_param === null) {
4102
-            $original_query_param = $query_param;
4103
-        }
4104
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4105
-        // check to see if we have a field on this model
4106
-        $this_model_fields = $this->field_settings(true);
4107
-        if (array_key_exists($query_param, $this_model_fields)) {
4108
-            $field_is_allowed = in_array(
4109
-                $query_param_type,
4110
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4111
-                true
4112
-            );
4113
-            if ($field_is_allowed) {
4114
-                return;
4115
-            }
4116
-            throw new EE_Error(
4117
-                sprintf(
4118
-                    esc_html__(
4119
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4120
-                        "event_espresso"
4121
-                    ),
4122
-                    $query_param,
4123
-                    get_class($this),
4124
-                    $query_param_type,
4125
-                    $original_query_param
4126
-                )
4127
-            );
4128
-        }
4129
-        // check if this is a special logic query param
4130
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4131
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4132
-            if ($operator_is_allowed) {
4133
-                return;
4134
-            }
4135
-            throw new EE_Error(
4136
-                sprintf(
4137
-                    esc_html__(
4138
-                        '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',
4139
-                        'event_espresso'
4140
-                    ),
4141
-                    implode('", "', $this->_logic_query_param_keys),
4142
-                    $query_param,
4143
-                    get_class($this),
4144
-                    '<br />',
4145
-                    "\t"
4146
-                    . ' $passed_in_query_info = <pre>'
4147
-                    . print_r($passed_in_query_info, true)
4148
-                    . '</pre>'
4149
-                    . "\n\t"
4150
-                    . ' $query_param_type = '
4151
-                    . $query_param_type
4152
-                    . "\n\t"
4153
-                    . ' $original_query_param = '
4154
-                    . $original_query_param
4155
-                )
4156
-            );
4157
-        }
4158
-        // check if it's a custom selection
4159
-        if (
4160
-            $this->_custom_selections instanceof CustomSelects
4161
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4162
-        ) {
4163
-            return;
4164
-        }
4165
-        // check if has a model name at the beginning
4166
-        // and
4167
-        // check if it's a field on a related model
4168
-        if (
4169
-            $this->extractJoinModelFromQueryParams(
4170
-                $passed_in_query_info,
4171
-                $query_param,
4172
-                $original_query_param,
4173
-                $query_param_type
4174
-            )
4175
-        ) {
4176
-            return;
4177
-        }
4178
-
4179
-        // ok so $query_param didn't start with a model name
4180
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4181
-        // it's wack, that's what it is
4182
-        throw new EE_Error(
4183
-            sprintf(
4184
-                esc_html__(
4185
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4186
-                    "event_espresso"
4187
-                ),
4188
-                $query_param,
4189
-                get_class($this),
4190
-                $query_param_type,
4191
-                $original_query_param
4192
-            )
4193
-        );
4194
-    }
4195
-
4196
-
4197
-    /**
4198
-     * Extracts any possible join model information from the provided possible_join_string.
4199
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4200
-     * join
4201
-     * parts that should be added to the query.
4202
-     *
4203
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4204
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4205
-     * @param null|string                 $original_query_param
4206
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4207
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4208
-     *                                                           etc.)
4209
-     * @return bool  returns true if a join was added and false if not.
4210
-     * @throws EE_Error
4211
-     */
4212
-    private function extractJoinModelFromQueryParams(
4213
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4214
-        $possible_join_string,
4215
-        $original_query_param,
4216
-        $query_parameter_type
4217
-    ) {
4218
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4219
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4220
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4221
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4222
-                if ($possible_join_string === '') {
4223
-                    // nothing left to $query_param
4224
-                    // we should actually end in a field name, not a model like this!
4225
-                    throw new EE_Error(
4226
-                        sprintf(
4227
-                            esc_html__(
4228
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4229
-                                "event_espresso"
4230
-                            ),
4231
-                            $possible_join_string,
4232
-                            $query_parameter_type,
4233
-                            get_class($this),
4234
-                            $valid_related_model_name
4235
-                        )
4236
-                    );
4237
-                }
4238
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4239
-                $related_model_obj->_extract_related_model_info_from_query_param(
4240
-                    $possible_join_string,
4241
-                    $query_info_carrier,
4242
-                    $query_parameter_type,
4243
-                    $original_query_param
4244
-                );
4245
-                return true;
4246
-            }
4247
-            if ($possible_join_string === $valid_related_model_name) {
4248
-                $this->_add_join_to_model(
4249
-                    $valid_related_model_name,
4250
-                    $query_info_carrier,
4251
-                    $original_query_param
4252
-                );
4253
-                return true;
4254
-            }
4255
-        }
4256
-        return false;
4257
-    }
4258
-
4259
-
4260
-    /**
4261
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4262
-     *
4263
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4264
-     * @throws EE_Error
4265
-     */
4266
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4267
-    {
4268
-        if (
4269
-            $this->_custom_selections instanceof CustomSelects
4270
-            && (
4271
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4272
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4273
-            )
4274
-        ) {
4275
-            $original_selects = $this->_custom_selections->originalSelects();
4276
-            foreach ($original_selects as $alias => $select_configuration) {
4277
-                $this->extractJoinModelFromQueryParams(
4278
-                    $query_info_carrier,
4279
-                    $select_configuration[0],
4280
-                    $select_configuration[0],
4281
-                    'custom_selects'
4282
-                );
4283
-            }
4284
-        }
4285
-    }
4286
-
4287
-
4288
-    /**
4289
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4290
-     * and store it on $passed_in_query_info
4291
-     *
4292
-     * @param string                      $model_name
4293
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4294
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4295
-     *                                                          model and $model_name. Eg, if we are querying Event,
4296
-     *                                                          and are adding a join to 'Payment' with the original
4297
-     *                                                          query param key
4298
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4299
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4300
-     *                                                          Payment wants to add default query params so that it
4301
-     *                                                          will know what models to prepend onto its default query
4302
-     *                                                          params or in case it wants to rename tables (in case
4303
-     *                                                          there are multiple joins to the same table)
4304
-     * @return void
4305
-     * @throws EE_Error
4306
-     */
4307
-    private function _add_join_to_model(
4308
-        $model_name,
4309
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4310
-        $original_query_param
4311
-    ) {
4312
-        $relation_obj         = $this->related_settings_for($model_name);
4313
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4314
-        // check if the relation is HABTM, because then we're essentially doing two joins
4315
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4316
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4317
-            $join_model_obj = $relation_obj->get_join_model();
4318
-            // replace the model specified with the join model for this relation chain, whi
4319
-            $relation_chain_to_join_model =
4320
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4321
-                    $model_name,
4322
-                    $join_model_obj->get_this_model_name(),
4323
-                    $model_relation_chain
4324
-                );
4325
-            $passed_in_query_info->merge(
4326
-                new EE_Model_Query_Info_Carrier(
4327
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4328
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4329
-                )
4330
-            );
4331
-        }
4332
-        // now just join to the other table pointed to by the relation object, and add its data types
4333
-        $passed_in_query_info->merge(
4334
-            new EE_Model_Query_Info_Carrier(
4335
-                [$model_relation_chain => $model_name],
4336
-                $relation_obj->get_join_statement($model_relation_chain)
4337
-            )
4338
-        );
4339
-    }
4340
-
4341
-
4342
-    /**
4343
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4344
-     *
4345
-     * @param array $where_params @see
4346
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4347
-     * @return string of SQL
4348
-     * @throws EE_Error
4349
-     */
4350
-    private function _construct_where_clause($where_params)
4351
-    {
4352
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4353
-        if ($SQL) {
4354
-            return " WHERE " . $SQL;
4355
-        }
4356
-        return '';
4357
-    }
4358
-
4359
-
4360
-    /**
4361
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4362
-     * and should be passed HAVING parameters, not WHERE parameters
4363
-     *
4364
-     * @param array $having_params
4365
-     * @return string
4366
-     * @throws EE_Error
4367
-     */
4368
-    private function _construct_having_clause($having_params)
4369
-    {
4370
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4371
-        if ($SQL) {
4372
-            return " HAVING " . $SQL;
4373
-        }
4374
-        return '';
4375
-    }
4376
-
4377
-
4378
-    /**
4379
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4380
-     * Event_Meta.meta_value = 'foo'))"
4381
-     *
4382
-     * @param array  $where_params @see
4383
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4384
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4385
-     * @return string of SQL
4386
-     * @throws EE_Error
4387
-     */
4388
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4389
-    {
4390
-        $where_clauses = [];
4391
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4392
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4393
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4394
-                switch ($query_param) {
4395
-                    case 'not':
4396
-                    case 'NOT':
4397
-                        $where_clauses[] = "! ("
4398
-                                           . $this->_construct_condition_clause_recursive(
4399
-                                               $op_and_value_or_sub_condition,
4400
-                                               $glue
4401
-                                           )
4402
-                                           . ")";
4403
-                        break;
4404
-                    case 'and':
4405
-                    case 'AND':
4406
-                        $where_clauses[] = " ("
4407
-                                           . $this->_construct_condition_clause_recursive(
4408
-                                               $op_and_value_or_sub_condition,
4409
-                                               ' AND '
4410
-                                           )
4411
-                                           . ")";
4412
-                        break;
4413
-                    case 'or':
4414
-                    case 'OR':
4415
-                        $where_clauses[] = " ("
4416
-                                           . $this->_construct_condition_clause_recursive(
4417
-                                               $op_and_value_or_sub_condition,
4418
-                                               ' OR '
4419
-                                           )
4420
-                                           . ")";
4421
-                        break;
4422
-                }
4423
-            } else {
4424
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4425
-                // if it's not a normal field, maybe it's a custom selection?
4426
-                if (! $field_obj) {
4427
-                    if ($this->_custom_selections instanceof CustomSelects) {
4428
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4429
-                    } else {
4430
-                        throw new EE_Error(
4431
-                            sprintf(
4432
-                                esc_html__(
4433
-                                    "%s is neither a valid model field name, nor a custom selection",
4434
-                                    "event_espresso"
4435
-                                ),
4436
-                                $query_param
4437
-                            )
4438
-                        );
4439
-                    }
4440
-                }
4441
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4442
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4443
-            }
4444
-        }
4445
-        return $where_clauses
4446
-            ? implode($glue, $where_clauses)
4447
-            : '';
4448
-    }
4449
-
4450
-
4451
-    /**
4452
-     * Takes the input parameter and extract the table name (alias) and column name
4453
-     *
4454
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4455
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4456
-     * @throws EE_Error
4457
-     */
4458
-    private function _deduce_column_name_from_query_param($query_param)
4459
-    {
4460
-        $field = $this->_deduce_field_from_query_param($query_param);
4461
-        if ($field) {
4462
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4463
-                $field->get_model_name(),
4464
-                $query_param
4465
-            );
4466
-            return $table_alias_prefix . $field->get_qualified_column();
4467
-        }
4468
-        if (
4469
-            $this->_custom_selections instanceof CustomSelects
4470
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4471
-        ) {
4472
-            // maybe it's custom selection item?
4473
-            // if so, just use it as the "column name"
4474
-            return $query_param;
4475
-        }
4476
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4477
-            ? implode(',', $this->_custom_selections->columnAliases())
4478
-            : '';
4479
-        throw new EE_Error(
4480
-            sprintf(
4481
-                esc_html__(
4482
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4483
-                    "event_espresso"
4484
-                ),
4485
-                $query_param,
4486
-                $custom_select_aliases
4487
-            )
4488
-        );
4489
-    }
4490
-
4491
-
4492
-    /**
4493
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4494
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4495
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4496
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4497
-     *
4498
-     * @param string $condition_query_param_key
4499
-     * @return string
4500
-     */
4501
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4502
-    {
4503
-        $pos_of_star = strpos($condition_query_param_key, '*');
4504
-        if ($pos_of_star === false) {
4505
-            return $condition_query_param_key;
4506
-        }
4507
-        return substr($condition_query_param_key, 0, $pos_of_star);
4508
-    }
4509
-
4510
-
4511
-    /**
4512
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4513
-     *
4514
-     * @param array|string               $op_and_value
4515
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4516
-     * @return string
4517
-     * @throws EE_Error
4518
-     */
4519
-    private function _construct_op_and_value($op_and_value, $field_obj)
4520
-    {
4521
-        $operator = '=';
4522
-        $value    = $op_and_value;
4523
-        if (is_array($op_and_value)) {
4524
-            $operator = isset($op_and_value[0])
4525
-                ? $this->_prepare_operator_for_sql($op_and_value[0])
4526
-                : null;
4527
-            if (! $operator) {
4528
-                $php_array_like_string = [];
4529
-                foreach ($op_and_value as $key => $value) {
4530
-                    $php_array_like_string[] = "$key=>$value";
4531
-                }
4532
-                throw new EE_Error(
4533
-                    sprintf(
4534
-                        esc_html__(
4535
-                            "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))",
4536
-                            "event_espresso"
4537
-                        ),
4538
-                        implode(",", $php_array_like_string)
4539
-                    )
4540
-                );
4541
-            }
4542
-            $value = $op_and_value[1] ?? null;
4543
-        }
4544
-
4545
-        // check to see if the value is actually another field
4546
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4547
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4548
-        }
4549
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4550
-            // in this case, the value should be an array, or at least a comma-separated list
4551
-            // it will need to handle a little differently
4552
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4553
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4554
-            return $operator . SP . $cleaned_value;
4555
-        }
4556
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4557
-            // the value should be an array with count of two.
4558
-            if (count($value) !== 2) {
4559
-                throw new EE_Error(
4560
-                    sprintf(
4561
-                        esc_html__(
4562
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4563
-                            'event_espresso'
4564
-                        ),
4565
-                        "BETWEEN"
4566
-                    )
4567
-                );
4568
-            }
4569
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4570
-            return $operator . SP . $cleaned_value;
4571
-        }
4572
-        if (in_array($operator, $this->valid_null_style_operators())) {
4573
-            if ($value !== null) {
4574
-                throw new EE_Error(
4575
-                    sprintf(
4576
-                        esc_html__(
4577
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4578
-                            "event_espresso"
4579
-                        ),
4580
-                        $value,
4581
-                        $operator
4582
-                    )
4583
-                );
4584
-            }
4585
-            return $operator;
4586
-        }
4587
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4588
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4589
-            // remove other junk. So just treat it as a string.
4590
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4591
-        }
4592
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4593
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4594
-        }
4595
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4596
-            throw new EE_Error(
4597
-                sprintf(
4598
-                    esc_html__(
4599
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4600
-                        'event_espresso'
4601
-                    ),
4602
-                    $operator,
4603
-                    $operator
4604
-                )
4605
-            );
4606
-        }
4607
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4608
-            throw new EE_Error(
4609
-                sprintf(
4610
-                    esc_html__(
4611
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4612
-                        'event_espresso'
4613
-                    ),
4614
-                    $operator,
4615
-                    $operator
4616
-                )
4617
-            );
4618
-        }
4619
-        throw new EE_Error(
4620
-            sprintf(
4621
-                esc_html__(
4622
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4623
-                    "event_espresso"
4624
-                ),
4625
-                http_build_query($op_and_value)
4626
-            )
4627
-        );
4628
-    }
4629
-
4630
-
4631
-    /**
4632
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4633
-     *
4634
-     * @param array                      $values
4635
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4636
-     *                                              '%s'
4637
-     * @return string
4638
-     * @throws EE_Error
4639
-     */
4640
-    public function _construct_between_value($values, $field_obj)
4641
-    {
4642
-        $cleaned_values = [];
4643
-        foreach ($values as $value) {
4644
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4645
-        }
4646
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4647
-    }
4648
-
4649
-
4650
-    /**
4651
-     * Takes an array or a comma-separated list of $values and cleans them
4652
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4653
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4654
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4655
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4656
-     *
4657
-     * @param mixed                      $values    array or comma-separated string
4658
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4659
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4660
-     * @throws EE_Error
4661
-     */
4662
-    public function _construct_in_value($values, $field_obj)
4663
-    {
4664
-        $prepped = [];
4665
-        // check if the value is a CSV list
4666
-        if (is_string($values)) {
4667
-            // in which case, turn it into an array
4668
-            $values = explode(',', $values);
4669
-        }
4670
-        // make sure we only have one of each value in the list
4671
-        $values = array_unique($values);
4672
-        foreach ($values as $value) {
4673
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4674
-        }
4675
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4676
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4677
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4678
-        if (empty($prepped)) {
4679
-            $all_fields  = $this->field_settings();
4680
-            $first_field = reset($all_fields);
4681
-            $main_table  = $this->_get_main_table();
4682
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4683
-        }
4684
-        return '(' . implode(',', $prepped) . ')';
4685
-    }
4686
-
4687
-
4688
-    /**
4689
-     * @param mixed                      $value
4690
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4691
-     * @return false|null|string
4692
-     * @throws EE_Error
4693
-     */
4694
-    private function _wpdb_prepare_using_field($value, $field_obj)
4695
-    {
4696
-        /** @type WPDB $wpdb */
4697
-        global $wpdb;
4698
-        if ($field_obj instanceof EE_Model_Field_Base) {
4699
-            return $wpdb->prepare(
4700
-                $field_obj->get_wpdb_data_type(),
4701
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4702
-            );
4703
-        } //$field_obj should really just be a data type
4704
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4705
-            throw new EE_Error(
4706
-                sprintf(
4707
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4708
-                    $field_obj,
4709
-                    implode(",", $this->_valid_wpdb_data_types)
4710
-                )
4711
-            );
4712
-        }
4713
-        return $wpdb->prepare($field_obj, $value);
4714
-    }
4715
-
4716
-
4717
-    /**
4718
-     * Takes the input parameter and finds the model field that it indicates.
4719
-     *
4720
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4721
-     * @return EE_Model_Field_Base
4722
-     * @throws EE_Error
4723
-     */
4724
-    protected function _deduce_field_from_query_param($query_param_name)
4725
-    {
4726
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4727
-        // which will help us find the database table and column
4728
-        $query_param_parts = explode(".", $query_param_name);
4729
-        if (empty($query_param_parts)) {
4730
-            throw new EE_Error(
4731
-                sprintf(
4732
-                    esc_html__(
4733
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4734
-                        'event_espresso'
4735
-                    ),
4736
-                    $query_param_name
4737
-                )
4738
-            );
4739
-        }
4740
-        $number_of_parts       = count($query_param_parts);
4741
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4742
-        if ($number_of_parts === 1) {
4743
-            $field_name = $last_query_param_part;
4744
-            $model_obj  = $this;
4745
-        } else {// $number_of_parts >= 2
4746
-            // the last part is the column name, and there are only 2parts. therefore...
4747
-            $field_name = $last_query_param_part;
4748
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4749
-        }
4750
-        try {
4751
-            return $model_obj->field_settings_for($field_name);
4752
-        } catch (EE_Error $e) {
4753
-            return null;
4754
-        }
4755
-    }
4756
-
4757
-
4758
-    /**
4759
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4760
-     * alias and column which corresponds to it
4761
-     *
4762
-     * @param string $field_name
4763
-     * @return string
4764
-     * @throws EE_Error
4765
-     */
4766
-    public function _get_qualified_column_for_field($field_name)
4767
-    {
4768
-        $all_fields = $this->field_settings();
4769
-        $field      = $all_fields[ $field_name ] ?? false;
4770
-        if ($field) {
4771
-            return $field->get_qualified_column();
4772
-        }
4773
-        throw new EE_Error(
4774
-            sprintf(
4775
-                esc_html__(
4776
-                    "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.",
4777
-                    'event_espresso'
4778
-                ),
4779
-                $field_name,
4780
-                get_class($this)
4781
-            )
4782
-        );
4783
-    }
4784
-
4785
-
4786
-    /**
4787
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4788
-     * Example usage:
4789
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4790
-     *      array(),
4791
-     *      ARRAY_A,
4792
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4793
-     *  );
4794
-     * is equivalent to
4795
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4796
-     * and
4797
-     *  EEM_Event::instance()->get_all_wpdb_results(
4798
-     *      array(
4799
-     *          array(
4800
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4801
-     *          ),
4802
-     *          ARRAY_A,
4803
-     *          implode(
4804
-     *              ', ',
4805
-     *              array_merge(
4806
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4807
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4808
-     *              )
4809
-     *          )
4810
-     *      )
4811
-     *  );
4812
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4813
-     *
4814
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4815
-     *                                            and the one whose fields you are selecting for example: when querying
4816
-     *                                            tickets model and selecting fields from the tickets model you would
4817
-     *                                            leave this parameter empty, because no models are needed to join
4818
-     *                                            between the queried model and the selected one. Likewise when
4819
-     *                                            querying the datetime model and selecting fields from the tickets
4820
-     *                                            model, it would also be left empty, because there is a direct
4821
-     *                                            relation from datetimes to tickets, so no model is needed to join
4822
-     *                                            them together. However, when querying from the event model and
4823
-     *                                            selecting fields from the ticket model, you should provide the string
4824
-     *                                            'Datetime', indicating that the event model must first join to the
4825
-     *                                            datetime model in order to find its relation to ticket model.
4826
-     *                                            Also, when querying from the venue model and selecting fields from
4827
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4828
-     *                                            indicating you need to join the venue model to the event model,
4829
-     *                                            to the datetime model, in order to find its relation to the ticket
4830
-     *                                            model. This string is used to deduce the prefix that gets added onto
4831
-     *                                            the models' tables qualified columns
4832
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4833
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4834
-     *                                            qualified column names
4835
-     * @return array|string
4836
-     */
4837
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4838
-    {
4839
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4840
-                ? ''
4841
-                : '__');
4842
-        $qualified_columns = [];
4843
-        foreach ($this->field_settings() as $field_name => $field) {
4844
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4845
-        }
4846
-        return $return_string
4847
-            ? implode(', ', $qualified_columns)
4848
-            : $qualified_columns;
4849
-    }
4850
-
4851
-
4852
-    /**
4853
-     * constructs the select use on special limit joins
4854
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4855
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4856
-     * (as that is typically where the limits would be set).
4857
-     *
4858
-     * @param string       $table_alias The table the select is being built for
4859
-     * @param mixed|string $limit       The limit for this select
4860
-     * @return string                The final select join element for the query.
4861
-     * @throws EE_Error
4862
-     * @throws EE_Error
4863
-     */
4864
-    public function _construct_limit_join_select($table_alias, $limit)
4865
-    {
4866
-        $SQL = '';
4867
-        foreach ($this->_tables as $table_obj) {
4868
-            if ($table_obj instanceof EE_Primary_Table) {
4869
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4870
-                    ? $table_obj->get_select_join_limit($limit)
4871
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4872
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4873
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4874
-                    ? $table_obj->get_select_join_limit_join($limit)
4875
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4876
-            }
4877
-        }
4878
-        return $SQL;
4879
-    }
4880
-
4881
-
4882
-    /**
4883
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4884
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4885
-     *
4886
-     * @return string SQL
4887
-     * @throws EE_Error
4888
-     */
4889
-    public function _construct_internal_join()
4890
-    {
4891
-        $SQL = $this->_get_main_table()->get_table_sql();
4892
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4893
-        return $SQL;
4894
-    }
4895
-
4896
-
4897
-    /**
4898
-     * Constructs the SQL for joining all the tables on this model.
4899
-     * Normally $alias should be the primary table's alias, but in cases where
4900
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4901
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4902
-     * alias, this will construct SQL like:
4903
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4904
-     * With $alias being a secondary table's alias, this will construct SQL like:
4905
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4906
-     *
4907
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4908
-     * @return string
4909
-     * @throws EE_Error
4910
-     * @throws EE_Error
4911
-     */
4912
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4913
-    {
4914
-        $SQL               = '';
4915
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4916
-        foreach ($this->_tables as $table_obj) {
4917
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4918
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4919
-                    // so we're joining to this table, meaning the table is already in
4920
-                    // the FROM statement, BUT the primary table isn't. So we want
4921
-                    // to add the inverse join sql
4922
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4923
-                } else {
4924
-                    // just add a regular JOIN to this table from the primary table
4925
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4926
-                }
4927
-            }// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4928
-        }
4929
-        return $SQL;
4930
-    }
4931
-
4932
-
4933
-    /**
4934
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4935
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4936
-     * their data type (eg, '%s', '%d', etc)
4937
-     *
4938
-     * @return array
4939
-     */
4940
-    public function _get_data_types()
4941
-    {
4942
-        $data_types = [];
4943
-        foreach ($this->field_settings() as $field_obj) {
4944
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4945
-            /** @var $field_obj EE_Model_Field_Base */
4946
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4947
-        }
4948
-        return $data_types;
4949
-    }
4950
-
4951
-
4952
-    /**
4953
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4954
-     *
4955
-     * @param string $model_name
4956
-     * @return EEM_Base
4957
-     * @throws EE_Error
4958
-     */
4959
-    public function get_related_model_obj($model_name)
4960
-    {
4961
-        $model_classname = "EEM_" . $model_name;
4962
-        if (! class_exists($model_classname)) {
4963
-            throw new EE_Error(
4964
-                sprintf(
4965
-                    esc_html__(
4966
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4967
-                        'event_espresso'
4968
-                    ),
4969
-                    $model_name,
4970
-                    $model_classname
4971
-                )
4972
-            );
4973
-        }
4974
-        return call_user_func($model_classname . "::instance");
4975
-    }
4976
-
4977
-
4978
-    /**
4979
-     * Returns the array of EE_ModelRelations for this model.
4980
-     *
4981
-     * @return EE_Model_Relation_Base[]
4982
-     */
4983
-    public function relation_settings()
4984
-    {
4985
-        return $this->_model_relations;
4986
-    }
4987
-
4988
-
4989
-    /**
4990
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4991
-     * because without THOSE models, this model probably doesn't have much purpose.
4992
-     * (Eg, without an event, datetimes have little purpose.)
4993
-     *
4994
-     * @return EE_Belongs_To_Relation[]
4995
-     */
4996
-    public function belongs_to_relations()
4997
-    {
4998
-        $belongs_to_relations = [];
4999
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
5000
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
5001
-                $belongs_to_relations[ $model_name ] = $relation_obj;
5002
-            }
5003
-        }
5004
-        return $belongs_to_relations;
5005
-    }
5006
-
5007
-
5008
-    /**
5009
-     * Returns the specified EE_Model_Relation, or throws an exception
5010
-     *
5011
-     * @param string $relation_name name of relation, key in $this->_relatedModels
5012
-     * @return EE_Model_Relation_Base
5013
-     * @throws EE_Error
5014
-     */
5015
-    public function related_settings_for($relation_name)
5016
-    {
5017
-        $relatedModels = $this->relation_settings();
5018
-        if (! array_key_exists($relation_name, $relatedModels)) {
5019
-            throw new EE_Error(
5020
-                sprintf(
5021
-                    esc_html__(
5022
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5023
-                        'event_espresso'
5024
-                    ),
5025
-                    $relation_name,
5026
-                    $this->_get_class_name(),
5027
-                    implode(', ', array_keys($relatedModels))
5028
-                )
5029
-            );
5030
-        }
5031
-        return $relatedModels[ $relation_name ];
5032
-    }
5033
-
5034
-
5035
-    /**
5036
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5037
-     * fields
5038
-     *
5039
-     * @param string  $fieldName
5040
-     * @param boolean $include_db_only_fields
5041
-     * @return EE_Model_Field_Base
5042
-     * @throws EE_Error
5043
-     */
5044
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
5045
-    {
5046
-        $fieldSettings = $this->field_settings($include_db_only_fields);
5047
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5048
-            throw new EE_Error(
5049
-                sprintf(
5050
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5051
-                    $fieldName,
5052
-                    get_class($this)
5053
-                )
5054
-            );
5055
-        }
5056
-        return $fieldSettings[ $fieldName ];
5057
-    }
5058
-
5059
-
5060
-    /**
5061
-     * Checks if this field exists on this model
5062
-     *
5063
-     * @param string $fieldName a key in the model's _field_settings array
5064
-     * @return boolean
5065
-     */
5066
-    public function has_field($fieldName)
5067
-    {
5068
-        $fieldSettings = $this->field_settings(true);
5069
-        if (isset($fieldSettings[ $fieldName ])) {
5070
-            return true;
5071
-        }
5072
-        return false;
5073
-    }
5074
-
5075
-
5076
-    /**
5077
-     * Returns whether or not this model has a relation to the specified model
5078
-     *
5079
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5080
-     * @return boolean
5081
-     */
5082
-    public function has_relation($relation_name)
5083
-    {
5084
-        $relations = $this->relation_settings();
5085
-        if (isset($relations[ $relation_name ])) {
5086
-            return true;
5087
-        }
5088
-        return false;
5089
-    }
5090
-
5091
-
5092
-    /**
5093
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5094
-     * Eg, on EE_Answer that would be ANS_ID field object
5095
-     *
5096
-     * @param $field_obj
5097
-     * @return boolean
5098
-     */
5099
-    public function is_primary_key_field($field_obj): bool
5100
-    {
5101
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5102
-    }
5103
-
5104
-
5105
-    /**
5106
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5107
-     * Eg, on EE_Answer that would be ANS_ID field object
5108
-     *
5109
-     * @return EE_Primary_Key_Field_Base
5110
-     * @throws EE_Error
5111
-     */
5112
-    public function get_primary_key_field()
5113
-    {
5114
-        if ($this->_primary_key_field === null) {
5115
-            foreach ($this->field_settings(true) as $field_obj) {
5116
-                if ($this->is_primary_key_field($field_obj)) {
5117
-                    $this->_primary_key_field = $field_obj;
5118
-                    break;
5119
-                }
5120
-            }
5121
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5122
-                throw new EE_Error(
5123
-                    sprintf(
5124
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5125
-                        get_class($this)
5126
-                    )
5127
-                );
5128
-            }
5129
-        }
5130
-        return $this->_primary_key_field;
5131
-    }
5132
-
5133
-
5134
-    /**
5135
-     * Returns whether or not not there is a primary key on this model.
5136
-     * Internally does some caching.
5137
-     *
5138
-     * @return boolean
5139
-     */
5140
-    public function has_primary_key_field()
5141
-    {
5142
-        if ($this->_has_primary_key_field === null) {
5143
-            try {
5144
-                $this->get_primary_key_field();
5145
-                $this->_has_primary_key_field = true;
5146
-            } catch (EE_Error $e) {
5147
-                $this->_has_primary_key_field = false;
5148
-            }
5149
-        }
5150
-        return $this->_has_primary_key_field;
5151
-    }
5152
-
5153
-
5154
-    /**
5155
-     * Finds the first field of type $field_class_name.
5156
-     *
5157
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5158
-     *                                 EE_Foreign_Key_Field, etc
5159
-     * @return EE_Model_Field_Base or null if none is found
5160
-     */
5161
-    public function get_a_field_of_type($field_class_name)
5162
-    {
5163
-        foreach ($this->field_settings() as $field) {
5164
-            if ($field instanceof $field_class_name) {
5165
-                return $field;
5166
-            }
5167
-        }
5168
-        return null;
5169
-    }
5170
-
5171
-
5172
-    /**
5173
-     * Gets a foreign key field pointing to model.
5174
-     *
5175
-     * @param string $model_name eg Event, Registration, not EEM_Event
5176
-     * @return EE_Foreign_Key_Field_Base
5177
-     * @throws EE_Error
5178
-     */
5179
-    public function get_foreign_key_to($model_name)
5180
-    {
5181
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
-            foreach ($this->field_settings() as $field) {
5183
-                if (
5184
-                    $field instanceof EE_Foreign_Key_Field_Base
5185
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5186
-                ) {
5187
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5188
-                    break;
5189
-                }
5190
-            }
5191
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5192
-                throw new EE_Error(
5193
-                    sprintf(
5194
-                        esc_html__(
5195
-                            "There is no foreign key field pointing to model %s on model %s",
5196
-                            'event_espresso'
5197
-                        ),
5198
-                        $model_name,
5199
-                        get_class($this)
5200
-                    )
5201
-                );
5202
-            }
5203
-        }
5204
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5205
-    }
5206
-
5207
-
5208
-    /**
5209
-     * Gets the table name (including $wpdb->prefix) for the table alias
5210
-     *
5211
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5212
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5213
-     *                            Either one works
5214
-     * @return string
5215
-     */
5216
-    public function get_table_for_alias($table_alias)
5217
-    {
5218
-        $table_alias_sans_model_relation_chain_prefix =
5219
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5220
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5221
-    }
5222
-
5223
-
5224
-    /**
5225
-     * Returns a flat array of all field son this model, instead of organizing them
5226
-     * by table_alias as they are in the constructor.
5227
-     *
5228
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5229
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5230
-     */
5231
-    public function field_settings($include_db_only_fields = false)
5232
-    {
5233
-        if ($include_db_only_fields) {
5234
-            if ($this->_cached_fields === null) {
5235
-                $this->_cached_fields = [];
5236
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5237
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5239
-                    }
5240
-                }
5241
-            }
5242
-            return $this->_cached_fields;
5243
-        }
5244
-        if ($this->_cached_fields_non_db_only === null) {
5245
-            $this->_cached_fields_non_db_only = [];
5246
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5247
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
-                    /** @var $field_obj EE_Model_Field_Base */
5249
-                    if (! $field_obj->is_db_only_field()) {
5250
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5251
-                    }
5252
-                }
5253
-            }
5254
-        }
5255
-        return $this->_cached_fields_non_db_only;
5256
-    }
5257
-
5258
-
5259
-    /**
5260
-     *        cycle though array of attendees and create objects out of each item
5261
-     *
5262
-     * @access        private
5263
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5264
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5265
-     *                           numerically indexed)
5266
-     * @throws EE_Error
5267
-     * @throws ReflectionException
5268
-     */
5269
-    protected function _create_objects($rows = [])
5270
-    {
5271
-        $array_of_objects = [];
5272
-        if (empty($rows)) {
5273
-            return [];
5274
-        }
5275
-        $count_if_model_has_no_primary_key = 0;
5276
-        $has_primary_key                   = $this->has_primary_key_field();
5277
-        $primary_key_field                 = $has_primary_key
5278
-            ? $this->get_primary_key_field()
5279
-            : null;
5280
-        foreach ((array) $rows as $row) {
5281
-            if (empty($row)) {
5282
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5283
-                return [];
5284
-            }
5285
-            // check if we've already set this object in the results array,
5286
-            // in which case there's no need to process it further (again)
5287
-            if ($has_primary_key) {
5288
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5289
-                    $row,
5290
-                    $primary_key_field->get_qualified_column(),
5291
-                    $primary_key_field->get_table_column()
5292
-                );
5293
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5294
-                    continue;
5295
-                }
5296
-            }
5297
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5298
-            if (! $classInstance) {
5299
-                throw new EE_Error(
5300
-                    sprintf(
5301
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5302
-                        $this->get_this_model_name(),
5303
-                        http_build_query($row)
5304
-                    )
5305
-                );
5306
-            }
5307
-            // set the timezone on the instantiated objects
5308
-            $classInstance->set_timezone($this->_timezone);
5309
-            // make sure if there is any timezone setting present that we set the timezone for the object
5310
-            $key                      = $has_primary_key
5311
-                ? $classInstance->ID()
5312
-                : $count_if_model_has_no_primary_key++;
5313
-            $array_of_objects[ $key ] = $classInstance;
5314
-            // also, for all the relations of type BelongsTo, see if we can cache
5315
-            // those related models
5316
-            // (we could do this for other relations too, but if there are conditions
5317
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5318
-            // so it requires a little more thought than just caching them immediately...)
5319
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5320
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5321
-                    // check if this model's INFO is present. If so, cache it on the model
5322
-                    $other_model           = $relation_obj->get_other_model();
5323
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5324
-                    // if we managed to make a model object from the results, cache it on the main model object
5325
-                    if ($other_model_obj_maybe) {
5326
-                        // set timezone on these other model objects if they are present
5327
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5328
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5329
-                    }
5330
-                }
5331
-            }
5332
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5333
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5334
-            // the field in the CustomSelects object
5335
-            if ($this->_custom_selections instanceof CustomSelects) {
5336
-                $classInstance->setCustomSelectsValues(
5337
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5338
-                );
5339
-            }
5340
-        }
5341
-        return $array_of_objects;
5342
-    }
5343
-
5344
-
5345
-    /**
5346
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5347
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5348
-     *
5349
-     * @param array $db_results_row
5350
-     * @return array
5351
-     */
5352
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5353
-    {
5354
-        $results = [];
5355
-        if ($this->_custom_selections instanceof CustomSelects) {
5356
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5357
-                if (isset($db_results_row[ $alias ])) {
5358
-                    $results[ $alias ] = $this->convertValueToDataType(
5359
-                        $db_results_row[ $alias ],
5360
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5361
-                    );
5362
-                }
5363
-            }
5364
-        }
5365
-        return $results;
5366
-    }
5367
-
5368
-
5369
-    /**
5370
-     * This will set the value for the given alias
5371
-     *
5372
-     * @param string $value
5373
-     * @param string $datatype (one of %d, %s, %f)
5374
-     * @return int|string|float (int for %d, string for %s, float for %f)
5375
-     */
5376
-    protected function convertValueToDataType($value, $datatype)
5377
-    {
5378
-        switch ($datatype) {
5379
-            case '%f':
5380
-                return (float) $value;
5381
-            case '%d':
5382
-                return (int) $value;
5383
-            default:
5384
-                return (string) $value;
5385
-        }
5386
-    }
5387
-
5388
-
5389
-    /**
5390
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5391
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5392
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5393
-     * object (as set in the model_field!).
5394
-     *
5395
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5396
-     * @throws EE_Error
5397
-     * @throws ReflectionException
5398
-     */
5399
-    public function create_default_object()
5400
-    {
5401
-        $this_model_fields_and_values = [];
5402
-        // setup the row using default values;
5403
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5404
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5405
-        }
5406
-        $className = $this->_get_class_name();
5407
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5408
-    }
5409
-
5410
-
5411
-    /**
5412
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5413
-     *                             or an stdClass where each property is the name of a column,
5414
-     * @return EE_Base_Class
5415
-     * @throws EE_Error
5416
-     * @throws ReflectionException
5417
-     */
5418
-    public function instantiate_class_from_array_or_object($cols_n_values)
5419
-    {
5420
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5421
-            $cols_n_values = get_object_vars($cols_n_values);
5422
-        }
5423
-        $primary_key = null;
5424
-        // make sure the array only has keys that are fields/columns on this model
5425
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5426
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5427
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5428
-        }
5429
-        $className = $this->_get_class_name();
5430
-        // check we actually found results that we can use to build our model object
5431
-        // if not, return null
5432
-        if ($this->has_primary_key_field()) {
5433
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5434
-                return null;
5435
-            }
5436
-        } elseif ($this->unique_indexes()) {
5437
-            $first_column = reset($this_model_fields_n_values);
5438
-            if (empty($first_column)) {
5439
-                return null;
5440
-            }
5441
-        }
5442
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5443
-        if ($primary_key) {
5444
-            $classInstance = $this->get_from_entity_map($primary_key);
5445
-            if (! $classInstance) {
5446
-                $classInstance = EE_Registry::instance()
5447
-                                            ->load_class(
5448
-                                                $className,
5449
-                                                [$this_model_fields_n_values, $this->_timezone],
5450
-                                                true,
5451
-                                                false
5452
-                                            );
5453
-                // add this new object to the entity map
5454
-                $classInstance = $this->add_to_entity_map($classInstance);
5455
-            }
5456
-        } else {
5457
-            $classInstance = EE_Registry::instance()->load_class(
5458
-                $className,
5459
-                [$this_model_fields_n_values, $this->_timezone],
5460
-                true,
5461
-                false
5462
-            );
5463
-        }
5464
-        return $classInstance;
5465
-    }
5466
-
5467
-
5468
-    /**
5469
-     * Gets the model object from the  entity map if it exists
5470
-     *
5471
-     * @param int|string $id the ID of the model object
5472
-     * @return EE_Base_Class
5473
-     */
5474
-    public function get_from_entity_map($id)
5475
-    {
5476
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5477
-    }
5478
-
5479
-
5480
-    /**
5481
-     * add_to_entity_map
5482
-     * Adds the object to the model's entity mappings
5483
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5484
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5485
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5486
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5487
-     *        then this method should be called immediately after the update query
5488
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5489
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5490
-     *
5491
-     * @param EE_Base_Class $object
5492
-     * @return EE_Base_Class
5493
-     * @throws EE_Error
5494
-     * @throws ReflectionException
5495
-     */
5496
-    public function add_to_entity_map(EE_Base_Class $object)
5497
-    {
5498
-        $className = $this->_get_class_name();
5499
-        if (! $object instanceof $className) {
5500
-            throw new EE_Error(
5501
-                sprintf(
5502
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5503
-                    is_object($object)
5504
-                        ? get_class($object)
5505
-                        : $object,
5506
-                    $className
5507
-                )
5508
-            );
5509
-        }
5510
-
5511
-        if (! $object->ID()) {
5512
-            throw new EE_Error(
5513
-                sprintf(
5514
-                    esc_html__(
5515
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5516
-                        "event_espresso"
5517
-                    ),
5518
-                    get_class($this)
5519
-                )
5520
-            );
5521
-        }
5522
-        // double check it's not already there
5523
-        $classInstance = $this->get_from_entity_map($object->ID());
5524
-        if ($classInstance) {
5525
-            return $classInstance;
5526
-        }
5527
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5528
-        return $object;
5529
-    }
5530
-
5531
-
5532
-    /**
5533
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5534
-     * if no identifier is provided, then the entire entity map is emptied
5535
-     *
5536
-     * @param int|string $id the ID of the model object
5537
-     * @return boolean
5538
-     */
5539
-    public function clear_entity_map($id = null)
5540
-    {
5541
-        if (empty($id)) {
5542
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5543
-            return true;
5544
-        }
5545
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5546
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5547
-            return true;
5548
-        }
5549
-        return false;
5550
-    }
5551
-
5552
-
5553
-    /**
5554
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5555
-     * Given an array where keys are column (or column alias) names and values,
5556
-     * returns an array of their corresponding field names and database values
5557
-     *
5558
-     * @param array $cols_n_values
5559
-     * @return array
5560
-     * @throws EE_Error
5561
-     * @throws ReflectionException
5562
-     */
5563
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5564
-    {
5565
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5566
-    }
5567
-
5568
-
5569
-    /**
5570
-     * _deduce_fields_n_values_from_cols_n_values
5571
-     * Given an array where keys are column (or column alias) names and values,
5572
-     * returns an array of their corresponding field names and database values
5573
-     *
5574
-     * @param array|stdClass $cols_n_values
5575
-     * @return array
5576
-     * @throws EE_Error
5577
-     * @throws ReflectionException
5578
-     */
5579
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5580
-    {
5581
-        if ($cols_n_values instanceof stdClass) {
5582
-            $cols_n_values = get_object_vars($cols_n_values);
5583
-        }
5584
-        $this_model_fields_n_values = [];
5585
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5586
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5587
-                $cols_n_values,
5588
-                $table_obj->get_fully_qualified_pk_column(),
5589
-                $table_obj->get_pk_column()
5590
-            );
5591
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5592
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5593
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5595
-                        // prepare field as if its coming from db
5596
-                        $prepared_value                            =
5597
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5598
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5599
-                    }
5600
-                }
5601
-            } else {
5602
-                // the table's rows existed. Use their values
5603
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
-                    if (! $field_obj->is_db_only_field()) {
5605
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5606
-                            $cols_n_values,
5607
-                            $field_obj->get_qualified_column(),
5608
-                            $field_obj->get_table_column()
5609
-                        );
5610
-                    }
5611
-                }
5612
-            }
5613
-        }
5614
-        return $this_model_fields_n_values;
5615
-    }
5616
-
5617
-
5618
-    /**
5619
-     * @param $cols_n_values
5620
-     * @param $qualified_column
5621
-     * @param $regular_column
5622
-     * @return null
5623
-     * @throws EE_Error
5624
-     * @throws ReflectionException
5625
-     */
5626
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5627
-    {
5628
-        $value = null;
5629
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5630
-        // does the field on the model relate to this column retrieved from the db?
5631
-        // or is it a db-only field? (not relating to the model)
5632
-        if (isset($cols_n_values[ $qualified_column ])) {
5633
-            $value = $cols_n_values[ $qualified_column ];
5634
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5635
-            $value = $cols_n_values[ $regular_column ];
5636
-        } elseif (! empty($this->foreign_key_aliases)) {
5637
-            // no PK?  ok check if there is a foreign key alias set for this table
5638
-            // then check if that alias exists in the incoming data
5639
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5640
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5641
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5642
-                    $value = $cols_n_values[ $FK_alias ];
5643
-                    [$pk_class] = explode('.', $PK_column);
5644
-                    $pk_model_name = "EEM_{$pk_class}";
5645
-                    /** @var EEM_Base $pk_model */
5646
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5647
-                    if ($pk_model instanceof EEM_Base) {
5648
-                        // make sure object is pulled from db and added to entity map
5649
-                        $pk_model->get_one_by_ID($value);
5650
-                    }
5651
-                    break;
5652
-                }
5653
-            }
5654
-        }
5655
-        return $value;
5656
-    }
5657
-
5658
-
5659
-    /**
5660
-     * refresh_entity_map_from_db
5661
-     * Makes sure the model object in the entity map at $id assumes the values
5662
-     * of the database (opposite of EE_base_Class::save())
5663
-     *
5664
-     * @param int|string $id
5665
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5666
-     * @throws EE_Error
5667
-     * @throws ReflectionException
5668
-     */
5669
-    public function refresh_entity_map_from_db($id)
5670
-    {
5671
-        $obj_in_map = $this->get_from_entity_map($id);
5672
-        if ($obj_in_map) {
5673
-            $wpdb_results = $this->_get_all_wpdb_results(
5674
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5675
-            );
5676
-            if ($wpdb_results && is_array($wpdb_results)) {
5677
-                $one_row = reset($wpdb_results);
5678
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5679
-                    $obj_in_map->set_from_db($field_name, $db_value);
5680
-                }
5681
-                // clear the cache of related model objects
5682
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5683
-                    $obj_in_map->clear_cache($relation_name, null, true);
5684
-                }
5685
-            }
5686
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5687
-            return $obj_in_map;
5688
-        }
5689
-        return $this->get_one_by_ID($id);
5690
-    }
5691
-
5692
-
5693
-    /**
5694
-     * refresh_entity_map_with
5695
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5696
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5697
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5698
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5699
-     *
5700
-     * @param int|string    $id
5701
-     * @param EE_Base_Class $replacing_model_obj
5702
-     * @return EE_Base_Class
5703
-     * @throws EE_Error
5704
-     * @throws ReflectionException
5705
-     */
5706
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5707
-    {
5708
-        $obj_in_map = $this->get_from_entity_map($id);
5709
-        if ($obj_in_map) {
5710
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5711
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5712
-                    $obj_in_map->set($field_name, $value);
5713
-                }
5714
-                // make the model object in the entity map's cache match the $replacing_model_obj
5715
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5716
-                    $obj_in_map->clear_cache($relation_name, null, true);
5717
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5718
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5719
-                    }
5720
-                }
5721
-            }
5722
-            return $obj_in_map;
5723
-        }
5724
-        $this->add_to_entity_map($replacing_model_obj);
5725
-        return $replacing_model_obj;
5726
-    }
5727
-
5728
-
5729
-    /**
5730
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5731
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5732
-     * require_once($this->_getClassName().".class.php");
5733
-     *
5734
-     * @return string
5735
-     */
5736
-    private function _get_class_name()
5737
-    {
5738
-        return "EE_" . $this->get_this_model_name();
5739
-    }
5740
-
5741
-
5742
-    /**
5743
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5744
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5745
-     * it would be 'Events'.
5746
-     *
5747
-     * @param int|float|null $quantity
5748
-     * @return string
5749
-     */
5750
-    public function item_name($quantity = 1): string
5751
-    {
5752
-        $quantity = floor($quantity);
5753
-        return apply_filters(
5754
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5755
-            $quantity > 1
5756
-                ? $this->plural_item
5757
-                : $this->singular_item,
5758
-            $quantity,
5759
-            $this->plural_item,
5760
-            $this->singular_item
5761
-        );
5762
-    }
5763
-
5764
-
5765
-    /**
5766
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5767
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5768
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5769
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5770
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5771
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5772
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5773
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5774
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5775
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5776
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5777
-     *        return $previousReturnValue.$returnString;
5778
-     * }
5779
-     * require('EEM_Answer.model.php');
5780
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5781
-     * // will output "you called my_callback! and passed args:monkeys,100"
5782
-     *
5783
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5784
-     * @param array  $args       array of original arguments passed to the function
5785
-     * @return mixed whatever the plugin which calls add_filter decides
5786
-     * @throws EE_Error
5787
-     */
5788
-    public function __call($methodName, $args)
5789
-    {
5790
-        $className = get_class($this);
5791
-        $tagName   = "FHEE__{$className}__{$methodName}";
5792
-        if (! has_filter($tagName)) {
5793
-            throw new EE_Error(
5794
-                sprintf(
5795
-                    esc_html__(
5796
-                        '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 );',
5797
-                        'event_espresso'
5798
-                    ),
5799
-                    $methodName,
5800
-                    $className,
5801
-                    $tagName,
5802
-                    '<br />'
5803
-                )
5804
-            );
5805
-        }
5806
-        return apply_filters($tagName, null, $this, $args);
5807
-    }
5808
-
5809
-
5810
-    /**
5811
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5812
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5813
-     *
5814
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5815
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5816
-     *                                                       the object's class name
5817
-     *                                                       or object's ID
5818
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5819
-     *                                                       exists in the database. If it does not, we add it
5820
-     * @return EE_Base_Class
5821
-     * @throws EE_Error
5822
-     * @throws ReflectionException
5823
-     */
5824
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5825
-    {
5826
-        $className = $this->_get_class_name();
5827
-        if ($base_class_obj_or_id instanceof $className) {
5828
-            $model_object = $base_class_obj_or_id;
5829
-        } else {
5830
-            $primary_key_field = $this->get_primary_key_field();
5831
-            if (
5832
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5833
-                && (
5834
-                    is_int($base_class_obj_or_id)
5835
-                    || is_string($base_class_obj_or_id)
5836
-                )
5837
-            ) {
5838
-                // assume it's an ID.
5839
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5840
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5841
-            } elseif (
5842
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5843
-                && is_string($base_class_obj_or_id)
5844
-            ) {
5845
-                // assume it's a string representation of the object
5846
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5847
-            } else {
5848
-                throw new EE_Error(
5849
-                    sprintf(
5850
-                        esc_html__(
5851
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5852
-                            'event_espresso'
5853
-                        ),
5854
-                        $base_class_obj_or_id,
5855
-                        $this->_get_class_name(),
5856
-                        print_r($base_class_obj_or_id, true)
5857
-                    )
5858
-                );
5859
-            }
5860
-        }
5861
-        if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5862
-            $model_object->save();
5863
-        }
5864
-        return $model_object;
5865
-    }
5866
-
5867
-
5868
-    /**
5869
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5870
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5871
-     * returns it ID.
5872
-     *
5873
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5874
-     * @return int|string depending on the type of this model object's ID
5875
-     * @throws EE_Error
5876
-     * @throws ReflectionException
5877
-     */
5878
-    public function ensure_is_ID($base_class_obj_or_id)
5879
-    {
5880
-        $className = $this->_get_class_name();
5881
-        if ($base_class_obj_or_id instanceof $className) {
5882
-            /** @var $base_class_obj_or_id EE_Base_Class */
5883
-            $id = $base_class_obj_or_id->ID();
5884
-        } elseif (is_int($base_class_obj_or_id)) {
5885
-            // assume it's an ID
5886
-            $id = $base_class_obj_or_id;
5887
-        } elseif (is_string($base_class_obj_or_id)) {
5888
-            // assume its a string representation of the object
5889
-            $id = $base_class_obj_or_id;
5890
-        } else {
5891
-            throw new EE_Error(
5892
-                sprintf(
5893
-                    esc_html__(
5894
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5895
-                        'event_espresso'
5896
-                    ),
5897
-                    $base_class_obj_or_id,
5898
-                    $this->_get_class_name(),
5899
-                    print_r($base_class_obj_or_id, true)
5900
-                )
5901
-            );
5902
-        }
5903
-        return $id;
5904
-    }
5905
-
5906
-
5907
-    /**
5908
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5909
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5910
-     * been sanitized and converted into the appropriate domain.
5911
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5912
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5913
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5914
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5915
-     * $EVT = EEM_Event::instance(); $old_setting =
5916
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5917
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5918
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5919
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5920
-     *
5921
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5922
-     * @return void
5923
-     */
5924
-    public function assume_values_already_prepared_by_model_object(
5925
-        $values_already_prepared = self::not_prepared_by_model_object
5926
-    ) {
5927
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5928
-    }
5929
-
5930
-
5931
-    /**
5932
-     * Read comments for assume_values_already_prepared_by_model_object()
5933
-     *
5934
-     * @return int
5935
-     */
5936
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5937
-    {
5938
-        return $this->_values_already_prepared_by_model_object;
5939
-    }
5940
-
5941
-
5942
-    /**
5943
-     * Gets all the indexes on this model
5944
-     *
5945
-     * @return EE_Index[]
5946
-     */
5947
-    public function indexes()
5948
-    {
5949
-        return $this->_indexes;
5950
-    }
5951
-
5952
-
5953
-    /**
5954
-     * Gets all the Unique Indexes on this model
5955
-     *
5956
-     * @return EE_Unique_Index[]
5957
-     */
5958
-    public function unique_indexes()
5959
-    {
5960
-        $unique_indexes = [];
5961
-        foreach ($this->_indexes as $name => $index) {
5962
-            if ($index instanceof EE_Unique_Index) {
5963
-                $unique_indexes [ $name ] = $index;
5964
-            }
5965
-        }
5966
-        return $unique_indexes;
5967
-    }
5968
-
5969
-
5970
-    /**
5971
-     * Gets all the fields which, when combined, make the primary key.
5972
-     * This is usually just an array with 1 element (the primary key), but in cases
5973
-     * where there is no primary key, it's a combination of fields as defined
5974
-     * on a primary index
5975
-     *
5976
-     * @return EE_Model_Field_Base[] indexed by the field's name
5977
-     * @throws EE_Error
5978
-     */
5979
-    public function get_combined_primary_key_fields()
5980
-    {
5981
-        foreach ($this->indexes() as $index) {
5982
-            if ($index instanceof EE_Primary_Key_Index) {
5983
-                return $index->fields();
5984
-            }
5985
-        }
5986
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5987
-    }
5988
-
5989
-
5990
-    /**
5991
-     * Used to build a primary key string (when the model has no primary key),
5992
-     * which can be used a unique string to identify this model object.
5993
-     *
5994
-     * @param array $fields_n_values keys are field names, values are their values.
5995
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5996
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5997
-     *                               before passing it to this function (that will convert it from columns-n-values
5998
-     *                               to field-names-n-values).
5999
-     * @return string
6000
-     * @throws EE_Error
6001
-     */
6002
-    public function get_index_primary_key_string($fields_n_values)
6003
-    {
6004
-        $cols_n_values_for_primary_key_index = array_intersect_key(
6005
-            $fields_n_values,
6006
-            $this->get_combined_primary_key_fields()
6007
-        );
6008
-        return http_build_query($cols_n_values_for_primary_key_index);
6009
-    }
6010
-
6011
-
6012
-    /**
6013
-     * Gets the field values from the primary key string
6014
-     *
6015
-     * @param string $index_primary_key_string
6016
-     * @return null|array
6017
-     * @throws EE_Error
6018
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6019
-     */
6020
-    public function parse_index_primary_key_string($index_primary_key_string)
6021
-    {
6022
-        $key_fields = $this->get_combined_primary_key_fields();
6023
-        // check all of them are in the $id
6024
-        $key_vals_in_combined_pk = [];
6025
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6026
-        foreach ($key_fields as $key_field_name => $field_obj) {
6027
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6028
-                return null;
6029
-            }
6030
-        }
6031
-        return $key_vals_in_combined_pk;
6032
-    }
6033
-
6034
-
6035
-    /**
6036
-     * verifies that an array of key-value pairs for model fields has a key
6037
-     * for each field comprising the primary key index
6038
-     *
6039
-     * @param array $key_vals
6040
-     * @return boolean
6041
-     * @throws EE_Error
6042
-     */
6043
-    public function has_all_combined_primary_key_fields($key_vals)
6044
-    {
6045
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6046
-        foreach ($keys_it_should_have as $key) {
6047
-            if (! isset($key_vals[ $key ])) {
6048
-                return false;
6049
-            }
6050
-        }
6051
-        return true;
6052
-    }
6053
-
6054
-
6055
-    /**
6056
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6057
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
6058
-     *
6059
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6060
-     * @param array               $query_params                     @see
6061
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6062
-     * @throws EE_Error
6063
-     * @throws ReflectionException
6064
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6065
-     *                                                              indexed)
6066
-     */
6067
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6068
-    {
6069
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6070
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
6071
-        } elseif (is_array($model_object_or_attributes_array)) {
6072
-            $attributes_array = $model_object_or_attributes_array;
6073
-        } else {
6074
-            throw new EE_Error(
6075
-                sprintf(
6076
-                    esc_html__(
6077
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6078
-                        "event_espresso"
6079
-                    ),
6080
-                    $model_object_or_attributes_array
6081
-                )
6082
-            );
6083
-        }
6084
-        // even copies obviously won't have the same ID, so remove the primary key
6085
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6086
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6087
-            unset($attributes_array[ $this->primary_key_name() ]);
6088
-        }
6089
-        if (isset($query_params[0])) {
6090
-            $query_params[0] = array_merge($attributes_array, $query_params);
6091
-        } else {
6092
-            $query_params[0] = $attributes_array;
6093
-        }
6094
-        return $this->get_all($query_params);
6095
-    }
6096
-
6097
-
6098
-    /**
6099
-     * Gets the first copy we find. See get_all_copies for more details
6100
-     *
6101
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6102
-     * @param array $query_params
6103
-     * @return EE_Base_Class
6104
-     * @throws EE_Error
6105
-     * @throws ReflectionException
6106
-     */
6107
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6108
-    {
6109
-        if (! is_array($query_params)) {
6110
-            EE_Error::doing_it_wrong(
6111
-                'EEM_Base::get_one_copy',
6112
-                sprintf(
6113
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6114
-                    gettype($query_params)
6115
-                ),
6116
-                '4.6.0'
6117
-            );
6118
-            $query_params = [];
6119
-        }
6120
-        $query_params['limit'] = 1;
6121
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6122
-        if (is_array($copies)) {
6123
-            return array_shift($copies);
6124
-        }
6125
-        return null;
6126
-    }
6127
-
6128
-
6129
-    /**
6130
-     * Updates the item with the specified id. Ignores default query parameters because
6131
-     * we have specified the ID, and its assumed we KNOW what we're doing
6132
-     *
6133
-     * @param array      $fields_n_values keys are field names, values are their new values
6134
-     * @param int|string $id              the value of the primary key to update
6135
-     * @return int number of rows updated
6136
-     * @throws EE_Error
6137
-     * @throws ReflectionException
6138
-     */
6139
-    public function update_by_ID($fields_n_values, $id)
6140
-    {
6141
-        $query_params = [
6142
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6143
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6144
-        ];
6145
-        return $this->update($fields_n_values, $query_params);
6146
-    }
6147
-
6148
-
6149
-    /**
6150
-     * Changes an operator which was supplied to the models into one usable in SQL
6151
-     *
6152
-     * @param string $operator_supplied
6153
-     * @return string an operator which can be used in SQL
6154
-     * @throws EE_Error
6155
-     */
6156
-    private function _prepare_operator_for_sql($operator_supplied)
6157
-    {
6158
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6159
-        if ($sql_operator) {
6160
-            return $sql_operator;
6161
-        }
6162
-        throw new EE_Error(
6163
-            sprintf(
6164
-                esc_html__(
6165
-                    "The operator '%s' is not in the list of valid operators: %s",
6166
-                    "event_espresso"
6167
-                ),
6168
-                $operator_supplied,
6169
-                implode(",", array_keys($this->_valid_operators))
6170
-            )
6171
-        );
6172
-    }
6173
-
6174
-
6175
-    /**
6176
-     * Gets the valid operators
6177
-     *
6178
-     * @return array keys are accepted strings, values are the SQL they are converted to
6179
-     */
6180
-    public function valid_operators()
6181
-    {
6182
-        return $this->_valid_operators;
6183
-    }
6184
-
6185
-
6186
-    /**
6187
-     * Gets the between-style operators (take 2 arguments).
6188
-     *
6189
-     * @return array keys are accepted strings, values are the SQL they are converted to
6190
-     */
6191
-    public function valid_between_style_operators()
6192
-    {
6193
-        return array_intersect(
6194
-            $this->valid_operators(),
6195
-            $this->_between_style_operators
6196
-        );
6197
-    }
6198
-
6199
-
6200
-    /**
6201
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6202
-     *
6203
-     * @return array keys are accepted strings, values are the SQL they are converted to
6204
-     */
6205
-    public function valid_like_style_operators()
6206
-    {
6207
-        return array_intersect(
6208
-            $this->valid_operators(),
6209
-            $this->_like_style_operators
6210
-        );
6211
-    }
6212
-
6213
-
6214
-    /**
6215
-     * Gets the "in"-style operators
6216
-     *
6217
-     * @return array keys are accepted strings, values are the SQL they are converted to
6218
-     */
6219
-    public function valid_in_style_operators()
6220
-    {
6221
-        return array_intersect(
6222
-            $this->valid_operators(),
6223
-            $this->_in_style_operators
6224
-        );
6225
-    }
6226
-
6227
-
6228
-    /**
6229
-     * Gets the "null"-style operators (accept no arguments)
6230
-     *
6231
-     * @return array keys are accepted strings, values are the SQL they are converted to
6232
-     */
6233
-    public function valid_null_style_operators()
6234
-    {
6235
-        return array_intersect(
6236
-            $this->valid_operators(),
6237
-            $this->_null_style_operators
6238
-        );
6239
-    }
6240
-
6241
-
6242
-    /**
6243
-     * Gets an array where keys are the primary keys and values are their 'names'
6244
-     * (as determined by the model object's name() function, which is often overridden)
6245
-     *
6246
-     * @param array $query_params like get_all's
6247
-     * @return string[]
6248
-     * @throws EE_Error
6249
-     * @throws ReflectionException
6250
-     */
6251
-    public function get_all_names($query_params = [])
6252
-    {
6253
-        $objs  = $this->get_all($query_params);
6254
-        $names = [];
6255
-        foreach ($objs as $obj) {
6256
-            $names[ $obj->ID() ] = $obj->name();
6257
-        }
6258
-        return $names;
6259
-    }
6260
-
6261
-
6262
-    /**
6263
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6264
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6265
-     * this is duplicated effort and reduces efficiency) you would be better to use
6266
-     * array_keys() on $model_objects.
6267
-     *
6268
-     * @param \EE_Base_Class[] $model_objects
6269
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6270
-     *                                               in the returned array
6271
-     * @return array
6272
-     * @throws EE_Error
6273
-     * @throws ReflectionException
6274
-     */
6275
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6276
-    {
6277
-        if (! $this->has_primary_key_field()) {
6278
-            if (defined('WP_DEBUG') && WP_DEBUG) {
6279
-                EE_Error::add_error(
6280
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6281
-                    __FILE__,
6282
-                    __FUNCTION__,
6283
-                    __LINE__
6284
-                );
6285
-            }
6286
-        }
6287
-        $IDs = [];
6288
-        foreach ($model_objects as $model_object) {
6289
-            $id = $model_object->ID();
6290
-            if (! $id) {
6291
-                if ($filter_out_empty_ids) {
6292
-                    continue;
6293
-                }
6294
-                if (defined('WP_DEBUG') && WP_DEBUG) {
6295
-                    EE_Error::add_error(
6296
-                        esc_html__(
6297
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6298
-                            'event_espresso'
6299
-                        ),
6300
-                        __FILE__,
6301
-                        __FUNCTION__,
6302
-                        __LINE__
6303
-                    );
6304
-                }
6305
-            }
6306
-            $IDs[] = $id;
6307
-        }
6308
-        return $IDs;
6309
-    }
6310
-
6311
-
6312
-    /**
6313
-     * Returns the string used in capabilities relating to this model. If there
6314
-     * are no capabilities that relate to this model returns false
6315
-     *
6316
-     * @return string|false
6317
-     */
6318
-    public function cap_slug()
6319
-    {
6320
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6321
-    }
6322
-
6323
-
6324
-    /**
6325
-     * Returns the capability-restrictions array (@param string $context
6326
-     *
6327
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6328
-     * @throws EE_Error
6329
-     * @see EEM_Base::_cap_restrictions).
6330
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6331
-     *      only returns the cap restrictions array in that context (ie, the array
6332
-     *      at that key)
6333
-     */
6334
-    public function cap_restrictions($context = EEM_Base::caps_read)
6335
-    {
6336
-        EEM_Base::verify_is_valid_cap_context($context);
6337
-        // check if we ought to run the restriction generator first
6338
-        if (
6339
-            isset($this->_cap_restriction_generators[ $context ])
6340
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6341
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6342
-        ) {
6343
-            $this->_cap_restrictions[ $context ] = array_merge(
6344
-                $this->_cap_restrictions[ $context ],
6345
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6346
-            );
6347
-        }
6348
-        // and make sure we've finalized the construction of each restriction
6349
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6350
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6351
-                $where_conditions_obj->_finalize_construct($this);
6352
-            }
6353
-        }
6354
-        return $this->_cap_restrictions[ $context ];
6355
-    }
6356
-
6357
-
6358
-    /**
6359
-     * Indicating whether or not this model thinks its a wp core model
6360
-     *
6361
-     * @return boolean
6362
-     */
6363
-    public function is_wp_core_model()
6364
-    {
6365
-        return $this->_wp_core_model;
6366
-    }
6367
-
6368
-
6369
-    /**
6370
-     * Gets all the caps that are missing which impose a restriction on
6371
-     * queries made in this context
6372
-     *
6373
-     * @param string $context one of EEM_Base::caps_ constants
6374
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6375
-     * @throws EE_Error
6376
-     */
6377
-    public function caps_missing($context = EEM_Base::caps_read)
6378
-    {
6379
-        $missing_caps     = [];
6380
-        $cap_restrictions = $this->cap_restrictions($context);
6381
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6382
-            if (
6383
-                ! EE_Capabilities::instance()
6384
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6385
-            ) {
6386
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6387
-            }
6388
-        }
6389
-        return $missing_caps;
6390
-    }
6391
-
6392
-
6393
-    /**
6394
-     * Gets the mapping from capability contexts to action strings used in capability names
6395
-     *
6396
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6397
-     * one of 'read', 'edit', or 'delete'
6398
-     */
6399
-    public function cap_contexts_to_cap_action_map()
6400
-    {
6401
-        return apply_filters(
6402
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6403
-            $this->_cap_contexts_to_cap_action_map,
6404
-            $this
6405
-        );
6406
-    }
6407
-
6408
-
6409
-    /**
6410
-     * Gets the action string for the specified capability context
6411
-     *
6412
-     * @param string $context
6413
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6414
-     * @throws EE_Error
6415
-     */
6416
-    public function cap_action_for_context($context)
6417
-    {
6418
-        $mapping = $this->cap_contexts_to_cap_action_map();
6419
-        if (isset($mapping[ $context ])) {
6420
-            return $mapping[ $context ];
6421
-        }
6422
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6423
-            return $action;
6424
-        }
6425
-        throw new EE_Error(
6426
-            sprintf(
6427
-                esc_html__(
6428
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6429
-                    'event_espresso'
6430
-                ),
6431
-                $context,
6432
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6433
-            )
6434
-        );
6435
-    }
6436
-
6437
-
6438
-    /**
6439
-     * Returns all the capability contexts which are valid when querying models
6440
-     *
6441
-     * @return array
6442
-     */
6443
-    public static function valid_cap_contexts(): array
6444
-    {
6445
-        return (array) apply_filters(
6446
-            'FHEE__EEM_Base__valid_cap_contexts',
6447
-            [
6448
-                self::caps_read,
6449
-                self::caps_read_admin,
6450
-                self::caps_edit,
6451
-                self::caps_delete,
6452
-            ]
6453
-        );
6454
-    }
6455
-
6456
-
6457
-    /**
6458
-     * Returns all valid options for 'default_where_conditions'
6459
-     *
6460
-     * @return array
6461
-     */
6462
-    public static function valid_default_where_conditions(): array
6463
-    {
6464
-        return [
6465
-            EEM_Base::default_where_conditions_all,
6466
-            EEM_Base::default_where_conditions_this_only,
6467
-            EEM_Base::default_where_conditions_others_only,
6468
-            EEM_Base::default_where_conditions_minimum_all,
6469
-            EEM_Base::default_where_conditions_minimum_others,
6470
-            EEM_Base::default_where_conditions_none,
6471
-        ];
6472
-    }
6473
-
6474
-    // public static function default_where_conditions_full
6475
-
6476
-
6477
-    /**
6478
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6479
-     *
6480
-     * @param string $context
6481
-     * @return bool
6482
-     * @throws EE_Error
6483
-     */
6484
-    public static function verify_is_valid_cap_context($context): bool
6485
-    {
6486
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6487
-        if (in_array($context, $valid_cap_contexts)) {
6488
-            return true;
6489
-        }
6490
-        throw new EE_Error(
6491
-            sprintf(
6492
-                esc_html__(
6493
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6494
-                    'event_espresso'
6495
-                ),
6496
-                $context,
6497
-                'EEM_Base',
6498
-                implode(',', $valid_cap_contexts)
6499
-            )
6500
-        );
6501
-    }
6502
-
6503
-
6504
-    /**
6505
-     * Clears all the models field caches. This is only useful when a sub-class
6506
-     * might have added a field or something and these caches might be invalidated
6507
-     */
6508
-    protected function _invalidate_field_caches()
6509
-    {
6510
-        $this->_cache_foreign_key_to_fields = [];
6511
-        $this->_cached_fields               = null;
6512
-        $this->_cached_fields_non_db_only   = null;
6513
-    }
6514
-
6515
-
6516
-    /**
6517
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6518
-     * (eg "and", "or", "not").
6519
-     *
6520
-     * @return array
6521
-     */
6522
-    public function logic_query_param_keys(): array
6523
-    {
6524
-        return $this->_logic_query_param_keys;
6525
-    }
6526
-
6527
-
6528
-    /**
6529
-     * Determines whether or not the where query param array key is for a logic query param.
6530
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6531
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6532
-     *
6533
-     * @param $query_param_key
6534
-     * @return bool
6535
-     */
6536
-    public function is_logic_query_param_key($query_param_key): bool
6537
-    {
6538
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6539
-            if (
6540
-                $query_param_key === $logic_query_param_key
6541
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6542
-            ) {
6543
-                return true;
6544
-            }
6545
-        }
6546
-        return false;
6547
-    }
6548
-
6549
-
6550
-    /**
6551
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6552
-     *
6553
-     * @return boolean
6554
-     * @since 4.9.74.p
6555
-     */
6556
-    public function hasPassword(): bool
6557
-    {
6558
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6559
-        if ($this->has_password_field === null) {
6560
-            $password_field           = $this->getPasswordField();
6561
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6562
-        }
6563
-        return $this->has_password_field;
6564
-    }
6565
-
6566
-
6567
-    /**
6568
-     * Returns the password field on this model, if there is one
6569
-     *
6570
-     * @return EE_Password_Field|null
6571
-     * @since 4.9.74.p
6572
-     */
6573
-    public function getPasswordField()
6574
-    {
6575
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6576
-        // there's no need to search for it. If we don't know yet, then find out
6577
-        if ($this->has_password_field === null && $this->password_field === null) {
6578
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6579
-        }
6580
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6581
-        return $this->password_field;
6582
-    }
6583
-
6584
-
6585
-    /**
6586
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6587
-     *
6588
-     * @return EE_Model_Field_Base[]
6589
-     * @throws EE_Error
6590
-     * @since 4.9.74.p
6591
-     */
6592
-    public function getPasswordProtectedFields()
6593
-    {
6594
-        $password_field = $this->getPasswordField();
6595
-        $fields         = [];
6596
-        if ($password_field instanceof EE_Password_Field) {
6597
-            $field_names = $password_field->protectedFields();
6598
-            foreach ($field_names as $field_name) {
6599
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6600
-            }
6601
-        }
6602
-        return $fields;
6603
-    }
6604
-
6605
-
6606
-    /**
6607
-     * Checks if the current user can perform the requested action on this model
6608
-     *
6609
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6610
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6611
-     * @return bool
6612
-     * @throws EE_Error
6613
-     * @throws InvalidArgumentException
6614
-     * @throws InvalidDataTypeException
6615
-     * @throws InvalidInterfaceException
6616
-     * @throws ReflectionException
6617
-     * @throws UnexpectedEntityException
6618
-     * @since 4.9.74.p
6619
-     */
6620
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6621
-    {
6622
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6623
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6624
-        }
6625
-        if (! is_array($model_obj_or_fields_n_values)) {
6626
-            throw new UnexpectedEntityException(
6627
-                $model_obj_or_fields_n_values,
6628
-                'EE_Base_Class',
6629
-                sprintf(
6630
-                    esc_html__(
6631
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6632
-                        'event_espresso'
6633
-                    ),
6634
-                    __FUNCTION__
6635
-                )
6636
-            );
6637
-        }
6638
-        return $this->exists(
6639
-            $this->alter_query_params_to_restrict_by_ID(
6640
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6641
-                [
6642
-                    'default_where_conditions' => 'none',
6643
-                    'caps'                     => $cap_to_check,
6644
-                ]
6645
-            )
6646
-        );
6647
-    }
6648
-
6649
-
6650
-    /**
6651
-     * Returns the query param where conditions key to the password affecting this model.
6652
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6653
-     *
6654
-     * @return null|string
6655
-     * @throws EE_Error
6656
-     * @throws InvalidArgumentException
6657
-     * @throws InvalidDataTypeException
6658
-     * @throws InvalidInterfaceException
6659
-     * @throws ModelConfigurationException
6660
-     * @throws ReflectionException
6661
-     * @since 4.9.74.p
6662
-     */
6663
-    public function modelChainAndPassword()
6664
-    {
6665
-        if ($this->model_chain_to_password === null) {
6666
-            throw new ModelConfigurationException(
6667
-                $this,
6668
-                esc_html_x(
6669
-                // @codingStandardsIgnoreStart
6670
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6671
-                    // @codingStandardsIgnoreEnd
6672
-                    '1: model name',
6673
-                    'event_espresso'
6674
-                )
6675
-            );
6676
-        }
6677
-        if ($this->model_chain_to_password === '') {
6678
-            $model_with_password = $this;
6679
-        } else {
6680
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6681
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6682
-            } else {
6683
-                $last_model_in_chain = $this->model_chain_to_password;
6684
-            }
6685
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6686
-        }
6687
-
6688
-        $password_field = $model_with_password->getPasswordField();
6689
-        if ($password_field instanceof EE_Password_Field) {
6690
-            $password_field_name = $password_field->get_name();
6691
-        } else {
6692
-            throw new ModelConfigurationException(
6693
-                $this,
6694
-                sprintf(
6695
-                    esc_html_x(
6696
-                        '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"',
6697
-                        '1: model name, 2: special string',
6698
-                        'event_espresso'
6699
-                    ),
6700
-                    $model_with_password->get_this_model_name(),
6701
-                    $this->model_chain_to_password
6702
-                )
6703
-            );
6704
-        }
6705
-        return (
6706
-               $this->model_chain_to_password
6707
-                   ? $this->model_chain_to_password . '.'
6708
-                   : ''
6709
-               ) . $password_field_name;
6710
-    }
6711
-
6712
-
6713
-    /**
6714
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6715
-     * or if this model itself has a password affecting access to some of its other fields.
6716
-     *
6717
-     * @return boolean
6718
-     * @since 4.9.74.p
6719
-     */
6720
-    public function restrictedByRelatedModelPassword(): bool
6721
-    {
6722
-        return $this->model_chain_to_password !== null;
6723
-    }
3961
+		}
3962
+		return $null_friendly_where_conditions;
3963
+	}
3964
+
3965
+
3966
+	/**
3967
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3968
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3969
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3970
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3971
+	 *
3972
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3973
+	 * @return array @see
3974
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3975
+	 * @throws EE_Error
3976
+	 * @throws EE_Error
3977
+	 */
3978
+	private function _get_default_where_conditions($model_relation_path = '')
3979
+	{
3980
+		if ($this->_ignore_where_strategy) {
3981
+			return [];
3982
+		}
3983
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3984
+	}
3985
+
3986
+
3987
+	/**
3988
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3989
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3990
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3991
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3992
+	 * Similar to _get_default_where_conditions
3993
+	 *
3994
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3995
+	 * @return array @see
3996
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3997
+	 * @throws EE_Error
3998
+	 * @throws EE_Error
3999
+	 */
4000
+	protected function _get_minimum_where_conditions($model_relation_path = '')
4001
+	{
4002
+		if ($this->_ignore_where_strategy) {
4003
+			return [];
4004
+		}
4005
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
4006
+	}
4007
+
4008
+
4009
+	/**
4010
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4011
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4012
+	 *
4013
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
4014
+	 * @return string
4015
+	 * @throws EE_Error
4016
+	 */
4017
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4018
+	{
4019
+		$selects = $this->_get_columns_to_select_for_this_model();
4020
+		foreach (
4021
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4022
+		) {
4023
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4024
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4025
+			foreach ($other_model_selects as $key => $value) {
4026
+				$selects[] = $value;
4027
+			}
4028
+		}
4029
+		return implode(", ", $selects);
4030
+	}
4031
+
4032
+
4033
+	/**
4034
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4035
+	 * So that's going to be the columns for all the fields on the model
4036
+	 *
4037
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
4038
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4039
+	 */
4040
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4041
+	{
4042
+		$fields                                       = $this->field_settings();
4043
+		$selects                                      = [];
4044
+		$table_alias_with_model_relation_chain_prefix =
4045
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4046
+				$model_relation_chain,
4047
+				$this->get_this_model_name()
4048
+			);
4049
+		foreach ($fields as $field_obj) {
4050
+			$selects[] = $table_alias_with_model_relation_chain_prefix
4051
+						 . $field_obj->get_table_alias()
4052
+						 . "."
4053
+						 . $field_obj->get_table_column()
4054
+						 . " AS '"
4055
+						 . $table_alias_with_model_relation_chain_prefix
4056
+						 . $field_obj->get_table_alias()
4057
+						 . "."
4058
+						 . $field_obj->get_table_column()
4059
+						 . "'";
4060
+		}
4061
+		// make sure we are also getting the PKs of each table
4062
+		$tables = $this->get_tables();
4063
+		if (count($tables) > 1) {
4064
+			foreach ($tables as $table_obj) {
4065
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4066
+									   . $table_obj->get_fully_qualified_pk_column();
4067
+				if (! in_array($qualified_pk_column, $selects)) {
4068
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4069
+				}
4070
+			}
4071
+		}
4072
+		return $selects;
4073
+	}
4074
+
4075
+
4076
+	/**
4077
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4078
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4079
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4080
+	 * SQL for joining, and the data types
4081
+	 *
4082
+	 * @param null|string                 $original_query_param
4083
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4084
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4085
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4086
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4087
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4088
+	 *                                                          or 'Registration's
4089
+	 * @param string                      $original_query_param what it originally was (eg
4090
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4091
+	 *                                                          matches $query_param
4092
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4093
+	 * @throws EE_Error
4094
+	 */
4095
+	private function _extract_related_model_info_from_query_param(
4096
+		$query_param,
4097
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4098
+		$query_param_type,
4099
+		$original_query_param = null
4100
+	) {
4101
+		if ($original_query_param === null) {
4102
+			$original_query_param = $query_param;
4103
+		}
4104
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4105
+		// check to see if we have a field on this model
4106
+		$this_model_fields = $this->field_settings(true);
4107
+		if (array_key_exists($query_param, $this_model_fields)) {
4108
+			$field_is_allowed = in_array(
4109
+				$query_param_type,
4110
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4111
+				true
4112
+			);
4113
+			if ($field_is_allowed) {
4114
+				return;
4115
+			}
4116
+			throw new EE_Error(
4117
+				sprintf(
4118
+					esc_html__(
4119
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4120
+						"event_espresso"
4121
+					),
4122
+					$query_param,
4123
+					get_class($this),
4124
+					$query_param_type,
4125
+					$original_query_param
4126
+				)
4127
+			);
4128
+		}
4129
+		// check if this is a special logic query param
4130
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4131
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4132
+			if ($operator_is_allowed) {
4133
+				return;
4134
+			}
4135
+			throw new EE_Error(
4136
+				sprintf(
4137
+					esc_html__(
4138
+						'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',
4139
+						'event_espresso'
4140
+					),
4141
+					implode('", "', $this->_logic_query_param_keys),
4142
+					$query_param,
4143
+					get_class($this),
4144
+					'<br />',
4145
+					"\t"
4146
+					. ' $passed_in_query_info = <pre>'
4147
+					. print_r($passed_in_query_info, true)
4148
+					. '</pre>'
4149
+					. "\n\t"
4150
+					. ' $query_param_type = '
4151
+					. $query_param_type
4152
+					. "\n\t"
4153
+					. ' $original_query_param = '
4154
+					. $original_query_param
4155
+				)
4156
+			);
4157
+		}
4158
+		// check if it's a custom selection
4159
+		if (
4160
+			$this->_custom_selections instanceof CustomSelects
4161
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4162
+		) {
4163
+			return;
4164
+		}
4165
+		// check if has a model name at the beginning
4166
+		// and
4167
+		// check if it's a field on a related model
4168
+		if (
4169
+			$this->extractJoinModelFromQueryParams(
4170
+				$passed_in_query_info,
4171
+				$query_param,
4172
+				$original_query_param,
4173
+				$query_param_type
4174
+			)
4175
+		) {
4176
+			return;
4177
+		}
4178
+
4179
+		// ok so $query_param didn't start with a model name
4180
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4181
+		// it's wack, that's what it is
4182
+		throw new EE_Error(
4183
+			sprintf(
4184
+				esc_html__(
4185
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4186
+					"event_espresso"
4187
+				),
4188
+				$query_param,
4189
+				get_class($this),
4190
+				$query_param_type,
4191
+				$original_query_param
4192
+			)
4193
+		);
4194
+	}
4195
+
4196
+
4197
+	/**
4198
+	 * Extracts any possible join model information from the provided possible_join_string.
4199
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4200
+	 * join
4201
+	 * parts that should be added to the query.
4202
+	 *
4203
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4204
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4205
+	 * @param null|string                 $original_query_param
4206
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4207
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4208
+	 *                                                           etc.)
4209
+	 * @return bool  returns true if a join was added and false if not.
4210
+	 * @throws EE_Error
4211
+	 */
4212
+	private function extractJoinModelFromQueryParams(
4213
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4214
+		$possible_join_string,
4215
+		$original_query_param,
4216
+		$query_parameter_type
4217
+	) {
4218
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4219
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4220
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4221
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4222
+				if ($possible_join_string === '') {
4223
+					// nothing left to $query_param
4224
+					// we should actually end in a field name, not a model like this!
4225
+					throw new EE_Error(
4226
+						sprintf(
4227
+							esc_html__(
4228
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4229
+								"event_espresso"
4230
+							),
4231
+							$possible_join_string,
4232
+							$query_parameter_type,
4233
+							get_class($this),
4234
+							$valid_related_model_name
4235
+						)
4236
+					);
4237
+				}
4238
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4239
+				$related_model_obj->_extract_related_model_info_from_query_param(
4240
+					$possible_join_string,
4241
+					$query_info_carrier,
4242
+					$query_parameter_type,
4243
+					$original_query_param
4244
+				);
4245
+				return true;
4246
+			}
4247
+			if ($possible_join_string === $valid_related_model_name) {
4248
+				$this->_add_join_to_model(
4249
+					$valid_related_model_name,
4250
+					$query_info_carrier,
4251
+					$original_query_param
4252
+				);
4253
+				return true;
4254
+			}
4255
+		}
4256
+		return false;
4257
+	}
4258
+
4259
+
4260
+	/**
4261
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4262
+	 *
4263
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4264
+	 * @throws EE_Error
4265
+	 */
4266
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4267
+	{
4268
+		if (
4269
+			$this->_custom_selections instanceof CustomSelects
4270
+			&& (
4271
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4272
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4273
+			)
4274
+		) {
4275
+			$original_selects = $this->_custom_selections->originalSelects();
4276
+			foreach ($original_selects as $alias => $select_configuration) {
4277
+				$this->extractJoinModelFromQueryParams(
4278
+					$query_info_carrier,
4279
+					$select_configuration[0],
4280
+					$select_configuration[0],
4281
+					'custom_selects'
4282
+				);
4283
+			}
4284
+		}
4285
+	}
4286
+
4287
+
4288
+	/**
4289
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4290
+	 * and store it on $passed_in_query_info
4291
+	 *
4292
+	 * @param string                      $model_name
4293
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4294
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4295
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4296
+	 *                                                          and are adding a join to 'Payment' with the original
4297
+	 *                                                          query param key
4298
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4299
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4300
+	 *                                                          Payment wants to add default query params so that it
4301
+	 *                                                          will know what models to prepend onto its default query
4302
+	 *                                                          params or in case it wants to rename tables (in case
4303
+	 *                                                          there are multiple joins to the same table)
4304
+	 * @return void
4305
+	 * @throws EE_Error
4306
+	 */
4307
+	private function _add_join_to_model(
4308
+		$model_name,
4309
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4310
+		$original_query_param
4311
+	) {
4312
+		$relation_obj         = $this->related_settings_for($model_name);
4313
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4314
+		// check if the relation is HABTM, because then we're essentially doing two joins
4315
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4316
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4317
+			$join_model_obj = $relation_obj->get_join_model();
4318
+			// replace the model specified with the join model for this relation chain, whi
4319
+			$relation_chain_to_join_model =
4320
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4321
+					$model_name,
4322
+					$join_model_obj->get_this_model_name(),
4323
+					$model_relation_chain
4324
+				);
4325
+			$passed_in_query_info->merge(
4326
+				new EE_Model_Query_Info_Carrier(
4327
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4328
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4329
+				)
4330
+			);
4331
+		}
4332
+		// now just join to the other table pointed to by the relation object, and add its data types
4333
+		$passed_in_query_info->merge(
4334
+			new EE_Model_Query_Info_Carrier(
4335
+				[$model_relation_chain => $model_name],
4336
+				$relation_obj->get_join_statement($model_relation_chain)
4337
+			)
4338
+		);
4339
+	}
4340
+
4341
+
4342
+	/**
4343
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4344
+	 *
4345
+	 * @param array $where_params @see
4346
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4347
+	 * @return string of SQL
4348
+	 * @throws EE_Error
4349
+	 */
4350
+	private function _construct_where_clause($where_params)
4351
+	{
4352
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4353
+		if ($SQL) {
4354
+			return " WHERE " . $SQL;
4355
+		}
4356
+		return '';
4357
+	}
4358
+
4359
+
4360
+	/**
4361
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4362
+	 * and should be passed HAVING parameters, not WHERE parameters
4363
+	 *
4364
+	 * @param array $having_params
4365
+	 * @return string
4366
+	 * @throws EE_Error
4367
+	 */
4368
+	private function _construct_having_clause($having_params)
4369
+	{
4370
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4371
+		if ($SQL) {
4372
+			return " HAVING " . $SQL;
4373
+		}
4374
+		return '';
4375
+	}
4376
+
4377
+
4378
+	/**
4379
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4380
+	 * Event_Meta.meta_value = 'foo'))"
4381
+	 *
4382
+	 * @param array  $where_params @see
4383
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4384
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4385
+	 * @return string of SQL
4386
+	 * @throws EE_Error
4387
+	 */
4388
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4389
+	{
4390
+		$where_clauses = [];
4391
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4392
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4393
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4394
+				switch ($query_param) {
4395
+					case 'not':
4396
+					case 'NOT':
4397
+						$where_clauses[] = "! ("
4398
+										   . $this->_construct_condition_clause_recursive(
4399
+											   $op_and_value_or_sub_condition,
4400
+											   $glue
4401
+										   )
4402
+										   . ")";
4403
+						break;
4404
+					case 'and':
4405
+					case 'AND':
4406
+						$where_clauses[] = " ("
4407
+										   . $this->_construct_condition_clause_recursive(
4408
+											   $op_and_value_or_sub_condition,
4409
+											   ' AND '
4410
+										   )
4411
+										   . ")";
4412
+						break;
4413
+					case 'or':
4414
+					case 'OR':
4415
+						$where_clauses[] = " ("
4416
+										   . $this->_construct_condition_clause_recursive(
4417
+											   $op_and_value_or_sub_condition,
4418
+											   ' OR '
4419
+										   )
4420
+										   . ")";
4421
+						break;
4422
+				}
4423
+			} else {
4424
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4425
+				// if it's not a normal field, maybe it's a custom selection?
4426
+				if (! $field_obj) {
4427
+					if ($this->_custom_selections instanceof CustomSelects) {
4428
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4429
+					} else {
4430
+						throw new EE_Error(
4431
+							sprintf(
4432
+								esc_html__(
4433
+									"%s is neither a valid model field name, nor a custom selection",
4434
+									"event_espresso"
4435
+								),
4436
+								$query_param
4437
+							)
4438
+						);
4439
+					}
4440
+				}
4441
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4442
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4443
+			}
4444
+		}
4445
+		return $where_clauses
4446
+			? implode($glue, $where_clauses)
4447
+			: '';
4448
+	}
4449
+
4450
+
4451
+	/**
4452
+	 * Takes the input parameter and extract the table name (alias) and column name
4453
+	 *
4454
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4455
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4456
+	 * @throws EE_Error
4457
+	 */
4458
+	private function _deduce_column_name_from_query_param($query_param)
4459
+	{
4460
+		$field = $this->_deduce_field_from_query_param($query_param);
4461
+		if ($field) {
4462
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4463
+				$field->get_model_name(),
4464
+				$query_param
4465
+			);
4466
+			return $table_alias_prefix . $field->get_qualified_column();
4467
+		}
4468
+		if (
4469
+			$this->_custom_selections instanceof CustomSelects
4470
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4471
+		) {
4472
+			// maybe it's custom selection item?
4473
+			// if so, just use it as the "column name"
4474
+			return $query_param;
4475
+		}
4476
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4477
+			? implode(',', $this->_custom_selections->columnAliases())
4478
+			: '';
4479
+		throw new EE_Error(
4480
+			sprintf(
4481
+				esc_html__(
4482
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4483
+					"event_espresso"
4484
+				),
4485
+				$query_param,
4486
+				$custom_select_aliases
4487
+			)
4488
+		);
4489
+	}
4490
+
4491
+
4492
+	/**
4493
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4494
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4495
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4496
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4497
+	 *
4498
+	 * @param string $condition_query_param_key
4499
+	 * @return string
4500
+	 */
4501
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4502
+	{
4503
+		$pos_of_star = strpos($condition_query_param_key, '*');
4504
+		if ($pos_of_star === false) {
4505
+			return $condition_query_param_key;
4506
+		}
4507
+		return substr($condition_query_param_key, 0, $pos_of_star);
4508
+	}
4509
+
4510
+
4511
+	/**
4512
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4513
+	 *
4514
+	 * @param array|string               $op_and_value
4515
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4516
+	 * @return string
4517
+	 * @throws EE_Error
4518
+	 */
4519
+	private function _construct_op_and_value($op_and_value, $field_obj)
4520
+	{
4521
+		$operator = '=';
4522
+		$value    = $op_and_value;
4523
+		if (is_array($op_and_value)) {
4524
+			$operator = isset($op_and_value[0])
4525
+				? $this->_prepare_operator_for_sql($op_and_value[0])
4526
+				: null;
4527
+			if (! $operator) {
4528
+				$php_array_like_string = [];
4529
+				foreach ($op_and_value as $key => $value) {
4530
+					$php_array_like_string[] = "$key=>$value";
4531
+				}
4532
+				throw new EE_Error(
4533
+					sprintf(
4534
+						esc_html__(
4535
+							"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))",
4536
+							"event_espresso"
4537
+						),
4538
+						implode(",", $php_array_like_string)
4539
+					)
4540
+				);
4541
+			}
4542
+			$value = $op_and_value[1] ?? null;
4543
+		}
4544
+
4545
+		// check to see if the value is actually another field
4546
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4547
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4548
+		}
4549
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4550
+			// in this case, the value should be an array, or at least a comma-separated list
4551
+			// it will need to handle a little differently
4552
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4553
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4554
+			return $operator . SP . $cleaned_value;
4555
+		}
4556
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4557
+			// the value should be an array with count of two.
4558
+			if (count($value) !== 2) {
4559
+				throw new EE_Error(
4560
+					sprintf(
4561
+						esc_html__(
4562
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4563
+							'event_espresso'
4564
+						),
4565
+						"BETWEEN"
4566
+					)
4567
+				);
4568
+			}
4569
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4570
+			return $operator . SP . $cleaned_value;
4571
+		}
4572
+		if (in_array($operator, $this->valid_null_style_operators())) {
4573
+			if ($value !== null) {
4574
+				throw new EE_Error(
4575
+					sprintf(
4576
+						esc_html__(
4577
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4578
+							"event_espresso"
4579
+						),
4580
+						$value,
4581
+						$operator
4582
+					)
4583
+				);
4584
+			}
4585
+			return $operator;
4586
+		}
4587
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4588
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4589
+			// remove other junk. So just treat it as a string.
4590
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4591
+		}
4592
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4593
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4594
+		}
4595
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4596
+			throw new EE_Error(
4597
+				sprintf(
4598
+					esc_html__(
4599
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4600
+						'event_espresso'
4601
+					),
4602
+					$operator,
4603
+					$operator
4604
+				)
4605
+			);
4606
+		}
4607
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4608
+			throw new EE_Error(
4609
+				sprintf(
4610
+					esc_html__(
4611
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4612
+						'event_espresso'
4613
+					),
4614
+					$operator,
4615
+					$operator
4616
+				)
4617
+			);
4618
+		}
4619
+		throw new EE_Error(
4620
+			sprintf(
4621
+				esc_html__(
4622
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4623
+					"event_espresso"
4624
+				),
4625
+				http_build_query($op_and_value)
4626
+			)
4627
+		);
4628
+	}
4629
+
4630
+
4631
+	/**
4632
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4633
+	 *
4634
+	 * @param array                      $values
4635
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4636
+	 *                                              '%s'
4637
+	 * @return string
4638
+	 * @throws EE_Error
4639
+	 */
4640
+	public function _construct_between_value($values, $field_obj)
4641
+	{
4642
+		$cleaned_values = [];
4643
+		foreach ($values as $value) {
4644
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4645
+		}
4646
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4647
+	}
4648
+
4649
+
4650
+	/**
4651
+	 * Takes an array or a comma-separated list of $values and cleans them
4652
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4653
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4654
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4655
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4656
+	 *
4657
+	 * @param mixed                      $values    array or comma-separated string
4658
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4659
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4660
+	 * @throws EE_Error
4661
+	 */
4662
+	public function _construct_in_value($values, $field_obj)
4663
+	{
4664
+		$prepped = [];
4665
+		// check if the value is a CSV list
4666
+		if (is_string($values)) {
4667
+			// in which case, turn it into an array
4668
+			$values = explode(',', $values);
4669
+		}
4670
+		// make sure we only have one of each value in the list
4671
+		$values = array_unique($values);
4672
+		foreach ($values as $value) {
4673
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4674
+		}
4675
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4676
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4677
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4678
+		if (empty($prepped)) {
4679
+			$all_fields  = $this->field_settings();
4680
+			$first_field = reset($all_fields);
4681
+			$main_table  = $this->_get_main_table();
4682
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4683
+		}
4684
+		return '(' . implode(',', $prepped) . ')';
4685
+	}
4686
+
4687
+
4688
+	/**
4689
+	 * @param mixed                      $value
4690
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4691
+	 * @return false|null|string
4692
+	 * @throws EE_Error
4693
+	 */
4694
+	private function _wpdb_prepare_using_field($value, $field_obj)
4695
+	{
4696
+		/** @type WPDB $wpdb */
4697
+		global $wpdb;
4698
+		if ($field_obj instanceof EE_Model_Field_Base) {
4699
+			return $wpdb->prepare(
4700
+				$field_obj->get_wpdb_data_type(),
4701
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4702
+			);
4703
+		} //$field_obj should really just be a data type
4704
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4705
+			throw new EE_Error(
4706
+				sprintf(
4707
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4708
+					$field_obj,
4709
+					implode(",", $this->_valid_wpdb_data_types)
4710
+				)
4711
+			);
4712
+		}
4713
+		return $wpdb->prepare($field_obj, $value);
4714
+	}
4715
+
4716
+
4717
+	/**
4718
+	 * Takes the input parameter and finds the model field that it indicates.
4719
+	 *
4720
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4721
+	 * @return EE_Model_Field_Base
4722
+	 * @throws EE_Error
4723
+	 */
4724
+	protected function _deduce_field_from_query_param($query_param_name)
4725
+	{
4726
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4727
+		// which will help us find the database table and column
4728
+		$query_param_parts = explode(".", $query_param_name);
4729
+		if (empty($query_param_parts)) {
4730
+			throw new EE_Error(
4731
+				sprintf(
4732
+					esc_html__(
4733
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4734
+						'event_espresso'
4735
+					),
4736
+					$query_param_name
4737
+				)
4738
+			);
4739
+		}
4740
+		$number_of_parts       = count($query_param_parts);
4741
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4742
+		if ($number_of_parts === 1) {
4743
+			$field_name = $last_query_param_part;
4744
+			$model_obj  = $this;
4745
+		} else {// $number_of_parts >= 2
4746
+			// the last part is the column name, and there are only 2parts. therefore...
4747
+			$field_name = $last_query_param_part;
4748
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4749
+		}
4750
+		try {
4751
+			return $model_obj->field_settings_for($field_name);
4752
+		} catch (EE_Error $e) {
4753
+			return null;
4754
+		}
4755
+	}
4756
+
4757
+
4758
+	/**
4759
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4760
+	 * alias and column which corresponds to it
4761
+	 *
4762
+	 * @param string $field_name
4763
+	 * @return string
4764
+	 * @throws EE_Error
4765
+	 */
4766
+	public function _get_qualified_column_for_field($field_name)
4767
+	{
4768
+		$all_fields = $this->field_settings();
4769
+		$field      = $all_fields[ $field_name ] ?? false;
4770
+		if ($field) {
4771
+			return $field->get_qualified_column();
4772
+		}
4773
+		throw new EE_Error(
4774
+			sprintf(
4775
+				esc_html__(
4776
+					"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.",
4777
+					'event_espresso'
4778
+				),
4779
+				$field_name,
4780
+				get_class($this)
4781
+			)
4782
+		);
4783
+	}
4784
+
4785
+
4786
+	/**
4787
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4788
+	 * Example usage:
4789
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4790
+	 *      array(),
4791
+	 *      ARRAY_A,
4792
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4793
+	 *  );
4794
+	 * is equivalent to
4795
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4796
+	 * and
4797
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4798
+	 *      array(
4799
+	 *          array(
4800
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4801
+	 *          ),
4802
+	 *          ARRAY_A,
4803
+	 *          implode(
4804
+	 *              ', ',
4805
+	 *              array_merge(
4806
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4807
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4808
+	 *              )
4809
+	 *          )
4810
+	 *      )
4811
+	 *  );
4812
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4813
+	 *
4814
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4815
+	 *                                            and the one whose fields you are selecting for example: when querying
4816
+	 *                                            tickets model and selecting fields from the tickets model you would
4817
+	 *                                            leave this parameter empty, because no models are needed to join
4818
+	 *                                            between the queried model and the selected one. Likewise when
4819
+	 *                                            querying the datetime model and selecting fields from the tickets
4820
+	 *                                            model, it would also be left empty, because there is a direct
4821
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4822
+	 *                                            them together. However, when querying from the event model and
4823
+	 *                                            selecting fields from the ticket model, you should provide the string
4824
+	 *                                            'Datetime', indicating that the event model must first join to the
4825
+	 *                                            datetime model in order to find its relation to ticket model.
4826
+	 *                                            Also, when querying from the venue model and selecting fields from
4827
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4828
+	 *                                            indicating you need to join the venue model to the event model,
4829
+	 *                                            to the datetime model, in order to find its relation to the ticket
4830
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4831
+	 *                                            the models' tables qualified columns
4832
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4833
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4834
+	 *                                            qualified column names
4835
+	 * @return array|string
4836
+	 */
4837
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4838
+	{
4839
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4840
+				? ''
4841
+				: '__');
4842
+		$qualified_columns = [];
4843
+		foreach ($this->field_settings() as $field_name => $field) {
4844
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4845
+		}
4846
+		return $return_string
4847
+			? implode(', ', $qualified_columns)
4848
+			: $qualified_columns;
4849
+	}
4850
+
4851
+
4852
+	/**
4853
+	 * constructs the select use on special limit joins
4854
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4855
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4856
+	 * (as that is typically where the limits would be set).
4857
+	 *
4858
+	 * @param string       $table_alias The table the select is being built for
4859
+	 * @param mixed|string $limit       The limit for this select
4860
+	 * @return string                The final select join element for the query.
4861
+	 * @throws EE_Error
4862
+	 * @throws EE_Error
4863
+	 */
4864
+	public function _construct_limit_join_select($table_alias, $limit)
4865
+	{
4866
+		$SQL = '';
4867
+		foreach ($this->_tables as $table_obj) {
4868
+			if ($table_obj instanceof EE_Primary_Table) {
4869
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4870
+					? $table_obj->get_select_join_limit($limit)
4871
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4872
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4873
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4874
+					? $table_obj->get_select_join_limit_join($limit)
4875
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4876
+			}
4877
+		}
4878
+		return $SQL;
4879
+	}
4880
+
4881
+
4882
+	/**
4883
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4884
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4885
+	 *
4886
+	 * @return string SQL
4887
+	 * @throws EE_Error
4888
+	 */
4889
+	public function _construct_internal_join()
4890
+	{
4891
+		$SQL = $this->_get_main_table()->get_table_sql();
4892
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4893
+		return $SQL;
4894
+	}
4895
+
4896
+
4897
+	/**
4898
+	 * Constructs the SQL for joining all the tables on this model.
4899
+	 * Normally $alias should be the primary table's alias, but in cases where
4900
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4901
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4902
+	 * alias, this will construct SQL like:
4903
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4904
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4905
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4906
+	 *
4907
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4908
+	 * @return string
4909
+	 * @throws EE_Error
4910
+	 * @throws EE_Error
4911
+	 */
4912
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4913
+	{
4914
+		$SQL               = '';
4915
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4916
+		foreach ($this->_tables as $table_obj) {
4917
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4918
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4919
+					// so we're joining to this table, meaning the table is already in
4920
+					// the FROM statement, BUT the primary table isn't. So we want
4921
+					// to add the inverse join sql
4922
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4923
+				} else {
4924
+					// just add a regular JOIN to this table from the primary table
4925
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4926
+				}
4927
+			}// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4928
+		}
4929
+		return $SQL;
4930
+	}
4931
+
4932
+
4933
+	/**
4934
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4935
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4936
+	 * their data type (eg, '%s', '%d', etc)
4937
+	 *
4938
+	 * @return array
4939
+	 */
4940
+	public function _get_data_types()
4941
+	{
4942
+		$data_types = [];
4943
+		foreach ($this->field_settings() as $field_obj) {
4944
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4945
+			/** @var $field_obj EE_Model_Field_Base */
4946
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4947
+		}
4948
+		return $data_types;
4949
+	}
4950
+
4951
+
4952
+	/**
4953
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4954
+	 *
4955
+	 * @param string $model_name
4956
+	 * @return EEM_Base
4957
+	 * @throws EE_Error
4958
+	 */
4959
+	public function get_related_model_obj($model_name)
4960
+	{
4961
+		$model_classname = "EEM_" . $model_name;
4962
+		if (! class_exists($model_classname)) {
4963
+			throw new EE_Error(
4964
+				sprintf(
4965
+					esc_html__(
4966
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4967
+						'event_espresso'
4968
+					),
4969
+					$model_name,
4970
+					$model_classname
4971
+				)
4972
+			);
4973
+		}
4974
+		return call_user_func($model_classname . "::instance");
4975
+	}
4976
+
4977
+
4978
+	/**
4979
+	 * Returns the array of EE_ModelRelations for this model.
4980
+	 *
4981
+	 * @return EE_Model_Relation_Base[]
4982
+	 */
4983
+	public function relation_settings()
4984
+	{
4985
+		return $this->_model_relations;
4986
+	}
4987
+
4988
+
4989
+	/**
4990
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4991
+	 * because without THOSE models, this model probably doesn't have much purpose.
4992
+	 * (Eg, without an event, datetimes have little purpose.)
4993
+	 *
4994
+	 * @return EE_Belongs_To_Relation[]
4995
+	 */
4996
+	public function belongs_to_relations()
4997
+	{
4998
+		$belongs_to_relations = [];
4999
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
5000
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
5001
+				$belongs_to_relations[ $model_name ] = $relation_obj;
5002
+			}
5003
+		}
5004
+		return $belongs_to_relations;
5005
+	}
5006
+
5007
+
5008
+	/**
5009
+	 * Returns the specified EE_Model_Relation, or throws an exception
5010
+	 *
5011
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
5012
+	 * @return EE_Model_Relation_Base
5013
+	 * @throws EE_Error
5014
+	 */
5015
+	public function related_settings_for($relation_name)
5016
+	{
5017
+		$relatedModels = $this->relation_settings();
5018
+		if (! array_key_exists($relation_name, $relatedModels)) {
5019
+			throw new EE_Error(
5020
+				sprintf(
5021
+					esc_html__(
5022
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5023
+						'event_espresso'
5024
+					),
5025
+					$relation_name,
5026
+					$this->_get_class_name(),
5027
+					implode(', ', array_keys($relatedModels))
5028
+				)
5029
+			);
5030
+		}
5031
+		return $relatedModels[ $relation_name ];
5032
+	}
5033
+
5034
+
5035
+	/**
5036
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5037
+	 * fields
5038
+	 *
5039
+	 * @param string  $fieldName
5040
+	 * @param boolean $include_db_only_fields
5041
+	 * @return EE_Model_Field_Base
5042
+	 * @throws EE_Error
5043
+	 */
5044
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
5045
+	{
5046
+		$fieldSettings = $this->field_settings($include_db_only_fields);
5047
+		if (! array_key_exists($fieldName, $fieldSettings)) {
5048
+			throw new EE_Error(
5049
+				sprintf(
5050
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5051
+					$fieldName,
5052
+					get_class($this)
5053
+				)
5054
+			);
5055
+		}
5056
+		return $fieldSettings[ $fieldName ];
5057
+	}
5058
+
5059
+
5060
+	/**
5061
+	 * Checks if this field exists on this model
5062
+	 *
5063
+	 * @param string $fieldName a key in the model's _field_settings array
5064
+	 * @return boolean
5065
+	 */
5066
+	public function has_field($fieldName)
5067
+	{
5068
+		$fieldSettings = $this->field_settings(true);
5069
+		if (isset($fieldSettings[ $fieldName ])) {
5070
+			return true;
5071
+		}
5072
+		return false;
5073
+	}
5074
+
5075
+
5076
+	/**
5077
+	 * Returns whether or not this model has a relation to the specified model
5078
+	 *
5079
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5080
+	 * @return boolean
5081
+	 */
5082
+	public function has_relation($relation_name)
5083
+	{
5084
+		$relations = $this->relation_settings();
5085
+		if (isset($relations[ $relation_name ])) {
5086
+			return true;
5087
+		}
5088
+		return false;
5089
+	}
5090
+
5091
+
5092
+	/**
5093
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5094
+	 * Eg, on EE_Answer that would be ANS_ID field object
5095
+	 *
5096
+	 * @param $field_obj
5097
+	 * @return boolean
5098
+	 */
5099
+	public function is_primary_key_field($field_obj): bool
5100
+	{
5101
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5102
+	}
5103
+
5104
+
5105
+	/**
5106
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5107
+	 * Eg, on EE_Answer that would be ANS_ID field object
5108
+	 *
5109
+	 * @return EE_Primary_Key_Field_Base
5110
+	 * @throws EE_Error
5111
+	 */
5112
+	public function get_primary_key_field()
5113
+	{
5114
+		if ($this->_primary_key_field === null) {
5115
+			foreach ($this->field_settings(true) as $field_obj) {
5116
+				if ($this->is_primary_key_field($field_obj)) {
5117
+					$this->_primary_key_field = $field_obj;
5118
+					break;
5119
+				}
5120
+			}
5121
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5122
+				throw new EE_Error(
5123
+					sprintf(
5124
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5125
+						get_class($this)
5126
+					)
5127
+				);
5128
+			}
5129
+		}
5130
+		return $this->_primary_key_field;
5131
+	}
5132
+
5133
+
5134
+	/**
5135
+	 * Returns whether or not not there is a primary key on this model.
5136
+	 * Internally does some caching.
5137
+	 *
5138
+	 * @return boolean
5139
+	 */
5140
+	public function has_primary_key_field()
5141
+	{
5142
+		if ($this->_has_primary_key_field === null) {
5143
+			try {
5144
+				$this->get_primary_key_field();
5145
+				$this->_has_primary_key_field = true;
5146
+			} catch (EE_Error $e) {
5147
+				$this->_has_primary_key_field = false;
5148
+			}
5149
+		}
5150
+		return $this->_has_primary_key_field;
5151
+	}
5152
+
5153
+
5154
+	/**
5155
+	 * Finds the first field of type $field_class_name.
5156
+	 *
5157
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5158
+	 *                                 EE_Foreign_Key_Field, etc
5159
+	 * @return EE_Model_Field_Base or null if none is found
5160
+	 */
5161
+	public function get_a_field_of_type($field_class_name)
5162
+	{
5163
+		foreach ($this->field_settings() as $field) {
5164
+			if ($field instanceof $field_class_name) {
5165
+				return $field;
5166
+			}
5167
+		}
5168
+		return null;
5169
+	}
5170
+
5171
+
5172
+	/**
5173
+	 * Gets a foreign key field pointing to model.
5174
+	 *
5175
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5176
+	 * @return EE_Foreign_Key_Field_Base
5177
+	 * @throws EE_Error
5178
+	 */
5179
+	public function get_foreign_key_to($model_name)
5180
+	{
5181
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
+			foreach ($this->field_settings() as $field) {
5183
+				if (
5184
+					$field instanceof EE_Foreign_Key_Field_Base
5185
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5186
+				) {
5187
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5188
+					break;
5189
+				}
5190
+			}
5191
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5192
+				throw new EE_Error(
5193
+					sprintf(
5194
+						esc_html__(
5195
+							"There is no foreign key field pointing to model %s on model %s",
5196
+							'event_espresso'
5197
+						),
5198
+						$model_name,
5199
+						get_class($this)
5200
+					)
5201
+				);
5202
+			}
5203
+		}
5204
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5205
+	}
5206
+
5207
+
5208
+	/**
5209
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5210
+	 *
5211
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5212
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5213
+	 *                            Either one works
5214
+	 * @return string
5215
+	 */
5216
+	public function get_table_for_alias($table_alias)
5217
+	{
5218
+		$table_alias_sans_model_relation_chain_prefix =
5219
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5220
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5221
+	}
5222
+
5223
+
5224
+	/**
5225
+	 * Returns a flat array of all field son this model, instead of organizing them
5226
+	 * by table_alias as they are in the constructor.
5227
+	 *
5228
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5229
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5230
+	 */
5231
+	public function field_settings($include_db_only_fields = false)
5232
+	{
5233
+		if ($include_db_only_fields) {
5234
+			if ($this->_cached_fields === null) {
5235
+				$this->_cached_fields = [];
5236
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5237
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
+						$this->_cached_fields[ $field_name ] = $field_obj;
5239
+					}
5240
+				}
5241
+			}
5242
+			return $this->_cached_fields;
5243
+		}
5244
+		if ($this->_cached_fields_non_db_only === null) {
5245
+			$this->_cached_fields_non_db_only = [];
5246
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5247
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
+					/** @var $field_obj EE_Model_Field_Base */
5249
+					if (! $field_obj->is_db_only_field()) {
5250
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5251
+					}
5252
+				}
5253
+			}
5254
+		}
5255
+		return $this->_cached_fields_non_db_only;
5256
+	}
5257
+
5258
+
5259
+	/**
5260
+	 *        cycle though array of attendees and create objects out of each item
5261
+	 *
5262
+	 * @access        private
5263
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5264
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5265
+	 *                           numerically indexed)
5266
+	 * @throws EE_Error
5267
+	 * @throws ReflectionException
5268
+	 */
5269
+	protected function _create_objects($rows = [])
5270
+	{
5271
+		$array_of_objects = [];
5272
+		if (empty($rows)) {
5273
+			return [];
5274
+		}
5275
+		$count_if_model_has_no_primary_key = 0;
5276
+		$has_primary_key                   = $this->has_primary_key_field();
5277
+		$primary_key_field                 = $has_primary_key
5278
+			? $this->get_primary_key_field()
5279
+			: null;
5280
+		foreach ((array) $rows as $row) {
5281
+			if (empty($row)) {
5282
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5283
+				return [];
5284
+			}
5285
+			// check if we've already set this object in the results array,
5286
+			// in which case there's no need to process it further (again)
5287
+			if ($has_primary_key) {
5288
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5289
+					$row,
5290
+					$primary_key_field->get_qualified_column(),
5291
+					$primary_key_field->get_table_column()
5292
+				);
5293
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5294
+					continue;
5295
+				}
5296
+			}
5297
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5298
+			if (! $classInstance) {
5299
+				throw new EE_Error(
5300
+					sprintf(
5301
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5302
+						$this->get_this_model_name(),
5303
+						http_build_query($row)
5304
+					)
5305
+				);
5306
+			}
5307
+			// set the timezone on the instantiated objects
5308
+			$classInstance->set_timezone($this->_timezone);
5309
+			// make sure if there is any timezone setting present that we set the timezone for the object
5310
+			$key                      = $has_primary_key
5311
+				? $classInstance->ID()
5312
+				: $count_if_model_has_no_primary_key++;
5313
+			$array_of_objects[ $key ] = $classInstance;
5314
+			// also, for all the relations of type BelongsTo, see if we can cache
5315
+			// those related models
5316
+			// (we could do this for other relations too, but if there are conditions
5317
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5318
+			// so it requires a little more thought than just caching them immediately...)
5319
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5320
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5321
+					// check if this model's INFO is present. If so, cache it on the model
5322
+					$other_model           = $relation_obj->get_other_model();
5323
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5324
+					// if we managed to make a model object from the results, cache it on the main model object
5325
+					if ($other_model_obj_maybe) {
5326
+						// set timezone on these other model objects if they are present
5327
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5328
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5329
+					}
5330
+				}
5331
+			}
5332
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5333
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5334
+			// the field in the CustomSelects object
5335
+			if ($this->_custom_selections instanceof CustomSelects) {
5336
+				$classInstance->setCustomSelectsValues(
5337
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5338
+				);
5339
+			}
5340
+		}
5341
+		return $array_of_objects;
5342
+	}
5343
+
5344
+
5345
+	/**
5346
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5347
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5348
+	 *
5349
+	 * @param array $db_results_row
5350
+	 * @return array
5351
+	 */
5352
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5353
+	{
5354
+		$results = [];
5355
+		if ($this->_custom_selections instanceof CustomSelects) {
5356
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5357
+				if (isset($db_results_row[ $alias ])) {
5358
+					$results[ $alias ] = $this->convertValueToDataType(
5359
+						$db_results_row[ $alias ],
5360
+						$this->_custom_selections->getDataTypeForAlias($alias)
5361
+					);
5362
+				}
5363
+			}
5364
+		}
5365
+		return $results;
5366
+	}
5367
+
5368
+
5369
+	/**
5370
+	 * This will set the value for the given alias
5371
+	 *
5372
+	 * @param string $value
5373
+	 * @param string $datatype (one of %d, %s, %f)
5374
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5375
+	 */
5376
+	protected function convertValueToDataType($value, $datatype)
5377
+	{
5378
+		switch ($datatype) {
5379
+			case '%f':
5380
+				return (float) $value;
5381
+			case '%d':
5382
+				return (int) $value;
5383
+			default:
5384
+				return (string) $value;
5385
+		}
5386
+	}
5387
+
5388
+
5389
+	/**
5390
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5391
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5392
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5393
+	 * object (as set in the model_field!).
5394
+	 *
5395
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5396
+	 * @throws EE_Error
5397
+	 * @throws ReflectionException
5398
+	 */
5399
+	public function create_default_object()
5400
+	{
5401
+		$this_model_fields_and_values = [];
5402
+		// setup the row using default values;
5403
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5404
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5405
+		}
5406
+		$className = $this->_get_class_name();
5407
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5408
+	}
5409
+
5410
+
5411
+	/**
5412
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5413
+	 *                             or an stdClass where each property is the name of a column,
5414
+	 * @return EE_Base_Class
5415
+	 * @throws EE_Error
5416
+	 * @throws ReflectionException
5417
+	 */
5418
+	public function instantiate_class_from_array_or_object($cols_n_values)
5419
+	{
5420
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5421
+			$cols_n_values = get_object_vars($cols_n_values);
5422
+		}
5423
+		$primary_key = null;
5424
+		// make sure the array only has keys that are fields/columns on this model
5425
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5426
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5427
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5428
+		}
5429
+		$className = $this->_get_class_name();
5430
+		// check we actually found results that we can use to build our model object
5431
+		// if not, return null
5432
+		if ($this->has_primary_key_field()) {
5433
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5434
+				return null;
5435
+			}
5436
+		} elseif ($this->unique_indexes()) {
5437
+			$first_column = reset($this_model_fields_n_values);
5438
+			if (empty($first_column)) {
5439
+				return null;
5440
+			}
5441
+		}
5442
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5443
+		if ($primary_key) {
5444
+			$classInstance = $this->get_from_entity_map($primary_key);
5445
+			if (! $classInstance) {
5446
+				$classInstance = EE_Registry::instance()
5447
+											->load_class(
5448
+												$className,
5449
+												[$this_model_fields_n_values, $this->_timezone],
5450
+												true,
5451
+												false
5452
+											);
5453
+				// add this new object to the entity map
5454
+				$classInstance = $this->add_to_entity_map($classInstance);
5455
+			}
5456
+		} else {
5457
+			$classInstance = EE_Registry::instance()->load_class(
5458
+				$className,
5459
+				[$this_model_fields_n_values, $this->_timezone],
5460
+				true,
5461
+				false
5462
+			);
5463
+		}
5464
+		return $classInstance;
5465
+	}
5466
+
5467
+
5468
+	/**
5469
+	 * Gets the model object from the  entity map if it exists
5470
+	 *
5471
+	 * @param int|string $id the ID of the model object
5472
+	 * @return EE_Base_Class
5473
+	 */
5474
+	public function get_from_entity_map($id)
5475
+	{
5476
+		return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5477
+	}
5478
+
5479
+
5480
+	/**
5481
+	 * add_to_entity_map
5482
+	 * Adds the object to the model's entity mappings
5483
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5484
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5485
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5486
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5487
+	 *        then this method should be called immediately after the update query
5488
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5489
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5490
+	 *
5491
+	 * @param EE_Base_Class $object
5492
+	 * @return EE_Base_Class
5493
+	 * @throws EE_Error
5494
+	 * @throws ReflectionException
5495
+	 */
5496
+	public function add_to_entity_map(EE_Base_Class $object)
5497
+	{
5498
+		$className = $this->_get_class_name();
5499
+		if (! $object instanceof $className) {
5500
+			throw new EE_Error(
5501
+				sprintf(
5502
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5503
+					is_object($object)
5504
+						? get_class($object)
5505
+						: $object,
5506
+					$className
5507
+				)
5508
+			);
5509
+		}
5510
+
5511
+		if (! $object->ID()) {
5512
+			throw new EE_Error(
5513
+				sprintf(
5514
+					esc_html__(
5515
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5516
+						"event_espresso"
5517
+					),
5518
+					get_class($this)
5519
+				)
5520
+			);
5521
+		}
5522
+		// double check it's not already there
5523
+		$classInstance = $this->get_from_entity_map($object->ID());
5524
+		if ($classInstance) {
5525
+			return $classInstance;
5526
+		}
5527
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5528
+		return $object;
5529
+	}
5530
+
5531
+
5532
+	/**
5533
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5534
+	 * if no identifier is provided, then the entire entity map is emptied
5535
+	 *
5536
+	 * @param int|string $id the ID of the model object
5537
+	 * @return boolean
5538
+	 */
5539
+	public function clear_entity_map($id = null)
5540
+	{
5541
+		if (empty($id)) {
5542
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5543
+			return true;
5544
+		}
5545
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5546
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5547
+			return true;
5548
+		}
5549
+		return false;
5550
+	}
5551
+
5552
+
5553
+	/**
5554
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5555
+	 * Given an array where keys are column (or column alias) names and values,
5556
+	 * returns an array of their corresponding field names and database values
5557
+	 *
5558
+	 * @param array $cols_n_values
5559
+	 * @return array
5560
+	 * @throws EE_Error
5561
+	 * @throws ReflectionException
5562
+	 */
5563
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5564
+	{
5565
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5566
+	}
5567
+
5568
+
5569
+	/**
5570
+	 * _deduce_fields_n_values_from_cols_n_values
5571
+	 * Given an array where keys are column (or column alias) names and values,
5572
+	 * returns an array of their corresponding field names and database values
5573
+	 *
5574
+	 * @param array|stdClass $cols_n_values
5575
+	 * @return array
5576
+	 * @throws EE_Error
5577
+	 * @throws ReflectionException
5578
+	 */
5579
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5580
+	{
5581
+		if ($cols_n_values instanceof stdClass) {
5582
+			$cols_n_values = get_object_vars($cols_n_values);
5583
+		}
5584
+		$this_model_fields_n_values = [];
5585
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5586
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5587
+				$cols_n_values,
5588
+				$table_obj->get_fully_qualified_pk_column(),
5589
+				$table_obj->get_pk_column()
5590
+			);
5591
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5592
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5593
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
+					if (! $field_obj->is_db_only_field()) {
5595
+						// prepare field as if its coming from db
5596
+						$prepared_value                            =
5597
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5598
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5599
+					}
5600
+				}
5601
+			} else {
5602
+				// the table's rows existed. Use their values
5603
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
+					if (! $field_obj->is_db_only_field()) {
5605
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5606
+							$cols_n_values,
5607
+							$field_obj->get_qualified_column(),
5608
+							$field_obj->get_table_column()
5609
+						);
5610
+					}
5611
+				}
5612
+			}
5613
+		}
5614
+		return $this_model_fields_n_values;
5615
+	}
5616
+
5617
+
5618
+	/**
5619
+	 * @param $cols_n_values
5620
+	 * @param $qualified_column
5621
+	 * @param $regular_column
5622
+	 * @return null
5623
+	 * @throws EE_Error
5624
+	 * @throws ReflectionException
5625
+	 */
5626
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5627
+	{
5628
+		$value = null;
5629
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5630
+		// does the field on the model relate to this column retrieved from the db?
5631
+		// or is it a db-only field? (not relating to the model)
5632
+		if (isset($cols_n_values[ $qualified_column ])) {
5633
+			$value = $cols_n_values[ $qualified_column ];
5634
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5635
+			$value = $cols_n_values[ $regular_column ];
5636
+		} elseif (! empty($this->foreign_key_aliases)) {
5637
+			// no PK?  ok check if there is a foreign key alias set for this table
5638
+			// then check if that alias exists in the incoming data
5639
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5640
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5641
+				if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5642
+					$value = $cols_n_values[ $FK_alias ];
5643
+					[$pk_class] = explode('.', $PK_column);
5644
+					$pk_model_name = "EEM_{$pk_class}";
5645
+					/** @var EEM_Base $pk_model */
5646
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5647
+					if ($pk_model instanceof EEM_Base) {
5648
+						// make sure object is pulled from db and added to entity map
5649
+						$pk_model->get_one_by_ID($value);
5650
+					}
5651
+					break;
5652
+				}
5653
+			}
5654
+		}
5655
+		return $value;
5656
+	}
5657
+
5658
+
5659
+	/**
5660
+	 * refresh_entity_map_from_db
5661
+	 * Makes sure the model object in the entity map at $id assumes the values
5662
+	 * of the database (opposite of EE_base_Class::save())
5663
+	 *
5664
+	 * @param int|string $id
5665
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5666
+	 * @throws EE_Error
5667
+	 * @throws ReflectionException
5668
+	 */
5669
+	public function refresh_entity_map_from_db($id)
5670
+	{
5671
+		$obj_in_map = $this->get_from_entity_map($id);
5672
+		if ($obj_in_map) {
5673
+			$wpdb_results = $this->_get_all_wpdb_results(
5674
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5675
+			);
5676
+			if ($wpdb_results && is_array($wpdb_results)) {
5677
+				$one_row = reset($wpdb_results);
5678
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5679
+					$obj_in_map->set_from_db($field_name, $db_value);
5680
+				}
5681
+				// clear the cache of related model objects
5682
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5683
+					$obj_in_map->clear_cache($relation_name, null, true);
5684
+				}
5685
+			}
5686
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5687
+			return $obj_in_map;
5688
+		}
5689
+		return $this->get_one_by_ID($id);
5690
+	}
5691
+
5692
+
5693
+	/**
5694
+	 * refresh_entity_map_with
5695
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5696
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5697
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5698
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5699
+	 *
5700
+	 * @param int|string    $id
5701
+	 * @param EE_Base_Class $replacing_model_obj
5702
+	 * @return EE_Base_Class
5703
+	 * @throws EE_Error
5704
+	 * @throws ReflectionException
5705
+	 */
5706
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5707
+	{
5708
+		$obj_in_map = $this->get_from_entity_map($id);
5709
+		if ($obj_in_map) {
5710
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5711
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5712
+					$obj_in_map->set($field_name, $value);
5713
+				}
5714
+				// make the model object in the entity map's cache match the $replacing_model_obj
5715
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5716
+					$obj_in_map->clear_cache($relation_name, null, true);
5717
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5718
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5719
+					}
5720
+				}
5721
+			}
5722
+			return $obj_in_map;
5723
+		}
5724
+		$this->add_to_entity_map($replacing_model_obj);
5725
+		return $replacing_model_obj;
5726
+	}
5727
+
5728
+
5729
+	/**
5730
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5731
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5732
+	 * require_once($this->_getClassName().".class.php");
5733
+	 *
5734
+	 * @return string
5735
+	 */
5736
+	private function _get_class_name()
5737
+	{
5738
+		return "EE_" . $this->get_this_model_name();
5739
+	}
5740
+
5741
+
5742
+	/**
5743
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5744
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5745
+	 * it would be 'Events'.
5746
+	 *
5747
+	 * @param int|float|null $quantity
5748
+	 * @return string
5749
+	 */
5750
+	public function item_name($quantity = 1): string
5751
+	{
5752
+		$quantity = floor($quantity);
5753
+		return apply_filters(
5754
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5755
+			$quantity > 1
5756
+				? $this->plural_item
5757
+				: $this->singular_item,
5758
+			$quantity,
5759
+			$this->plural_item,
5760
+			$this->singular_item
5761
+		);
5762
+	}
5763
+
5764
+
5765
+	/**
5766
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5767
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5768
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5769
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5770
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5771
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5772
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5773
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5774
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5775
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5776
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5777
+	 *        return $previousReturnValue.$returnString;
5778
+	 * }
5779
+	 * require('EEM_Answer.model.php');
5780
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5781
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5782
+	 *
5783
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5784
+	 * @param array  $args       array of original arguments passed to the function
5785
+	 * @return mixed whatever the plugin which calls add_filter decides
5786
+	 * @throws EE_Error
5787
+	 */
5788
+	public function __call($methodName, $args)
5789
+	{
5790
+		$className = get_class($this);
5791
+		$tagName   = "FHEE__{$className}__{$methodName}";
5792
+		if (! has_filter($tagName)) {
5793
+			throw new EE_Error(
5794
+				sprintf(
5795
+					esc_html__(
5796
+						'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 );',
5797
+						'event_espresso'
5798
+					),
5799
+					$methodName,
5800
+					$className,
5801
+					$tagName,
5802
+					'<br />'
5803
+				)
5804
+			);
5805
+		}
5806
+		return apply_filters($tagName, null, $this, $args);
5807
+	}
5808
+
5809
+
5810
+	/**
5811
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5812
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5813
+	 *
5814
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5815
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5816
+	 *                                                       the object's class name
5817
+	 *                                                       or object's ID
5818
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5819
+	 *                                                       exists in the database. If it does not, we add it
5820
+	 * @return EE_Base_Class
5821
+	 * @throws EE_Error
5822
+	 * @throws ReflectionException
5823
+	 */
5824
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5825
+	{
5826
+		$className = $this->_get_class_name();
5827
+		if ($base_class_obj_or_id instanceof $className) {
5828
+			$model_object = $base_class_obj_or_id;
5829
+		} else {
5830
+			$primary_key_field = $this->get_primary_key_field();
5831
+			if (
5832
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5833
+				&& (
5834
+					is_int($base_class_obj_or_id)
5835
+					|| is_string($base_class_obj_or_id)
5836
+				)
5837
+			) {
5838
+				// assume it's an ID.
5839
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5840
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5841
+			} elseif (
5842
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5843
+				&& is_string($base_class_obj_or_id)
5844
+			) {
5845
+				// assume it's a string representation of the object
5846
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5847
+			} else {
5848
+				throw new EE_Error(
5849
+					sprintf(
5850
+						esc_html__(
5851
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5852
+							'event_espresso'
5853
+						),
5854
+						$base_class_obj_or_id,
5855
+						$this->_get_class_name(),
5856
+						print_r($base_class_obj_or_id, true)
5857
+					)
5858
+				);
5859
+			}
5860
+		}
5861
+		if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5862
+			$model_object->save();
5863
+		}
5864
+		return $model_object;
5865
+	}
5866
+
5867
+
5868
+	/**
5869
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5870
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5871
+	 * returns it ID.
5872
+	 *
5873
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5874
+	 * @return int|string depending on the type of this model object's ID
5875
+	 * @throws EE_Error
5876
+	 * @throws ReflectionException
5877
+	 */
5878
+	public function ensure_is_ID($base_class_obj_or_id)
5879
+	{
5880
+		$className = $this->_get_class_name();
5881
+		if ($base_class_obj_or_id instanceof $className) {
5882
+			/** @var $base_class_obj_or_id EE_Base_Class */
5883
+			$id = $base_class_obj_or_id->ID();
5884
+		} elseif (is_int($base_class_obj_or_id)) {
5885
+			// assume it's an ID
5886
+			$id = $base_class_obj_or_id;
5887
+		} elseif (is_string($base_class_obj_or_id)) {
5888
+			// assume its a string representation of the object
5889
+			$id = $base_class_obj_or_id;
5890
+		} else {
5891
+			throw new EE_Error(
5892
+				sprintf(
5893
+					esc_html__(
5894
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5895
+						'event_espresso'
5896
+					),
5897
+					$base_class_obj_or_id,
5898
+					$this->_get_class_name(),
5899
+					print_r($base_class_obj_or_id, true)
5900
+				)
5901
+			);
5902
+		}
5903
+		return $id;
5904
+	}
5905
+
5906
+
5907
+	/**
5908
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5909
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5910
+	 * been sanitized and converted into the appropriate domain.
5911
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5912
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5913
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5914
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5915
+	 * $EVT = EEM_Event::instance(); $old_setting =
5916
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5917
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5918
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5919
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5920
+	 *
5921
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5922
+	 * @return void
5923
+	 */
5924
+	public function assume_values_already_prepared_by_model_object(
5925
+		$values_already_prepared = self::not_prepared_by_model_object
5926
+	) {
5927
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5928
+	}
5929
+
5930
+
5931
+	/**
5932
+	 * Read comments for assume_values_already_prepared_by_model_object()
5933
+	 *
5934
+	 * @return int
5935
+	 */
5936
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5937
+	{
5938
+		return $this->_values_already_prepared_by_model_object;
5939
+	}
5940
+
5941
+
5942
+	/**
5943
+	 * Gets all the indexes on this model
5944
+	 *
5945
+	 * @return EE_Index[]
5946
+	 */
5947
+	public function indexes()
5948
+	{
5949
+		return $this->_indexes;
5950
+	}
5951
+
5952
+
5953
+	/**
5954
+	 * Gets all the Unique Indexes on this model
5955
+	 *
5956
+	 * @return EE_Unique_Index[]
5957
+	 */
5958
+	public function unique_indexes()
5959
+	{
5960
+		$unique_indexes = [];
5961
+		foreach ($this->_indexes as $name => $index) {
5962
+			if ($index instanceof EE_Unique_Index) {
5963
+				$unique_indexes [ $name ] = $index;
5964
+			}
5965
+		}
5966
+		return $unique_indexes;
5967
+	}
5968
+
5969
+
5970
+	/**
5971
+	 * Gets all the fields which, when combined, make the primary key.
5972
+	 * This is usually just an array with 1 element (the primary key), but in cases
5973
+	 * where there is no primary key, it's a combination of fields as defined
5974
+	 * on a primary index
5975
+	 *
5976
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5977
+	 * @throws EE_Error
5978
+	 */
5979
+	public function get_combined_primary_key_fields()
5980
+	{
5981
+		foreach ($this->indexes() as $index) {
5982
+			if ($index instanceof EE_Primary_Key_Index) {
5983
+				return $index->fields();
5984
+			}
5985
+		}
5986
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5987
+	}
5988
+
5989
+
5990
+	/**
5991
+	 * Used to build a primary key string (when the model has no primary key),
5992
+	 * which can be used a unique string to identify this model object.
5993
+	 *
5994
+	 * @param array $fields_n_values keys are field names, values are their values.
5995
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5996
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5997
+	 *                               before passing it to this function (that will convert it from columns-n-values
5998
+	 *                               to field-names-n-values).
5999
+	 * @return string
6000
+	 * @throws EE_Error
6001
+	 */
6002
+	public function get_index_primary_key_string($fields_n_values)
6003
+	{
6004
+		$cols_n_values_for_primary_key_index = array_intersect_key(
6005
+			$fields_n_values,
6006
+			$this->get_combined_primary_key_fields()
6007
+		);
6008
+		return http_build_query($cols_n_values_for_primary_key_index);
6009
+	}
6010
+
6011
+
6012
+	/**
6013
+	 * Gets the field values from the primary key string
6014
+	 *
6015
+	 * @param string $index_primary_key_string
6016
+	 * @return null|array
6017
+	 * @throws EE_Error
6018
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6019
+	 */
6020
+	public function parse_index_primary_key_string($index_primary_key_string)
6021
+	{
6022
+		$key_fields = $this->get_combined_primary_key_fields();
6023
+		// check all of them are in the $id
6024
+		$key_vals_in_combined_pk = [];
6025
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6026
+		foreach ($key_fields as $key_field_name => $field_obj) {
6027
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6028
+				return null;
6029
+			}
6030
+		}
6031
+		return $key_vals_in_combined_pk;
6032
+	}
6033
+
6034
+
6035
+	/**
6036
+	 * verifies that an array of key-value pairs for model fields has a key
6037
+	 * for each field comprising the primary key index
6038
+	 *
6039
+	 * @param array $key_vals
6040
+	 * @return boolean
6041
+	 * @throws EE_Error
6042
+	 */
6043
+	public function has_all_combined_primary_key_fields($key_vals)
6044
+	{
6045
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6046
+		foreach ($keys_it_should_have as $key) {
6047
+			if (! isset($key_vals[ $key ])) {
6048
+				return false;
6049
+			}
6050
+		}
6051
+		return true;
6052
+	}
6053
+
6054
+
6055
+	/**
6056
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6057
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
6058
+	 *
6059
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6060
+	 * @param array               $query_params                     @see
6061
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6062
+	 * @throws EE_Error
6063
+	 * @throws ReflectionException
6064
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6065
+	 *                                                              indexed)
6066
+	 */
6067
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6068
+	{
6069
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6070
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
6071
+		} elseif (is_array($model_object_or_attributes_array)) {
6072
+			$attributes_array = $model_object_or_attributes_array;
6073
+		} else {
6074
+			throw new EE_Error(
6075
+				sprintf(
6076
+					esc_html__(
6077
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6078
+						"event_espresso"
6079
+					),
6080
+					$model_object_or_attributes_array
6081
+				)
6082
+			);
6083
+		}
6084
+		// even copies obviously won't have the same ID, so remove the primary key
6085
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6086
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6087
+			unset($attributes_array[ $this->primary_key_name() ]);
6088
+		}
6089
+		if (isset($query_params[0])) {
6090
+			$query_params[0] = array_merge($attributes_array, $query_params);
6091
+		} else {
6092
+			$query_params[0] = $attributes_array;
6093
+		}
6094
+		return $this->get_all($query_params);
6095
+	}
6096
+
6097
+
6098
+	/**
6099
+	 * Gets the first copy we find. See get_all_copies for more details
6100
+	 *
6101
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6102
+	 * @param array $query_params
6103
+	 * @return EE_Base_Class
6104
+	 * @throws EE_Error
6105
+	 * @throws ReflectionException
6106
+	 */
6107
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6108
+	{
6109
+		if (! is_array($query_params)) {
6110
+			EE_Error::doing_it_wrong(
6111
+				'EEM_Base::get_one_copy',
6112
+				sprintf(
6113
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6114
+					gettype($query_params)
6115
+				),
6116
+				'4.6.0'
6117
+			);
6118
+			$query_params = [];
6119
+		}
6120
+		$query_params['limit'] = 1;
6121
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6122
+		if (is_array($copies)) {
6123
+			return array_shift($copies);
6124
+		}
6125
+		return null;
6126
+	}
6127
+
6128
+
6129
+	/**
6130
+	 * Updates the item with the specified id. Ignores default query parameters because
6131
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6132
+	 *
6133
+	 * @param array      $fields_n_values keys are field names, values are their new values
6134
+	 * @param int|string $id              the value of the primary key to update
6135
+	 * @return int number of rows updated
6136
+	 * @throws EE_Error
6137
+	 * @throws ReflectionException
6138
+	 */
6139
+	public function update_by_ID($fields_n_values, $id)
6140
+	{
6141
+		$query_params = [
6142
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6143
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6144
+		];
6145
+		return $this->update($fields_n_values, $query_params);
6146
+	}
6147
+
6148
+
6149
+	/**
6150
+	 * Changes an operator which was supplied to the models into one usable in SQL
6151
+	 *
6152
+	 * @param string $operator_supplied
6153
+	 * @return string an operator which can be used in SQL
6154
+	 * @throws EE_Error
6155
+	 */
6156
+	private function _prepare_operator_for_sql($operator_supplied)
6157
+	{
6158
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6159
+		if ($sql_operator) {
6160
+			return $sql_operator;
6161
+		}
6162
+		throw new EE_Error(
6163
+			sprintf(
6164
+				esc_html__(
6165
+					"The operator '%s' is not in the list of valid operators: %s",
6166
+					"event_espresso"
6167
+				),
6168
+				$operator_supplied,
6169
+				implode(",", array_keys($this->_valid_operators))
6170
+			)
6171
+		);
6172
+	}
6173
+
6174
+
6175
+	/**
6176
+	 * Gets the valid operators
6177
+	 *
6178
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6179
+	 */
6180
+	public function valid_operators()
6181
+	{
6182
+		return $this->_valid_operators;
6183
+	}
6184
+
6185
+
6186
+	/**
6187
+	 * Gets the between-style operators (take 2 arguments).
6188
+	 *
6189
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6190
+	 */
6191
+	public function valid_between_style_operators()
6192
+	{
6193
+		return array_intersect(
6194
+			$this->valid_operators(),
6195
+			$this->_between_style_operators
6196
+		);
6197
+	}
6198
+
6199
+
6200
+	/**
6201
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6202
+	 *
6203
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6204
+	 */
6205
+	public function valid_like_style_operators()
6206
+	{
6207
+		return array_intersect(
6208
+			$this->valid_operators(),
6209
+			$this->_like_style_operators
6210
+		);
6211
+	}
6212
+
6213
+
6214
+	/**
6215
+	 * Gets the "in"-style operators
6216
+	 *
6217
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6218
+	 */
6219
+	public function valid_in_style_operators()
6220
+	{
6221
+		return array_intersect(
6222
+			$this->valid_operators(),
6223
+			$this->_in_style_operators
6224
+		);
6225
+	}
6226
+
6227
+
6228
+	/**
6229
+	 * Gets the "null"-style operators (accept no arguments)
6230
+	 *
6231
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6232
+	 */
6233
+	public function valid_null_style_operators()
6234
+	{
6235
+		return array_intersect(
6236
+			$this->valid_operators(),
6237
+			$this->_null_style_operators
6238
+		);
6239
+	}
6240
+
6241
+
6242
+	/**
6243
+	 * Gets an array where keys are the primary keys and values are their 'names'
6244
+	 * (as determined by the model object's name() function, which is often overridden)
6245
+	 *
6246
+	 * @param array $query_params like get_all's
6247
+	 * @return string[]
6248
+	 * @throws EE_Error
6249
+	 * @throws ReflectionException
6250
+	 */
6251
+	public function get_all_names($query_params = [])
6252
+	{
6253
+		$objs  = $this->get_all($query_params);
6254
+		$names = [];
6255
+		foreach ($objs as $obj) {
6256
+			$names[ $obj->ID() ] = $obj->name();
6257
+		}
6258
+		return $names;
6259
+	}
6260
+
6261
+
6262
+	/**
6263
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6264
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6265
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6266
+	 * array_keys() on $model_objects.
6267
+	 *
6268
+	 * @param \EE_Base_Class[] $model_objects
6269
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6270
+	 *                                               in the returned array
6271
+	 * @return array
6272
+	 * @throws EE_Error
6273
+	 * @throws ReflectionException
6274
+	 */
6275
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6276
+	{
6277
+		if (! $this->has_primary_key_field()) {
6278
+			if (defined('WP_DEBUG') && WP_DEBUG) {
6279
+				EE_Error::add_error(
6280
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6281
+					__FILE__,
6282
+					__FUNCTION__,
6283
+					__LINE__
6284
+				);
6285
+			}
6286
+		}
6287
+		$IDs = [];
6288
+		foreach ($model_objects as $model_object) {
6289
+			$id = $model_object->ID();
6290
+			if (! $id) {
6291
+				if ($filter_out_empty_ids) {
6292
+					continue;
6293
+				}
6294
+				if (defined('WP_DEBUG') && WP_DEBUG) {
6295
+					EE_Error::add_error(
6296
+						esc_html__(
6297
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6298
+							'event_espresso'
6299
+						),
6300
+						__FILE__,
6301
+						__FUNCTION__,
6302
+						__LINE__
6303
+					);
6304
+				}
6305
+			}
6306
+			$IDs[] = $id;
6307
+		}
6308
+		return $IDs;
6309
+	}
6310
+
6311
+
6312
+	/**
6313
+	 * Returns the string used in capabilities relating to this model. If there
6314
+	 * are no capabilities that relate to this model returns false
6315
+	 *
6316
+	 * @return string|false
6317
+	 */
6318
+	public function cap_slug()
6319
+	{
6320
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6321
+	}
6322
+
6323
+
6324
+	/**
6325
+	 * Returns the capability-restrictions array (@param string $context
6326
+	 *
6327
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6328
+	 * @throws EE_Error
6329
+	 * @see EEM_Base::_cap_restrictions).
6330
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6331
+	 *      only returns the cap restrictions array in that context (ie, the array
6332
+	 *      at that key)
6333
+	 */
6334
+	public function cap_restrictions($context = EEM_Base::caps_read)
6335
+	{
6336
+		EEM_Base::verify_is_valid_cap_context($context);
6337
+		// check if we ought to run the restriction generator first
6338
+		if (
6339
+			isset($this->_cap_restriction_generators[ $context ])
6340
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6341
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6342
+		) {
6343
+			$this->_cap_restrictions[ $context ] = array_merge(
6344
+				$this->_cap_restrictions[ $context ],
6345
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6346
+			);
6347
+		}
6348
+		// and make sure we've finalized the construction of each restriction
6349
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6350
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6351
+				$where_conditions_obj->_finalize_construct($this);
6352
+			}
6353
+		}
6354
+		return $this->_cap_restrictions[ $context ];
6355
+	}
6356
+
6357
+
6358
+	/**
6359
+	 * Indicating whether or not this model thinks its a wp core model
6360
+	 *
6361
+	 * @return boolean
6362
+	 */
6363
+	public function is_wp_core_model()
6364
+	{
6365
+		return $this->_wp_core_model;
6366
+	}
6367
+
6368
+
6369
+	/**
6370
+	 * Gets all the caps that are missing which impose a restriction on
6371
+	 * queries made in this context
6372
+	 *
6373
+	 * @param string $context one of EEM_Base::caps_ constants
6374
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6375
+	 * @throws EE_Error
6376
+	 */
6377
+	public function caps_missing($context = EEM_Base::caps_read)
6378
+	{
6379
+		$missing_caps     = [];
6380
+		$cap_restrictions = $this->cap_restrictions($context);
6381
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6382
+			if (
6383
+				! EE_Capabilities::instance()
6384
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6385
+			) {
6386
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6387
+			}
6388
+		}
6389
+		return $missing_caps;
6390
+	}
6391
+
6392
+
6393
+	/**
6394
+	 * Gets the mapping from capability contexts to action strings used in capability names
6395
+	 *
6396
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6397
+	 * one of 'read', 'edit', or 'delete'
6398
+	 */
6399
+	public function cap_contexts_to_cap_action_map()
6400
+	{
6401
+		return apply_filters(
6402
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6403
+			$this->_cap_contexts_to_cap_action_map,
6404
+			$this
6405
+		);
6406
+	}
6407
+
6408
+
6409
+	/**
6410
+	 * Gets the action string for the specified capability context
6411
+	 *
6412
+	 * @param string $context
6413
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6414
+	 * @throws EE_Error
6415
+	 */
6416
+	public function cap_action_for_context($context)
6417
+	{
6418
+		$mapping = $this->cap_contexts_to_cap_action_map();
6419
+		if (isset($mapping[ $context ])) {
6420
+			return $mapping[ $context ];
6421
+		}
6422
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6423
+			return $action;
6424
+		}
6425
+		throw new EE_Error(
6426
+			sprintf(
6427
+				esc_html__(
6428
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6429
+					'event_espresso'
6430
+				),
6431
+				$context,
6432
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6433
+			)
6434
+		);
6435
+	}
6436
+
6437
+
6438
+	/**
6439
+	 * Returns all the capability contexts which are valid when querying models
6440
+	 *
6441
+	 * @return array
6442
+	 */
6443
+	public static function valid_cap_contexts(): array
6444
+	{
6445
+		return (array) apply_filters(
6446
+			'FHEE__EEM_Base__valid_cap_contexts',
6447
+			[
6448
+				self::caps_read,
6449
+				self::caps_read_admin,
6450
+				self::caps_edit,
6451
+				self::caps_delete,
6452
+			]
6453
+		);
6454
+	}
6455
+
6456
+
6457
+	/**
6458
+	 * Returns all valid options for 'default_where_conditions'
6459
+	 *
6460
+	 * @return array
6461
+	 */
6462
+	public static function valid_default_where_conditions(): array
6463
+	{
6464
+		return [
6465
+			EEM_Base::default_where_conditions_all,
6466
+			EEM_Base::default_where_conditions_this_only,
6467
+			EEM_Base::default_where_conditions_others_only,
6468
+			EEM_Base::default_where_conditions_minimum_all,
6469
+			EEM_Base::default_where_conditions_minimum_others,
6470
+			EEM_Base::default_where_conditions_none,
6471
+		];
6472
+	}
6473
+
6474
+	// public static function default_where_conditions_full
6475
+
6476
+
6477
+	/**
6478
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6479
+	 *
6480
+	 * @param string $context
6481
+	 * @return bool
6482
+	 * @throws EE_Error
6483
+	 */
6484
+	public static function verify_is_valid_cap_context($context): bool
6485
+	{
6486
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6487
+		if (in_array($context, $valid_cap_contexts)) {
6488
+			return true;
6489
+		}
6490
+		throw new EE_Error(
6491
+			sprintf(
6492
+				esc_html__(
6493
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6494
+					'event_espresso'
6495
+				),
6496
+				$context,
6497
+				'EEM_Base',
6498
+				implode(',', $valid_cap_contexts)
6499
+			)
6500
+		);
6501
+	}
6502
+
6503
+
6504
+	/**
6505
+	 * Clears all the models field caches. This is only useful when a sub-class
6506
+	 * might have added a field or something and these caches might be invalidated
6507
+	 */
6508
+	protected function _invalidate_field_caches()
6509
+	{
6510
+		$this->_cache_foreign_key_to_fields = [];
6511
+		$this->_cached_fields               = null;
6512
+		$this->_cached_fields_non_db_only   = null;
6513
+	}
6514
+
6515
+
6516
+	/**
6517
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6518
+	 * (eg "and", "or", "not").
6519
+	 *
6520
+	 * @return array
6521
+	 */
6522
+	public function logic_query_param_keys(): array
6523
+	{
6524
+		return $this->_logic_query_param_keys;
6525
+	}
6526
+
6527
+
6528
+	/**
6529
+	 * Determines whether or not the where query param array key is for a logic query param.
6530
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6531
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6532
+	 *
6533
+	 * @param $query_param_key
6534
+	 * @return bool
6535
+	 */
6536
+	public function is_logic_query_param_key($query_param_key): bool
6537
+	{
6538
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6539
+			if (
6540
+				$query_param_key === $logic_query_param_key
6541
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6542
+			) {
6543
+				return true;
6544
+			}
6545
+		}
6546
+		return false;
6547
+	}
6548
+
6549
+
6550
+	/**
6551
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6552
+	 *
6553
+	 * @return boolean
6554
+	 * @since 4.9.74.p
6555
+	 */
6556
+	public function hasPassword(): bool
6557
+	{
6558
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6559
+		if ($this->has_password_field === null) {
6560
+			$password_field           = $this->getPasswordField();
6561
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6562
+		}
6563
+		return $this->has_password_field;
6564
+	}
6565
+
6566
+
6567
+	/**
6568
+	 * Returns the password field on this model, if there is one
6569
+	 *
6570
+	 * @return EE_Password_Field|null
6571
+	 * @since 4.9.74.p
6572
+	 */
6573
+	public function getPasswordField()
6574
+	{
6575
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6576
+		// there's no need to search for it. If we don't know yet, then find out
6577
+		if ($this->has_password_field === null && $this->password_field === null) {
6578
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6579
+		}
6580
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6581
+		return $this->password_field;
6582
+	}
6583
+
6584
+
6585
+	/**
6586
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6587
+	 *
6588
+	 * @return EE_Model_Field_Base[]
6589
+	 * @throws EE_Error
6590
+	 * @since 4.9.74.p
6591
+	 */
6592
+	public function getPasswordProtectedFields()
6593
+	{
6594
+		$password_field = $this->getPasswordField();
6595
+		$fields         = [];
6596
+		if ($password_field instanceof EE_Password_Field) {
6597
+			$field_names = $password_field->protectedFields();
6598
+			foreach ($field_names as $field_name) {
6599
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6600
+			}
6601
+		}
6602
+		return $fields;
6603
+	}
6604
+
6605
+
6606
+	/**
6607
+	 * Checks if the current user can perform the requested action on this model
6608
+	 *
6609
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6610
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6611
+	 * @return bool
6612
+	 * @throws EE_Error
6613
+	 * @throws InvalidArgumentException
6614
+	 * @throws InvalidDataTypeException
6615
+	 * @throws InvalidInterfaceException
6616
+	 * @throws ReflectionException
6617
+	 * @throws UnexpectedEntityException
6618
+	 * @since 4.9.74.p
6619
+	 */
6620
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6621
+	{
6622
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6623
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6624
+		}
6625
+		if (! is_array($model_obj_or_fields_n_values)) {
6626
+			throw new UnexpectedEntityException(
6627
+				$model_obj_or_fields_n_values,
6628
+				'EE_Base_Class',
6629
+				sprintf(
6630
+					esc_html__(
6631
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6632
+						'event_espresso'
6633
+					),
6634
+					__FUNCTION__
6635
+				)
6636
+			);
6637
+		}
6638
+		return $this->exists(
6639
+			$this->alter_query_params_to_restrict_by_ID(
6640
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6641
+				[
6642
+					'default_where_conditions' => 'none',
6643
+					'caps'                     => $cap_to_check,
6644
+				]
6645
+			)
6646
+		);
6647
+	}
6648
+
6649
+
6650
+	/**
6651
+	 * Returns the query param where conditions key to the password affecting this model.
6652
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6653
+	 *
6654
+	 * @return null|string
6655
+	 * @throws EE_Error
6656
+	 * @throws InvalidArgumentException
6657
+	 * @throws InvalidDataTypeException
6658
+	 * @throws InvalidInterfaceException
6659
+	 * @throws ModelConfigurationException
6660
+	 * @throws ReflectionException
6661
+	 * @since 4.9.74.p
6662
+	 */
6663
+	public function modelChainAndPassword()
6664
+	{
6665
+		if ($this->model_chain_to_password === null) {
6666
+			throw new ModelConfigurationException(
6667
+				$this,
6668
+				esc_html_x(
6669
+				// @codingStandardsIgnoreStart
6670
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6671
+					// @codingStandardsIgnoreEnd
6672
+					'1: model name',
6673
+					'event_espresso'
6674
+				)
6675
+			);
6676
+		}
6677
+		if ($this->model_chain_to_password === '') {
6678
+			$model_with_password = $this;
6679
+		} else {
6680
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6681
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6682
+			} else {
6683
+				$last_model_in_chain = $this->model_chain_to_password;
6684
+			}
6685
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6686
+		}
6687
+
6688
+		$password_field = $model_with_password->getPasswordField();
6689
+		if ($password_field instanceof EE_Password_Field) {
6690
+			$password_field_name = $password_field->get_name();
6691
+		} else {
6692
+			throw new ModelConfigurationException(
6693
+				$this,
6694
+				sprintf(
6695
+					esc_html_x(
6696
+						'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"',
6697
+						'1: model name, 2: special string',
6698
+						'event_espresso'
6699
+					),
6700
+					$model_with_password->get_this_model_name(),
6701
+					$this->model_chain_to_password
6702
+				)
6703
+			);
6704
+		}
6705
+		return (
6706
+			   $this->model_chain_to_password
6707
+				   ? $this->model_chain_to_password . '.'
6708
+				   : ''
6709
+			   ) . $password_field_name;
6710
+	}
6711
+
6712
+
6713
+	/**
6714
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6715
+	 * or if this model itself has a password affecting access to some of its other fields.
6716
+	 *
6717
+	 * @return boolean
6718
+	 * @since 4.9.74.p
6719
+	 */
6720
+	public function restrictedByRelatedModelPassword(): bool
6721
+	{
6722
+		return $this->model_chain_to_password !== null;
6723
+	}
6724 6724
 }
Please login to merge, or discard this patch.
Spacing   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = '')
568 568
     {
569 569
         // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
570
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
571 571
             throw new EE_Error(
572 572
                 sprintf(
573 573
                     esc_html__(
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          *
591 591
          * @var EE_Table_Base[] $_tables
592 592
          */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
593
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
594 594
         foreach ($this->_tables as $table_alias => $table_obj) {
595 595
             /** @var $table_obj EE_Table_Base */
596 596
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -604,10 +604,10 @@  discard block
 block discarded – undo
604 604
          *
605 605
          * @param EE_Model_Field_Base[] $_fields
606 606
          */
607
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
608 608
         $this->_invalidate_field_caches();
609 609
         foreach ($this->_fields as $table_alias => $fields_for_table) {
610
-            if (! array_key_exists($table_alias, $this->_tables)) {
610
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
611 611
                 throw new EE_Error(
612 612
                     sprintf(
613 613
                         esc_html__(
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
          * @param EE_Model_Relation_Base[] $_model_relations
645 645
          */
646 646
         $this->_model_relations = (array) apply_filters(
647
-            'FHEE__' . get_class($this) . '__construct__model_relations',
647
+            'FHEE__'.get_class($this).'__construct__model_relations',
648 648
             $this->_model_relations
649 649
         );
650 650
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -656,12 +656,12 @@  discard block
 block discarded – undo
656 656
         }
657 657
         $this->set_timezone($timezone);
658 658
         // finalize default where condition strategy, or set default
659
-        if (! $this->_default_where_conditions_strategy) {
659
+        if ( ! $this->_default_where_conditions_strategy) {
660 660
             // nothing was set during child constructor, so set default
661 661
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662 662
         }
663 663
         $this->_default_where_conditions_strategy->_finalize_construct($this);
664
-        if (! $this->_minimum_where_conditions_strategy) {
664
+        if ( ! $this->_minimum_where_conditions_strategy) {
665 665
             // nothing was set during child constructor, so set default
666 666
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667 667
         }
@@ -674,8 +674,8 @@  discard block
 block discarded – undo
674 674
         // initialize the standard cap restriction generators if none were specified by the child constructor
675 675
         if (is_array($this->_cap_restriction_generators)) {
676 676
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
678
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
679 679
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680 680
                         new EE_Restriction_Generator_Protected(),
681 681
                         $cap_context,
@@ -687,10 +687,10 @@  discard block
 block discarded – undo
687 687
         // if there are cap restriction generators, use them to make the default cap restrictions
688 688
         if (is_array($this->_cap_restriction_generators)) {
689 689
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
-                if (! $generator_object) {
690
+                if ( ! $generator_object) {
691 691
                     continue;
692 692
                 }
693
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
693
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
694 694
                     throw new EE_Error(
695 695
                         sprintf(
696 696
                             esc_html__(
@@ -703,12 +703,12 @@  discard block
 block discarded – undo
703 703
                     );
704 704
                 }
705 705
                 $action = $this->cap_action_for_context($context);
706
-                if (! $generator_object->construction_finalized()) {
706
+                if ( ! $generator_object->construction_finalized()) {
707 707
                     $generator_object->_construct_finalize($this, $action);
708 708
                 }
709 709
             }
710 710
         }
711
-        do_action('AHEE__' . get_class($this) . '__construct__end');
711
+        do_action('AHEE__'.get_class($this).'__construct__end');
712 712
     }
713 713
 
714 714
 
@@ -720,7 +720,7 @@  discard block
 block discarded – undo
720 720
      */
721 721
     protected static function getLoader(): LoaderInterface
722 722
     {
723
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
723
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
724 724
             EEM_Base::$loader = LoaderFactory::getLoader();
725 725
         }
726 726
         return EEM_Base::$loader;
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
      */
734 734
     private static function getMirror(): Mirror
735 735
     {
736
-        if (! EEM_Base::$mirror instanceof Mirror) {
736
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
737 737
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738 738
         }
739 739
         return EEM_Base::$mirror;
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
     public static function instance($timezone = '')
790 790
     {
791 791
         // check if instance of Espresso_model already exists
792
-        if (! static::$_instance instanceof static) {
792
+        if ( ! static::$_instance instanceof static) {
793 793
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794 794
             $model     = new static(...$arguments);
795 795
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
      */
819 819
     public static function reset($timezone = '')
820 820
     {
821
-        if (! static::$_instance instanceof EEM_Base) {
821
+        if ( ! static::$_instance instanceof EEM_Base) {
822 822
             return null;
823 823
         }
824 824
         // Let's NOT swap out the current instance for a new one
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830 830
             // don't set instance to null like it was originally,
831 831
             // but it's static anyways, and we're ignoring static properties (for now at least)
832
-            if (! isset($static_properties[ $property ])) {
832
+            if ( ! isset($static_properties[$property])) {
833 833
                 static::$_instance->{$property} = $value;
834 834
             }
835 835
         }
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
      */
879 879
     public function status_array($translated = false)
880 880
     {
881
-        if (! array_key_exists('Status', $this->_model_relations)) {
881
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
882 882
             return [];
883 883
         }
884 884
         $model_name   = $this->get_this_model_name();
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887 887
         $status_array = [];
888 888
         foreach ($stati as $status) {
889
-            $status_array[ $status->ID() ] = $status->get('STS_code');
889
+            $status_array[$status->ID()] = $status->get('STS_code');
890 890
         }
891 891
         return $translated
892 892
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
     {
952 952
         $wp_user_field_name = $this->wp_user_field_name();
953 953
         if ($wp_user_field_name) {
954
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
954
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
955 955
         }
956 956
         return $query_params;
957 957
     }
@@ -970,17 +970,17 @@  discard block
 block discarded – undo
970 970
     public function wp_user_field_name()
971 971
     {
972 972
         try {
973
-            if (! empty($this->_model_chain_to_wp_user)) {
973
+            if ( ! empty($this->_model_chain_to_wp_user)) {
974 974
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975 975
                 $last_model_name              = end($models_to_follow_to_wp_users);
976 976
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
977
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
978 978
             } else {
979 979
                 $model_with_fk_to_wp_users = $this;
980 980
                 $model_chain_to_wp_user    = '';
981 981
             }
982 982
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
983
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
984 984
         } catch (EE_Error $e) {
985 985
             return false;
986 986
         }
@@ -1056,11 +1056,11 @@  discard block
 block discarded – undo
1056 1056
         if ($this->_custom_selections instanceof CustomSelects) {
1057 1057
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058 1058
             $select_expressions .= $select_expressions
1059
-                ? ', ' . $custom_expressions
1059
+                ? ', '.$custom_expressions
1060 1060
                 : $custom_expressions;
1061 1061
         }
1062 1062
 
1063
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1063
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1064 1064
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065 1065
     }
1066 1066
 
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
      */
1078 1078
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079 1079
     {
1080
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1080
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081 1081
             return null;
1082 1082
         }
1083 1083
         $selects = $query_params['extra_selects'] ?? $columns_to_select;
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
         if (is_array($columns_to_select)) {
1129 1129
             $select_sql_array = [];
1130 1130
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1131
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132 1132
                     throw new EE_Error(
1133 1133
                         sprintf(
1134 1134
                             esc_html__(
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
                         )
1141 1141
                     );
1142 1142
                 }
1143
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1143
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144 1144
                     throw new EE_Error(
1145 1145
                         sprintf(
1146 1146
                             esc_html__(
@@ -1202,7 +1202,7 @@  discard block
 block discarded – undo
1202 1202
                 ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203 1203
             )
1204 1204
         );
1205
-        $className    = $this->_get_class_name();
1205
+        $className = $this->_get_class_name();
1206 1206
         if ($model_object instanceof $className) {
1207 1207
             // make sure valid objects get added to the entity map
1208 1208
             // so that the next call to this method doesn't trigger another trip to the db
@@ -1225,12 +1225,12 @@  discard block
 block discarded – undo
1225 1225
      */
1226 1226
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227 1227
     {
1228
-        if (! isset($query_params[0])) {
1228
+        if ( ! isset($query_params[0])) {
1229 1229
             $query_params[0] = [];
1230 1230
         }
1231 1231
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1232 1232
         if ($conditions_from_id === null) {
1233
-            $query_params[0][ $this->primary_key_name() ] = $id;
1233
+            $query_params[0][$this->primary_key_name()] = $id;
1234 1234
         } else {
1235 1235
             // no primary key, so the $id must be from the get_index_primary_key_string()
1236 1236
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1250,7 +1250,7 @@  discard block
 block discarded – undo
1250 1250
      */
1251 1251
     public function get_one($query_params = [])
1252 1252
     {
1253
-        if (! is_array($query_params)) {
1253
+        if ( ! is_array($query_params)) {
1254 1254
             EE_Error::doing_it_wrong(
1255 1255
                 'EEM_Base::get_one',
1256 1256
                 sprintf(
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
                 return [];
1460 1460
             }
1461 1461
         }
1462
-        if (! is_array($query_params)) {
1462
+        if ( ! is_array($query_params)) {
1463 1463
             EE_Error::doing_it_wrong(
1464 1464
                 'EEM_Base::_get_consecutive',
1465 1465
                 sprintf(
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
             $query_params = [];
1472 1472
         }
1473 1473
         // let's add the where query param for consecutive look up.
1474
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1474
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1475 1475
         $query_params['limit']                 = $limit;
1476 1476
         // set direction
1477 1477
         $incoming_orderby         = isset($query_params['order_by'])
@@ -1497,7 +1497,7 @@  discard block
 block discarded – undo
1497 1497
      */
1498 1498
     public function set_timezone(?string $timezone = '')
1499 1499
     {
1500
-        if (! $timezone) {
1500
+        if ( ! $timezone) {
1501 1501
             return;
1502 1502
         }
1503 1503
         $this->_timezone = $timezone;
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
     {
1555 1555
         $field_settings = $this->field_settings_for($field_name);
1556 1556
         // if not a valid EE_Datetime_Field then throw error
1557
-        if (! $field_settings instanceof EE_Datetime_Field) {
1557
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1558 1558
             throw new EE_Error(
1559 1559
                 sprintf(
1560 1560
                     esc_html__(
@@ -1641,7 +1641,7 @@  discard block
 block discarded – undo
1641 1641
         // just using this to ensure the timezone is set correctly internally
1642 1642
         $this->get_formats_for($field_name);
1643 1643
         // load EEH_DTT_Helper
1644
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1644
+        $timezone_string = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645 1645
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646 1646
         EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647 1647
         return DbSafeDateTime::createFromDateTime($incomingDateTime);
@@ -1711,7 +1711,7 @@  discard block
 block discarded – undo
1711 1711
      */
1712 1712
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713 1713
     {
1714
-        if (! is_array($query_params)) {
1714
+        if ( ! is_array($query_params)) {
1715 1715
             EE_Error::doing_it_wrong(
1716 1716
                 'EEM_Base::update',
1717 1717
                 sprintf(
@@ -1759,7 +1759,7 @@  discard block
 block discarded – undo
1759 1759
             $wpdb_result = (array) $wpdb_result;
1760 1760
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761 1761
             if ($this->has_primary_key_field()) {
1762
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1762
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1763 1763
             } else {
1764 1764
                 // 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)
1765 1765
                 $main_table_pk_value = null;
@@ -1775,7 +1775,7 @@  discard block
 block discarded – undo
1775 1775
                     // in this table, right? so insert a row in the current table, using any fields available
1776 1776
                     if (
1777 1777
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
-                           && $wpdb_result[ $this_table_pk_column ])
1778
+                           && $wpdb_result[$this_table_pk_column])
1779 1779
                     ) {
1780 1780
                         $success = $this->_insert_into_specific_table(
1781 1781
                             $table_obj,
@@ -1783,7 +1783,7 @@  discard block
 block discarded – undo
1783 1783
                             $main_table_pk_value
1784 1784
                         );
1785 1785
                         // if we died here, report the error
1786
-                        if (! $success) {
1786
+                        if ( ! $success) {
1787 1787
                             return false;
1788 1788
                         }
1789 1789
                     }
@@ -1811,10 +1811,10 @@  discard block
 block discarded – undo
1811 1811
                 $model_objs_affected_ids     = [];
1812 1812
                 foreach ($models_affected_key_columns as $row) {
1813 1813
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1814
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1814
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1815 1815
                 }
1816 1816
             }
1817
-            if (! $model_objs_affected_ids) {
1817
+            if ( ! $model_objs_affected_ids) {
1818 1818
                 // wait wait wait- if nothing was affected let's stop here
1819 1819
                 return 0;
1820 1820
             }
@@ -1843,8 +1843,8 @@  discard block
 block discarded – undo
1843 1843
         $rows_affected = $this->_do_wpdb_query(
1844 1844
             'query',
1845 1845
             [
1846
-                "UPDATE " . $model_query_info->get_full_join_sql()
1847
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1846
+                "UPDATE ".$model_query_info->get_full_join_sql()
1847
+                . " SET ".$this->_construct_update_sql($fields_n_values)
1848 1848
                 . $model_query_info->get_where_sql(),
1849 1849
             ]
1850 1850
         );
@@ -1858,7 +1858,7 @@  discard block
 block discarded – undo
1858 1858
          * @param int      $rows_affected
1859 1859
          */
1860 1860
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
-        return $rows_affected;// how many supposedly got updated
1861
+        return $rows_affected; // how many supposedly got updated
1862 1862
     }
1863 1863
 
1864 1864
 
@@ -1891,7 +1891,7 @@  discard block
 block discarded – undo
1891 1891
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892 1892
         $select_expressions = $field->get_qualified_column();
1893 1893
         $SQL                =
1894
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1894
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1895 1895
         return $this->_do_wpdb_query('get_col', [$SQL]);
1896 1896
     }
1897 1897
 
@@ -1910,7 +1910,7 @@  discard block
 block discarded – undo
1910 1910
     {
1911 1911
         $query_params['limit'] = 1;
1912 1912
         $col                   = $this->get_col($query_params, $field_to_select);
1913
-        if (! empty($col)) {
1913
+        if ( ! empty($col)) {
1914 1914
             return reset($col);
1915 1915
         }
1916 1916
         return null;
@@ -1941,7 +1941,7 @@  discard block
 block discarded – undo
1941 1941
             $value_sql       = $prepared_value === null
1942 1942
                 ? 'NULL'
1943 1943
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1944
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1945 1945
         }
1946 1946
         return implode(",", $cols_n_values);
1947 1947
     }
@@ -2076,7 +2076,7 @@  discard block
 block discarded – undo
2076 2076
                                 . $model_query_info->get_full_join_sql()
2077 2077
                                 . " WHERE "
2078 2078
                                 . $deletion_where_query_part;
2079
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2079
+            $rows_deleted = $this->_do_wpdb_query('query', [$SQL]);
2080 2080
         }
2081 2081
 
2082 2082
         // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
@@ -2084,12 +2084,12 @@  discard block
 block discarded – undo
2084 2084
         if (
2085 2085
             $this->has_primary_key_field()
2086 2086
             && $rows_deleted !== false
2087
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2087
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2088 2088
         ) {
2089
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2089
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2090 2090
             foreach ($ids_for_removal as $id) {
2091
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2092
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2091
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2092
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2093 2093
                 }
2094 2094
             }
2095 2095
 
@@ -2128,7 +2128,7 @@  discard block
 block discarded – undo
2128 2128
          * @param int      $rows_deleted
2129 2129
          */
2130 2130
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2131
-        return (int) $rows_deleted;// how many supposedly got deleted
2131
+        return (int) $rows_deleted; // how many supposedly got deleted
2132 2132
     }
2133 2133
 
2134 2134
 
@@ -2227,15 +2227,15 @@  discard block
 block discarded – undo
2227 2227
                 if (
2228 2228
                     $allow_blocking
2229 2229
                     && $this->delete_is_blocked_by_related_models(
2230
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2230
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2231 2231
                     )
2232 2232
                 ) {
2233 2233
                     continue;
2234 2234
                 }
2235 2235
                 // primary table deletes
2236
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2237
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2238
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2236
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2237
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2238
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2239 2239
                 }
2240 2240
             }
2241 2241
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2244,8 +2244,8 @@  discard block
 block discarded – undo
2244 2244
                 $ids_to_delete_indexed_by_column_for_row = [];
2245 2245
                 foreach ($fields as $cpk_field) {
2246 2246
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2247
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2248
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2247
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2248
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2249 2249
                     }
2250 2250
                 }
2251 2251
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2283,7 +2283,7 @@  discard block
 block discarded – undo
2283 2283
         } elseif ($this->has_primary_key_field()) {
2284 2284
             $query = [];
2285 2285
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2286
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2286
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2287 2287
             }
2288 2288
             $query_part = ! empty($query)
2289 2289
                 ? implode(' AND ', $query)
@@ -2293,7 +2293,7 @@  discard block
 block discarded – undo
2293 2293
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2294 2294
                 $values_for_each_combined_primary_key_for_a_row = [];
2295 2295
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2296
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2296
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2297 2297
                 }
2298 2298
                 $ways_to_identify_a_row[] = '('
2299 2299
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2369,10 +2369,10 @@  discard block
 block discarded – undo
2369 2369
             }
2370 2370
         }
2371 2371
         $column_to_count = $distinct
2372
-            ? "DISTINCT " . $column_to_count
2372
+            ? "DISTINCT ".$column_to_count
2373 2373
             : $column_to_count;
2374 2374
         $SQL             =
2375
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2375
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2376 2376
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2377 2377
     }
2378 2378
 
@@ -2397,7 +2397,7 @@  discard block
 block discarded – undo
2397 2397
         }
2398 2398
         $column_to_count = $field_obj->get_qualified_column();
2399 2399
         $SQL             =
2400
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2400
+            "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2401 2401
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2402 2402
         $data_type       = $field_obj->get_wpdb_data_type();
2403 2403
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2433,7 +2433,7 @@  discard block
 block discarded – undo
2433 2433
         }
2434 2434
         /** @type WPDB $wpdb */
2435 2435
         global $wpdb;
2436
-        if (! method_exists($wpdb, $wpdb_method)) {
2436
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2437 2437
             throw new DomainException(
2438 2438
                 sprintf(
2439 2439
                     esc_html__(
@@ -2452,7 +2452,7 @@  discard block
 block discarded – undo
2452 2452
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2453 2453
         if (defined('WP_DEBUG') && WP_DEBUG) {
2454 2454
             $wpdb->show_errors($old_show_errors_value);
2455
-            if (! empty($wpdb->last_error)) {
2455
+            if ( ! empty($wpdb->last_error)) {
2456 2456
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2457 2457
             }
2458 2458
             if ($result === false) {
@@ -2522,7 +2522,7 @@  discard block
 block discarded – undo
2522 2522
                     // ummmm... you in trouble
2523 2523
                     return $result;
2524 2524
             }
2525
-            if (! empty($error_message)) {
2525
+            if ( ! empty($error_message)) {
2526 2526
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2527 2527
                 trigger_error($error_message);
2528 2528
             }
@@ -2603,11 +2603,11 @@  discard block
 block discarded – undo
2603 2603
      */
2604 2604
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2605 2605
     {
2606
-        return " FROM " . $model_query_info->get_full_join_sql() .
2607
-               $model_query_info->get_where_sql() .
2608
-               $model_query_info->get_group_by_sql() .
2609
-               $model_query_info->get_having_sql() .
2610
-               $model_query_info->get_order_by_sql() .
2606
+        return " FROM ".$model_query_info->get_full_join_sql().
2607
+               $model_query_info->get_where_sql().
2608
+               $model_query_info->get_group_by_sql().
2609
+               $model_query_info->get_having_sql().
2610
+               $model_query_info->get_order_by_sql().
2611 2611
                $model_query_info->get_limit_sql();
2612 2612
     }
2613 2613
 
@@ -2632,7 +2632,7 @@  discard block
 block discarded – undo
2632 2632
             $left = is_admin() ? '12rem' : '2rem';
2633 2633
             echo "
2634 2634
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2635
-                " . esc_html($sql_query) . "
2635
+                ".esc_html($sql_query)."
2636 2636
             </div>";
2637 2637
             $this->_show_next_x_db_queries--;
2638 2638
         }
@@ -2808,12 +2808,12 @@  discard block
 block discarded – undo
2808 2808
         $related_model = $this->get_related_model_obj($model_name);
2809 2809
         // we're just going to use the query params on the related model's normal get_all query,
2810 2810
         // except add a condition to say to match the current mod
2811
-        if (! isset($query_params['default_where_conditions'])) {
2811
+        if ( ! isset($query_params['default_where_conditions'])) {
2812 2812
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2813 2813
         }
2814 2814
         $this_model_name                                                 = $this->get_this_model_name();
2815 2815
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2816
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2816
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2817 2817
         return $related_model->count($query_params, $field_to_count, $distinct);
2818 2818
     }
2819 2819
 
@@ -2834,7 +2834,7 @@  discard block
 block discarded – undo
2834 2834
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2835 2835
     {
2836 2836
         $related_model = $this->get_related_model_obj($model_name);
2837
-        if (! is_array($query_params)) {
2837
+        if ( ! is_array($query_params)) {
2838 2838
             EE_Error::doing_it_wrong(
2839 2839
                 'EEM_Base::sum_related',
2840 2840
                 sprintf(
@@ -2847,12 +2847,12 @@  discard block
 block discarded – undo
2847 2847
         }
2848 2848
         // we're just going to use the query params on the related model's normal get_all query,
2849 2849
         // except add a condition to say to match the current mod
2850
-        if (! isset($query_params['default_where_conditions'])) {
2850
+        if ( ! isset($query_params['default_where_conditions'])) {
2851 2851
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2852 2852
         }
2853 2853
         $this_model_name                                                 = $this->get_this_model_name();
2854 2854
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2855
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2855
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2856 2856
         return $related_model->sum($query_params, $field_to_sum);
2857 2857
     }
2858 2858
 
@@ -2904,7 +2904,7 @@  discard block
 block discarded – undo
2904 2904
                 $field_with_model_name = $field;
2905 2905
             }
2906 2906
         }
2907
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2907
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2908 2908
             throw new EE_Error(
2909 2909
                 sprintf(
2910 2910
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -3043,14 +3043,14 @@  discard block
 block discarded – undo
3043 3043
                 || $this->get_primary_key_field()
3044 3044
                    instanceof
3045 3045
                    EE_Primary_Key_String_Field)
3046
-            && isset($fields_n_values[ $this->primary_key_name() ])
3046
+            && isset($fields_n_values[$this->primary_key_name()])
3047 3047
         ) {
3048
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3048
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
3049 3049
         }
3050 3050
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3051 3051
             $uniqueness_where_params                              =
3052 3052
                 array_intersect_key($fields_n_values, $unique_index->fields());
3053
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3053
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
3054 3054
         }
3055 3055
         // if there is nothing to base this search on, then we shouldn't find anything
3056 3056
         if (empty($query_params)) {
@@ -3127,16 +3127,16 @@  discard block
 block discarded – undo
3127 3127
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3128 3128
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3129 3129
             if ($prepared_value !== null) {
3130
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3130
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3131 3131
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3132 3132
             }
3133 3133
         }
3134 3134
         if ($table instanceof EE_Secondary_Table && $new_id) {
3135 3135
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3136 3136
             // so add the fk to the main table as a column
3137
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3137
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3138 3138
             $format_for_insertion[]                              =
3139
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3139
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3140 3140
         }
3141 3141
 
3142 3142
         // insert the new entry
@@ -3154,7 +3154,7 @@  discard block
 block discarded – undo
3154 3154
             }
3155 3155
             // it's not an auto-increment primary key, so
3156 3156
             // it must have been supplied
3157
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3157
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3158 3158
         }
3159 3159
         // we can't return a  primary key because there is none. instead return
3160 3160
         // a unique string indicating this model
@@ -3176,10 +3176,10 @@  discard block
 block discarded – undo
3176 3176
     {
3177 3177
         $field_name = $field_obj->get_name();
3178 3178
         // if this field doesn't allow nullable, don't allow it
3179
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3180
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3179
+        if ( ! $field_obj->is_nullable() && ! isset($fields_n_values[$field_name])) {
3180
+            $fields_n_values[$field_name] = $field_obj->get_default_value();
3181 3181
         }
3182
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3182
+        $unprepared_value = $fields_n_values[$field_name] ?? null;
3183 3183
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3184 3184
     }
3185 3185
 
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
      */
3283 3283
     public function get_table_obj_by_alias($table_alias = '')
3284 3284
     {
3285
-        return $this->_tables[ $table_alias ] ?? null;
3285
+        return $this->_tables[$table_alias] ?? null;
3286 3286
     }
3287 3287
 
3288 3288
 
@@ -3296,7 +3296,7 @@  discard block
 block discarded – undo
3296 3296
         $other_tables = [];
3297 3297
         foreach ($this->_tables as $table_alias => $table) {
3298 3298
             if ($table instanceof EE_Secondary_Table) {
3299
-                $other_tables[ $table_alias ] = $table;
3299
+                $other_tables[$table_alias] = $table;
3300 3300
             }
3301 3301
         }
3302 3302
         return $other_tables;
@@ -3311,7 +3311,7 @@  discard block
 block discarded – undo
3311 3311
      */
3312 3312
     public function _get_fields_for_table($table_alias)
3313 3313
     {
3314
-        return $this->_fields[ $table_alias ];
3314
+        return $this->_fields[$table_alias];
3315 3315
     }
3316 3316
 
3317 3317
 
@@ -3340,7 +3340,7 @@  discard block
 block discarded – undo
3340 3340
                     $query_info_carrier,
3341 3341
                     'group_by'
3342 3342
                 );
3343
-            } elseif (! empty($query_params['group_by'])) {
3343
+            } elseif ( ! empty($query_params['group_by'])) {
3344 3344
                 $this->_extract_related_model_info_from_query_param(
3345 3345
                     $query_params['group_by'],
3346 3346
                     $query_info_carrier,
@@ -3362,7 +3362,7 @@  discard block
 block discarded – undo
3362 3362
                     $query_info_carrier,
3363 3363
                     'order_by'
3364 3364
                 );
3365
-            } elseif (! empty($query_params['order_by'])) {
3365
+            } elseif ( ! empty($query_params['order_by'])) {
3366 3366
                 $this->_extract_related_model_info_from_query_param(
3367 3367
                     $query_params['order_by'],
3368 3368
                     $query_info_carrier,
@@ -3397,7 +3397,7 @@  discard block
 block discarded – undo
3397 3397
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3398 3398
         $query_param_type
3399 3399
     ) {
3400
-        if (! empty($sub_query_params)) {
3400
+        if ( ! empty($sub_query_params)) {
3401 3401
             $sub_query_params = (array) $sub_query_params;
3402 3402
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3403 3403
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3413,7 +3413,7 @@  discard block
 block discarded – undo
3413 3413
                 $query_param_sans_stars =
3414 3414
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3415 3415
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3416
-                    if (! is_array($possibly_array_of_params)) {
3416
+                    if ( ! is_array($possibly_array_of_params)) {
3417 3417
                         throw new EE_Error(
3418 3418
                             sprintf(
3419 3419
                                 esc_html__(
@@ -3439,7 +3439,7 @@  discard block
 block discarded – undo
3439 3439
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3440 3440
                     // indicating that $possible_array_of_params[1] is actually a field name,
3441 3441
                     // from which we should extract query parameters!
3442
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3442
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3443 3443
                         throw new EE_Error(
3444 3444
                             sprintf(
3445 3445
                                 esc_html__(
@@ -3479,8 +3479,8 @@  discard block
 block discarded – undo
3479 3479
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3480 3480
         $query_param_type
3481 3481
     ) {
3482
-        if (! empty($sub_query_params)) {
3483
-            if (! is_array($sub_query_params)) {
3482
+        if ( ! empty($sub_query_params)) {
3483
+            if ( ! is_array($sub_query_params)) {
3484 3484
                 throw new EE_Error(
3485 3485
                     sprintf(
3486 3486
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3518,7 +3518,7 @@  discard block
 block discarded – undo
3518 3518
      */
3519 3519
     public function _create_model_query_info_carrier($query_params)
3520 3520
     {
3521
-        if (! is_array($query_params)) {
3521
+        if ( ! is_array($query_params)) {
3522 3522
             EE_Error::doing_it_wrong(
3523 3523
                 'EEM_Base::_create_model_query_info_carrier',
3524 3524
                 sprintf(
@@ -3549,7 +3549,7 @@  discard block
 block discarded – undo
3549 3549
             // only include if related to a cpt where no password has been set
3550 3550
             $query_params[0]['OR*nopassword'] = [
3551 3551
                 $where_param_key_for_password       => '',
3552
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3552
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3553 3553
             ];
3554 3554
         }
3555 3555
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3603,7 +3603,7 @@  discard block
 block discarded – undo
3603 3603
         // set limit
3604 3604
         if (array_key_exists('limit', $query_params)) {
3605 3605
             if (is_array($query_params['limit'])) {
3606
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3606
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3607 3607
                     $e = sprintf(
3608 3608
                         esc_html__(
3609 3609
                             "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)",
@@ -3611,12 +3611,12 @@  discard block
 block discarded – undo
3611 3611
                         ),
3612 3612
                         http_build_query($query_params['limit'])
3613 3613
                     );
3614
-                    throw new EE_Error($e . "|" . $e);
3614
+                    throw new EE_Error($e."|".$e);
3615 3615
                 }
3616 3616
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3617
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3618
-            } elseif (! empty($query_params['limit'])) {
3619
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3617
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3618
+            } elseif ( ! empty($query_params['limit'])) {
3619
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3620 3620
             }
3621 3621
         }
3622 3622
         // set order by
@@ -3648,10 +3648,10 @@  discard block
 block discarded – undo
3648 3648
                 $order_array = [];
3649 3649
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3650 3650
                     $order         = $this->_extract_order($order);
3651
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3651
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3652 3652
                 }
3653
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3654
-            } elseif (! empty($query_params['order_by'])) {
3653
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3654
+            } elseif ( ! empty($query_params['order_by'])) {
3655 3655
                 $this->_extract_related_model_info_from_query_param(
3656 3656
                     $query_params['order_by'],
3657 3657
                     $query_object,
@@ -3662,7 +3662,7 @@  discard block
 block discarded – undo
3662 3662
                     ? $this->_extract_order($query_params['order'])
3663 3663
                     : 'DESC';
3664 3664
                 $query_object->set_order_by_sql(
3665
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3665
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3666 3666
                 );
3667 3667
             }
3668 3668
         }
@@ -3674,7 +3674,7 @@  discard block
 block discarded – undo
3674 3674
         ) {
3675 3675
             $pk_field = $this->get_primary_key_field();
3676 3676
             $order    = $this->_extract_order($query_params['order']);
3677
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3677
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3678 3678
         }
3679 3679
         // set group by
3680 3680
         if (array_key_exists('group_by', $query_params)) {
@@ -3684,10 +3684,10 @@  discard block
 block discarded – undo
3684 3684
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3685 3685
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3686 3686
                 }
3687
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3688
-            } elseif (! empty($query_params['group_by'])) {
3687
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3688
+            } elseif ( ! empty($query_params['group_by'])) {
3689 3689
                 $query_object->set_group_by_sql(
3690
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3690
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3691 3691
                 );
3692 3692
             }
3693 3693
         }
@@ -3697,7 +3697,7 @@  discard block
 block discarded – undo
3697 3697
         }
3698 3698
         // now, just verify they didn't pass anything wack
3699 3699
         foreach ($query_params as $query_key => $query_value) {
3700
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3700
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3701 3701
                 throw new EE_Error(
3702 3702
                     sprintf(
3703 3703
                         esc_html__(
@@ -3802,7 +3802,7 @@  discard block
 block discarded – undo
3802 3802
         $where_query_params = []
3803 3803
     ) {
3804 3804
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3805
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3805
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3806 3806
             throw new EE_Error(
3807 3807
                 sprintf(
3808 3808
                     esc_html__(
@@ -3832,7 +3832,7 @@  discard block
 block discarded – undo
3832 3832
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3833 3833
                 continue;
3834 3834
             }
3835
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3835
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3836 3836
                 $related_model_universal_where_params,
3837 3837
                 $where_query_params,
3838 3838
                 $related_model,
@@ -3941,19 +3941,19 @@  discard block
 block discarded – undo
3941 3941
     ) {
3942 3942
         $null_friendly_where_conditions = [];
3943 3943
         $none_overridden                = true;
3944
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3944
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3945 3945
         foreach ($default_where_conditions as $key => $val) {
3946
-            if (isset($provided_where_conditions[ $key ])) {
3946
+            if (isset($provided_where_conditions[$key])) {
3947 3947
                 $none_overridden = false;
3948 3948
             } else {
3949
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3949
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3950 3950
             }
3951 3951
         }
3952 3952
         if ($none_overridden && $default_where_conditions) {
3953 3953
             if ($model->has_primary_key_field()) {
3954
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3954
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3955 3955
                                                                                    . "."
3956
-                                                                                   . $model->primary_key_name() ] =
3956
+                                                                                   . $model->primary_key_name()] =
3957 3957
                     ['IS NULL'];
3958 3958
             }/*else{
3959 3959
                 //@todo NO PK, use other defaults
@@ -4064,7 +4064,7 @@  discard block
 block discarded – undo
4064 4064
             foreach ($tables as $table_obj) {
4065 4065
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4066 4066
                                        . $table_obj->get_fully_qualified_pk_column();
4067
-                if (! in_array($qualified_pk_column, $selects)) {
4067
+                if ( ! in_array($qualified_pk_column, $selects)) {
4068 4068
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4069 4069
                 }
4070 4070
             }
@@ -4216,9 +4216,9 @@  discard block
 block discarded – undo
4216 4216
         $query_parameter_type
4217 4217
     ) {
4218 4218
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4219
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4219
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4220 4220
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4221
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4221
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4222 4222
                 if ($possible_join_string === '') {
4223 4223
                     // nothing left to $query_param
4224 4224
                     // we should actually end in a field name, not a model like this!
@@ -4351,7 +4351,7 @@  discard block
 block discarded – undo
4351 4351
     {
4352 4352
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4353 4353
         if ($SQL) {
4354
-            return " WHERE " . $SQL;
4354
+            return " WHERE ".$SQL;
4355 4355
         }
4356 4356
         return '';
4357 4357
     }
@@ -4369,7 +4369,7 @@  discard block
 block discarded – undo
4369 4369
     {
4370 4370
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4371 4371
         if ($SQL) {
4372
-            return " HAVING " . $SQL;
4372
+            return " HAVING ".$SQL;
4373 4373
         }
4374 4374
         return '';
4375 4375
     }
@@ -4423,7 +4423,7 @@  discard block
 block discarded – undo
4423 4423
             } else {
4424 4424
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4425 4425
                 // if it's not a normal field, maybe it's a custom selection?
4426
-                if (! $field_obj) {
4426
+                if ( ! $field_obj) {
4427 4427
                     if ($this->_custom_selections instanceof CustomSelects) {
4428 4428
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4429 4429
                     } else {
@@ -4439,7 +4439,7 @@  discard block
 block discarded – undo
4439 4439
                     }
4440 4440
                 }
4441 4441
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4442
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4442
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4443 4443
             }
4444 4444
         }
4445 4445
         return $where_clauses
@@ -4463,7 +4463,7 @@  discard block
 block discarded – undo
4463 4463
                 $field->get_model_name(),
4464 4464
                 $query_param
4465 4465
             );
4466
-            return $table_alias_prefix . $field->get_qualified_column();
4466
+            return $table_alias_prefix.$field->get_qualified_column();
4467 4467
         }
4468 4468
         if (
4469 4469
             $this->_custom_selections instanceof CustomSelects
@@ -4524,7 +4524,7 @@  discard block
 block discarded – undo
4524 4524
             $operator = isset($op_and_value[0])
4525 4525
                 ? $this->_prepare_operator_for_sql($op_and_value[0])
4526 4526
                 : null;
4527
-            if (! $operator) {
4527
+            if ( ! $operator) {
4528 4528
                 $php_array_like_string = [];
4529 4529
                 foreach ($op_and_value as $key => $value) {
4530 4530
                     $php_array_like_string[] = "$key=>$value";
@@ -4544,14 +4544,14 @@  discard block
 block discarded – undo
4544 4544
 
4545 4545
         // check to see if the value is actually another field
4546 4546
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4547
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4547
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4548 4548
         }
4549 4549
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4550 4550
             // in this case, the value should be an array, or at least a comma-separated list
4551 4551
             // it will need to handle a little differently
4552 4552
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4553 4553
             // note: $cleaned_value has already been run through $wpdb->prepare()
4554
-            return $operator . SP . $cleaned_value;
4554
+            return $operator.SP.$cleaned_value;
4555 4555
         }
4556 4556
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4557 4557
             // the value should be an array with count of two.
@@ -4567,7 +4567,7 @@  discard block
 block discarded – undo
4567 4567
                 );
4568 4568
             }
4569 4569
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4570
-            return $operator . SP . $cleaned_value;
4570
+            return $operator.SP.$cleaned_value;
4571 4571
         }
4572 4572
         if (in_array($operator, $this->valid_null_style_operators())) {
4573 4573
             if ($value !== null) {
@@ -4587,10 +4587,10 @@  discard block
 block discarded – undo
4587 4587
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4588 4588
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4589 4589
             // remove other junk. So just treat it as a string.
4590
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4590
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4591 4591
         }
4592
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4593
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4592
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4593
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4594 4594
         }
4595 4595
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4596 4596
             throw new EE_Error(
@@ -4604,7 +4604,7 @@  discard block
 block discarded – undo
4604 4604
                 )
4605 4605
             );
4606 4606
         }
4607
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4607
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4608 4608
             throw new EE_Error(
4609 4609
                 sprintf(
4610 4610
                     esc_html__(
@@ -4643,7 +4643,7 @@  discard block
 block discarded – undo
4643 4643
         foreach ($values as $value) {
4644 4644
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4645 4645
         }
4646
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4646
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4647 4647
     }
4648 4648
 
4649 4649
 
@@ -4681,7 +4681,7 @@  discard block
 block discarded – undo
4681 4681
             $main_table  = $this->_get_main_table();
4682 4682
             $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4683 4683
         }
4684
-        return '(' . implode(',', $prepped) . ')';
4684
+        return '('.implode(',', $prepped).')';
4685 4685
     }
4686 4686
 
4687 4687
 
@@ -4701,7 +4701,7 @@  discard block
 block discarded – undo
4701 4701
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4702 4702
             );
4703 4703
         } //$field_obj should really just be a data type
4704
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4704
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4705 4705
             throw new EE_Error(
4706 4706
                 sprintf(
4707 4707
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4738,14 +4738,14 @@  discard block
 block discarded – undo
4738 4738
             );
4739 4739
         }
4740 4740
         $number_of_parts       = count($query_param_parts);
4741
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4741
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4742 4742
         if ($number_of_parts === 1) {
4743 4743
             $field_name = $last_query_param_part;
4744 4744
             $model_obj  = $this;
4745 4745
         } else {// $number_of_parts >= 2
4746 4746
             // the last part is the column name, and there are only 2parts. therefore...
4747 4747
             $field_name = $last_query_param_part;
4748
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4748
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4749 4749
         }
4750 4750
         try {
4751 4751
             return $model_obj->field_settings_for($field_name);
@@ -4766,7 +4766,7 @@  discard block
 block discarded – undo
4766 4766
     public function _get_qualified_column_for_field($field_name)
4767 4767
     {
4768 4768
         $all_fields = $this->field_settings();
4769
-        $field      = $all_fields[ $field_name ] ?? false;
4769
+        $field      = $all_fields[$field_name] ?? false;
4770 4770
         if ($field) {
4771 4771
             return $field->get_qualified_column();
4772 4772
         }
@@ -4836,12 +4836,12 @@  discard block
 block discarded – undo
4836 4836
      */
4837 4837
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4838 4838
     {
4839
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4839
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain)
4840 4840
                 ? ''
4841 4841
                 : '__');
4842 4842
         $qualified_columns = [];
4843 4843
         foreach ($this->field_settings() as $field_name => $field) {
4844
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4844
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4845 4845
         }
4846 4846
         return $return_string
4847 4847
             ? implode(', ', $qualified_columns)
@@ -4868,11 +4868,11 @@  discard block
 block discarded – undo
4868 4868
             if ($table_obj instanceof EE_Primary_Table) {
4869 4869
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4870 4870
                     ? $table_obj->get_select_join_limit($limit)
4871
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4871
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4872 4872
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4873 4873
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4874 4874
                     ? $table_obj->get_select_join_limit_join($limit)
4875
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4875
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4876 4876
             }
4877 4877
         }
4878 4878
         return $SQL;
@@ -4943,7 +4943,7 @@  discard block
 block discarded – undo
4943 4943
         foreach ($this->field_settings() as $field_obj) {
4944 4944
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4945 4945
             /** @var $field_obj EE_Model_Field_Base */
4946
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4946
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4947 4947
         }
4948 4948
         return $data_types;
4949 4949
     }
@@ -4958,8 +4958,8 @@  discard block
 block discarded – undo
4958 4958
      */
4959 4959
     public function get_related_model_obj($model_name)
4960 4960
     {
4961
-        $model_classname = "EEM_" . $model_name;
4962
-        if (! class_exists($model_classname)) {
4961
+        $model_classname = "EEM_".$model_name;
4962
+        if ( ! class_exists($model_classname)) {
4963 4963
             throw new EE_Error(
4964 4964
                 sprintf(
4965 4965
                     esc_html__(
@@ -4971,7 +4971,7 @@  discard block
 block discarded – undo
4971 4971
                 )
4972 4972
             );
4973 4973
         }
4974
-        return call_user_func($model_classname . "::instance");
4974
+        return call_user_func($model_classname."::instance");
4975 4975
     }
4976 4976
 
4977 4977
 
@@ -4998,7 +4998,7 @@  discard block
 block discarded – undo
4998 4998
         $belongs_to_relations = [];
4999 4999
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
5000 5000
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
5001
-                $belongs_to_relations[ $model_name ] = $relation_obj;
5001
+                $belongs_to_relations[$model_name] = $relation_obj;
5002 5002
             }
5003 5003
         }
5004 5004
         return $belongs_to_relations;
@@ -5015,7 +5015,7 @@  discard block
 block discarded – undo
5015 5015
     public function related_settings_for($relation_name)
5016 5016
     {
5017 5017
         $relatedModels = $this->relation_settings();
5018
-        if (! array_key_exists($relation_name, $relatedModels)) {
5018
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
5019 5019
             throw new EE_Error(
5020 5020
                 sprintf(
5021 5021
                     esc_html__(
@@ -5028,7 +5028,7 @@  discard block
 block discarded – undo
5028 5028
                 )
5029 5029
             );
5030 5030
         }
5031
-        return $relatedModels[ $relation_name ];
5031
+        return $relatedModels[$relation_name];
5032 5032
     }
5033 5033
 
5034 5034
 
@@ -5044,7 +5044,7 @@  discard block
 block discarded – undo
5044 5044
     public function field_settings_for($fieldName, $include_db_only_fields = true)
5045 5045
     {
5046 5046
         $fieldSettings = $this->field_settings($include_db_only_fields);
5047
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5047
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
5048 5048
             throw new EE_Error(
5049 5049
                 sprintf(
5050 5050
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -5053,7 +5053,7 @@  discard block
 block discarded – undo
5053 5053
                 )
5054 5054
             );
5055 5055
         }
5056
-        return $fieldSettings[ $fieldName ];
5056
+        return $fieldSettings[$fieldName];
5057 5057
     }
5058 5058
 
5059 5059
 
@@ -5066,7 +5066,7 @@  discard block
 block discarded – undo
5066 5066
     public function has_field($fieldName)
5067 5067
     {
5068 5068
         $fieldSettings = $this->field_settings(true);
5069
-        if (isset($fieldSettings[ $fieldName ])) {
5069
+        if (isset($fieldSettings[$fieldName])) {
5070 5070
             return true;
5071 5071
         }
5072 5072
         return false;
@@ -5082,7 +5082,7 @@  discard block
 block discarded – undo
5082 5082
     public function has_relation($relation_name)
5083 5083
     {
5084 5084
         $relations = $this->relation_settings();
5085
-        if (isset($relations[ $relation_name ])) {
5085
+        if (isset($relations[$relation_name])) {
5086 5086
             return true;
5087 5087
         }
5088 5088
         return false;
@@ -5118,7 +5118,7 @@  discard block
 block discarded – undo
5118 5118
                     break;
5119 5119
                 }
5120 5120
             }
5121
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5121
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5122 5122
                 throw new EE_Error(
5123 5123
                     sprintf(
5124 5124
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5178,17 +5178,17 @@  discard block
 block discarded – undo
5178 5178
      */
5179 5179
     public function get_foreign_key_to($model_name)
5180 5180
     {
5181
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5181
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5182 5182
             foreach ($this->field_settings() as $field) {
5183 5183
                 if (
5184 5184
                     $field instanceof EE_Foreign_Key_Field_Base
5185 5185
                     && in_array($model_name, $field->get_model_names_pointed_to())
5186 5186
                 ) {
5187
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5187
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5188 5188
                     break;
5189 5189
                 }
5190 5190
             }
5191
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5191
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5192 5192
                 throw new EE_Error(
5193 5193
                     sprintf(
5194 5194
                         esc_html__(
@@ -5201,7 +5201,7 @@  discard block
 block discarded – undo
5201 5201
                 );
5202 5202
             }
5203 5203
         }
5204
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5204
+        return $this->_cache_foreign_key_to_fields[$model_name];
5205 5205
     }
5206 5206
 
5207 5207
 
@@ -5217,7 +5217,7 @@  discard block
 block discarded – undo
5217 5217
     {
5218 5218
         $table_alias_sans_model_relation_chain_prefix =
5219 5219
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5220
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5220
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5221 5221
     }
5222 5222
 
5223 5223
 
@@ -5235,7 +5235,7 @@  discard block
 block discarded – undo
5235 5235
                 $this->_cached_fields = [];
5236 5236
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5237 5237
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5238
+                        $this->_cached_fields[$field_name] = $field_obj;
5239 5239
                     }
5240 5240
                 }
5241 5241
             }
@@ -5246,8 +5246,8 @@  discard block
 block discarded – undo
5246 5246
             foreach ($this->_fields as $fields_corresponding_to_table) {
5247 5247
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248 5248
                     /** @var $field_obj EE_Model_Field_Base */
5249
-                    if (! $field_obj->is_db_only_field()) {
5250
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5249
+                    if ( ! $field_obj->is_db_only_field()) {
5250
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5251 5251
                     }
5252 5252
                 }
5253 5253
             }
@@ -5290,12 +5290,12 @@  discard block
 block discarded – undo
5290 5290
                     $primary_key_field->get_qualified_column(),
5291 5291
                     $primary_key_field->get_table_column()
5292 5292
                 );
5293
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5293
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5294 5294
                     continue;
5295 5295
                 }
5296 5296
             }
5297 5297
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5298
-            if (! $classInstance) {
5298
+            if ( ! $classInstance) {
5299 5299
                 throw new EE_Error(
5300 5300
                     sprintf(
5301 5301
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5310,7 +5310,7 @@  discard block
 block discarded – undo
5310 5310
             $key                      = $has_primary_key
5311 5311
                 ? $classInstance->ID()
5312 5312
                 : $count_if_model_has_no_primary_key++;
5313
-            $array_of_objects[ $key ] = $classInstance;
5313
+            $array_of_objects[$key] = $classInstance;
5314 5314
             // also, for all the relations of type BelongsTo, see if we can cache
5315 5315
             // those related models
5316 5316
             // (we could do this for other relations too, but if there are conditions
@@ -5354,9 +5354,9 @@  discard block
 block discarded – undo
5354 5354
         $results = [];
5355 5355
         if ($this->_custom_selections instanceof CustomSelects) {
5356 5356
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5357
-                if (isset($db_results_row[ $alias ])) {
5358
-                    $results[ $alias ] = $this->convertValueToDataType(
5359
-                        $db_results_row[ $alias ],
5357
+                if (isset($db_results_row[$alias])) {
5358
+                    $results[$alias] = $this->convertValueToDataType(
5359
+                        $db_results_row[$alias],
5360 5360
                         $this->_custom_selections->getDataTypeForAlias($alias)
5361 5361
                     );
5362 5362
                 }
@@ -5401,7 +5401,7 @@  discard block
 block discarded – undo
5401 5401
         $this_model_fields_and_values = [];
5402 5402
         // setup the row using default values;
5403 5403
         foreach ($this->field_settings() as $field_name => $field_obj) {
5404
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5404
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5405 5405
         }
5406 5406
         $className = $this->_get_class_name();
5407 5407
         return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
@@ -5417,20 +5417,20 @@  discard block
 block discarded – undo
5417 5417
      */
5418 5418
     public function instantiate_class_from_array_or_object($cols_n_values)
5419 5419
     {
5420
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5420
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5421 5421
             $cols_n_values = get_object_vars($cols_n_values);
5422 5422
         }
5423 5423
         $primary_key = null;
5424 5424
         // make sure the array only has keys that are fields/columns on this model
5425 5425
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5426
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5427
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5426
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5427
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5428 5428
         }
5429 5429
         $className = $this->_get_class_name();
5430 5430
         // check we actually found results that we can use to build our model object
5431 5431
         // if not, return null
5432 5432
         if ($this->has_primary_key_field()) {
5433
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5433
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5434 5434
                 return null;
5435 5435
             }
5436 5436
         } elseif ($this->unique_indexes()) {
@@ -5442,7 +5442,7 @@  discard block
 block discarded – undo
5442 5442
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5443 5443
         if ($primary_key) {
5444 5444
             $classInstance = $this->get_from_entity_map($primary_key);
5445
-            if (! $classInstance) {
5445
+            if ( ! $classInstance) {
5446 5446
                 $classInstance = EE_Registry::instance()
5447 5447
                                             ->load_class(
5448 5448
                                                 $className,
@@ -5473,7 +5473,7 @@  discard block
 block discarded – undo
5473 5473
      */
5474 5474
     public function get_from_entity_map($id)
5475 5475
     {
5476
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5476
+        return $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] ?? null;
5477 5477
     }
5478 5478
 
5479 5479
 
@@ -5496,7 +5496,7 @@  discard block
 block discarded – undo
5496 5496
     public function add_to_entity_map(EE_Base_Class $object)
5497 5497
     {
5498 5498
         $className = $this->_get_class_name();
5499
-        if (! $object instanceof $className) {
5499
+        if ( ! $object instanceof $className) {
5500 5500
             throw new EE_Error(
5501 5501
                 sprintf(
5502 5502
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5508,7 +5508,7 @@  discard block
 block discarded – undo
5508 5508
             );
5509 5509
         }
5510 5510
 
5511
-        if (! $object->ID()) {
5511
+        if ( ! $object->ID()) {
5512 5512
             throw new EE_Error(
5513 5513
                 sprintf(
5514 5514
                     esc_html__(
@@ -5524,7 +5524,7 @@  discard block
 block discarded – undo
5524 5524
         if ($classInstance) {
5525 5525
             return $classInstance;
5526 5526
         }
5527
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5527
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5528 5528
         return $object;
5529 5529
     }
5530 5530
 
@@ -5539,11 +5539,11 @@  discard block
 block discarded – undo
5539 5539
     public function clear_entity_map($id = null)
5540 5540
     {
5541 5541
         if (empty($id)) {
5542
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5542
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5543 5543
             return true;
5544 5544
         }
5545
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5546
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5545
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5546
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5547 5547
             return true;
5548 5548
         }
5549 5549
         return false;
@@ -5591,18 +5591,18 @@  discard block
 block discarded – undo
5591 5591
             // there is a primary key on this table and its not set. Use defaults for all its columns
5592 5592
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5593 5593
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5594
+                    if ( ! $field_obj->is_db_only_field()) {
5595 5595
                         // prepare field as if its coming from db
5596 5596
                         $prepared_value                            =
5597 5597
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5598
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5598
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5599 5599
                     }
5600 5600
                 }
5601 5601
             } else {
5602 5602
                 // the table's rows existed. Use their values
5603 5603
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
-                    if (! $field_obj->is_db_only_field()) {
5605
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5604
+                    if ( ! $field_obj->is_db_only_field()) {
5605
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5606 5606
                             $cols_n_values,
5607 5607
                             $field_obj->get_qualified_column(),
5608 5608
                             $field_obj->get_table_column()
@@ -5629,17 +5629,17 @@  discard block
 block discarded – undo
5629 5629
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5630 5630
         // does the field on the model relate to this column retrieved from the db?
5631 5631
         // or is it a db-only field? (not relating to the model)
5632
-        if (isset($cols_n_values[ $qualified_column ])) {
5633
-            $value = $cols_n_values[ $qualified_column ];
5634
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5635
-            $value = $cols_n_values[ $regular_column ];
5636
-        } elseif (! empty($this->foreign_key_aliases)) {
5632
+        if (isset($cols_n_values[$qualified_column])) {
5633
+            $value = $cols_n_values[$qualified_column];
5634
+        } elseif (isset($cols_n_values[$regular_column])) {
5635
+            $value = $cols_n_values[$regular_column];
5636
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5637 5637
             // no PK?  ok check if there is a foreign key alias set for this table
5638 5638
             // then check if that alias exists in the incoming data
5639 5639
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5640 5640
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5641
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5642
-                    $value = $cols_n_values[ $FK_alias ];
5641
+                if ($PK_column === $qualified_column && ! empty($cols_n_values[$FK_alias])) {
5642
+                    $value = $cols_n_values[$FK_alias];
5643 5643
                     [$pk_class] = explode('.', $PK_column);
5644 5644
                     $pk_model_name = "EEM_{$pk_class}";
5645 5645
                     /** @var EEM_Base $pk_model */
@@ -5683,7 +5683,7 @@  discard block
 block discarded – undo
5683 5683
                     $obj_in_map->clear_cache($relation_name, null, true);
5684 5684
                 }
5685 5685
             }
5686
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5686
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5687 5687
             return $obj_in_map;
5688 5688
         }
5689 5689
         return $this->get_one_by_ID($id);
@@ -5735,7 +5735,7 @@  discard block
 block discarded – undo
5735 5735
      */
5736 5736
     private function _get_class_name()
5737 5737
     {
5738
-        return "EE_" . $this->get_this_model_name();
5738
+        return "EE_".$this->get_this_model_name();
5739 5739
     }
5740 5740
 
5741 5741
 
@@ -5789,7 +5789,7 @@  discard block
 block discarded – undo
5789 5789
     {
5790 5790
         $className = get_class($this);
5791 5791
         $tagName   = "FHEE__{$className}__{$methodName}";
5792
-        if (! has_filter($tagName)) {
5792
+        if ( ! has_filter($tagName)) {
5793 5793
             throw new EE_Error(
5794 5794
                 sprintf(
5795 5795
                     esc_html__(
@@ -5960,7 +5960,7 @@  discard block
 block discarded – undo
5960 5960
         $unique_indexes = [];
5961 5961
         foreach ($this->_indexes as $name => $index) {
5962 5962
             if ($index instanceof EE_Unique_Index) {
5963
-                $unique_indexes [ $name ] = $index;
5963
+                $unique_indexes [$name] = $index;
5964 5964
             }
5965 5965
         }
5966 5966
         return $unique_indexes;
@@ -6024,7 +6024,7 @@  discard block
 block discarded – undo
6024 6024
         $key_vals_in_combined_pk = [];
6025 6025
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6026 6026
         foreach ($key_fields as $key_field_name => $field_obj) {
6027
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6027
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
6028 6028
                 return null;
6029 6029
             }
6030 6030
         }
@@ -6044,7 +6044,7 @@  discard block
 block discarded – undo
6044 6044
     {
6045 6045
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6046 6046
         foreach ($keys_it_should_have as $key) {
6047
-            if (! isset($key_vals[ $key ])) {
6047
+            if ( ! isset($key_vals[$key])) {
6048 6048
                 return false;
6049 6049
             }
6050 6050
         }
@@ -6083,8 +6083,8 @@  discard block
 block discarded – undo
6083 6083
         }
6084 6084
         // even copies obviously won't have the same ID, so remove the primary key
6085 6085
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
6086
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6087
-            unset($attributes_array[ $this->primary_key_name() ]);
6086
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
6087
+            unset($attributes_array[$this->primary_key_name()]);
6088 6088
         }
6089 6089
         if (isset($query_params[0])) {
6090 6090
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -6106,7 +6106,7 @@  discard block
 block discarded – undo
6106 6106
      */
6107 6107
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6108 6108
     {
6109
-        if (! is_array($query_params)) {
6109
+        if ( ! is_array($query_params)) {
6110 6110
             EE_Error::doing_it_wrong(
6111 6111
                 'EEM_Base::get_one_copy',
6112 6112
                 sprintf(
@@ -6155,7 +6155,7 @@  discard block
 block discarded – undo
6155 6155
      */
6156 6156
     private function _prepare_operator_for_sql($operator_supplied)
6157 6157
     {
6158
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6158
+        $sql_operator = $this->_valid_operators[$operator_supplied] ?? null;
6159 6159
         if ($sql_operator) {
6160 6160
             return $sql_operator;
6161 6161
         }
@@ -6253,7 +6253,7 @@  discard block
 block discarded – undo
6253 6253
         $objs  = $this->get_all($query_params);
6254 6254
         $names = [];
6255 6255
         foreach ($objs as $obj) {
6256
-            $names[ $obj->ID() ] = $obj->name();
6256
+            $names[$obj->ID()] = $obj->name();
6257 6257
         }
6258 6258
         return $names;
6259 6259
     }
@@ -6274,7 +6274,7 @@  discard block
 block discarded – undo
6274 6274
      */
6275 6275
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6276 6276
     {
6277
-        if (! $this->has_primary_key_field()) {
6277
+        if ( ! $this->has_primary_key_field()) {
6278 6278
             if (defined('WP_DEBUG') && WP_DEBUG) {
6279 6279
                 EE_Error::add_error(
6280 6280
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6287,7 +6287,7 @@  discard block
 block discarded – undo
6287 6287
         $IDs = [];
6288 6288
         foreach ($model_objects as $model_object) {
6289 6289
             $id = $model_object->ID();
6290
-            if (! $id) {
6290
+            if ( ! $id) {
6291 6291
                 if ($filter_out_empty_ids) {
6292 6292
                     continue;
6293 6293
                 }
@@ -6336,22 +6336,22 @@  discard block
 block discarded – undo
6336 6336
         EEM_Base::verify_is_valid_cap_context($context);
6337 6337
         // check if we ought to run the restriction generator first
6338 6338
         if (
6339
-            isset($this->_cap_restriction_generators[ $context ])
6340
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6341
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6339
+            isset($this->_cap_restriction_generators[$context])
6340
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6341
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6342 6342
         ) {
6343
-            $this->_cap_restrictions[ $context ] = array_merge(
6344
-                $this->_cap_restrictions[ $context ],
6345
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6343
+            $this->_cap_restrictions[$context] = array_merge(
6344
+                $this->_cap_restrictions[$context],
6345
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6346 6346
             );
6347 6347
         }
6348 6348
         // and make sure we've finalized the construction of each restriction
6349
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6349
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6350 6350
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6351 6351
                 $where_conditions_obj->_finalize_construct($this);
6352 6352
             }
6353 6353
         }
6354
-        return $this->_cap_restrictions[ $context ];
6354
+        return $this->_cap_restrictions[$context];
6355 6355
     }
6356 6356
 
6357 6357
 
@@ -6381,9 +6381,9 @@  discard block
 block discarded – undo
6381 6381
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6382 6382
             if (
6383 6383
                 ! EE_Capabilities::instance()
6384
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6384
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6385 6385
             ) {
6386
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6386
+                $missing_caps[$cap] = $restriction_if_no_cap;
6387 6387
             }
6388 6388
         }
6389 6389
         return $missing_caps;
@@ -6416,8 +6416,8 @@  discard block
 block discarded – undo
6416 6416
     public function cap_action_for_context($context)
6417 6417
     {
6418 6418
         $mapping = $this->cap_contexts_to_cap_action_map();
6419
-        if (isset($mapping[ $context ])) {
6420
-            return $mapping[ $context ];
6419
+        if (isset($mapping[$context])) {
6420
+            return $mapping[$context];
6421 6421
         }
6422 6422
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6423 6423
             return $action;
@@ -6538,7 +6538,7 @@  discard block
 block discarded – undo
6538 6538
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6539 6539
             if (
6540 6540
                 $query_param_key === $logic_query_param_key
6541
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6541
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6542 6542
             ) {
6543 6543
                 return true;
6544 6544
             }
@@ -6596,7 +6596,7 @@  discard block
 block discarded – undo
6596 6596
         if ($password_field instanceof EE_Password_Field) {
6597 6597
             $field_names = $password_field->protectedFields();
6598 6598
             foreach ($field_names as $field_name) {
6599
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6599
+                $fields[$field_name] = $this->field_settings_for($field_name);
6600 6600
             }
6601 6601
         }
6602 6602
         return $fields;
@@ -6622,7 +6622,7 @@  discard block
 block discarded – undo
6622 6622
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6623 6623
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6624 6624
         }
6625
-        if (! is_array($model_obj_or_fields_n_values)) {
6625
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6626 6626
             throw new UnexpectedEntityException(
6627 6627
                 $model_obj_or_fields_n_values,
6628 6628
                 'EE_Base_Class',
@@ -6704,9 +6704,9 @@  discard block
 block discarded – undo
6704 6704
         }
6705 6705
         return (
6706 6706
                $this->model_chain_to_password
6707
-                   ? $this->model_chain_to_password . '.'
6707
+                   ? $this->model_chain_to_password.'.'
6708 6708
                    : ''
6709
-               ) . $password_field_name;
6709
+               ).$password_field_name;
6710 6710
     }
6711 6711
 
6712 6712
 
Please login to merge, or discard this patch.
core/templates/notifications/persistent_admin_notice.template.php 2 patches
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
  */
13 13
 
14 14
 if (strpos($persistent_admin_notice_message, '<p>') === false) {
15
-    $persistent_admin_notice_message = '<p>' . $persistent_admin_notice_message . '</p>';
15
+	$persistent_admin_notice_message = '<p>' . $persistent_admin_notice_message . '</p>';
16 16
 }
17 17
 
18 18
 $notice_class = "espresso-notices notice ee-nag-notice ee-status-outline";
@@ -21,31 +21,31 @@  discard block
 block discarded – undo
21 21
 $notice_class .= " $persistent_admin_notice_css";
22 22
 
23 23
 switch($persistent_admin_notice_type) {
24
-    case 'success':
25
-        $dashicon = 'dashicons dashicons-yes-alt dashicons--bigger';
26
-        break;
27
-    case 'attention':
28
-    case 'warning':
29
-        $dashicon = 'dashicons dashicons-warning dashicons--bigger';
30
-        break;
31
-    case 'error':
32
-        $dashicon = 'dashicons dashicons-dismiss dashicons--bigger';
33
-        break;
34
-    case 'info':
35
-    default:
36
-        $dashicon = 'dashicons dashicons-info dashicons--bigger';
37
-        break;
24
+	case 'success':
25
+		$dashicon = 'dashicons dashicons-yes-alt dashicons--bigger';
26
+		break;
27
+	case 'attention':
28
+	case 'warning':
29
+		$dashicon = 'dashicons dashicons-warning dashicons--bigger';
30
+		break;
31
+	case 'error':
32
+		$dashicon = 'dashicons dashicons-dismiss dashicons--bigger';
33
+		break;
34
+	case 'info':
35
+	default:
36
+		$dashicon = 'dashicons dashicons-info dashicons--bigger';
37
+		break;
38 38
 }
39 39
 
40 40
 $button_class = 'button button--caution button--outline button--small';
41 41
 $button_class .= ' dismiss-ee-nag-notice-btn dismiss-ee-nag-notice hide-if-no-js';
42 42
 
43 43
 $dismiss_button = $is_dismissible
44
-    ? '
44
+	? '
45 45
     <button class="' . esc_attr($button_class) . '" data-target="' . esc_attr($persistent_admin_notice_name) . '">
46 46
         <span class="dashicons dashicons-dismiss"></span>' . esc_html__('Dismiss', 'event_espresso') . '
47 47
     </button>'
48
-    : '';
48
+	: '';
49 49
 
50 50
 ?>
51 51
 <div id="<?php echo esc_attr($persistent_admin_notice_name); ?>" class="<?php esc_attr_e($notice_class);?>">
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
  */
13 13
 
14 14
 if (strpos($persistent_admin_notice_message, '<p>') === false) {
15
-    $persistent_admin_notice_message = '<p>' . $persistent_admin_notice_message . '</p>';
15
+    $persistent_admin_notice_message = '<p>'.$persistent_admin_notice_message.'</p>';
16 16
 }
17 17
 
18 18
 $notice_class = "espresso-notices notice ee-nag-notice ee-status-outline";
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 $notice_class .= " ee-status-bg--$persistent_admin_notice_type";
21 21
 $notice_class .= " $persistent_admin_notice_css";
22 22
 
23
-switch($persistent_admin_notice_type) {
23
+switch ($persistent_admin_notice_type) {
24 24
     case 'success':
25 25
         $dashicon = 'dashicons dashicons-yes-alt dashicons--bigger';
26 26
         break;
@@ -42,13 +42,13 @@  discard block
 block discarded – undo
42 42
 
43 43
 $dismiss_button = $is_dismissible
44 44
     ? '
45
-    <button class="' . esc_attr($button_class) . '" data-target="' . esc_attr($persistent_admin_notice_name) . '">
46
-        <span class="dashicons dashicons-dismiss"></span>' . esc_html__('Dismiss', 'event_espresso') . '
45
+    <button class="' . esc_attr($button_class).'" data-target="'.esc_attr($persistent_admin_notice_name).'">
46
+        <span class="dashicons dashicons-dismiss"></span>' . esc_html__('Dismiss', 'event_espresso').'
47 47
     </button>'
48 48
     : '';
49 49
 
50 50
 ?>
51
-<div id="<?php echo esc_attr($persistent_admin_notice_name); ?>" class="<?php esc_attr_e($notice_class);?>">
51
+<div id="<?php echo esc_attr($persistent_admin_notice_name); ?>" class="<?php esc_attr_e($notice_class); ?>">
52 52
     <?php echo wp_kses($dismiss_button, AllowedTags::getWithFullTags()); ?>
53 53
     <div class="ee-nag-notice__body">
54 54
         <div class="ee-nag-notice__icons">
Please login to merge, or discard this patch.
core/domain/services/cron/jobs/GarbageCollection.php 2 patches
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -20,78 +20,78 @@
 block discarded – undo
20 20
 
21 21
 class GarbageCollection extends CronJob
22 22
 {
23
-    public function setHooks(): void
24
-    {
25
-        add_action(
26
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
27
-            [$this, 'cleanUpJunkTransactions']
28
-        );
29
-        add_action(
30
-            'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs',
31
-            [$this, 'cleanUpOldGatewayLogs']
32
-        );
33
-        add_action(
34
-            'AHEE__EE_Cron_Tasks__clean_up_temp_directories',
35
-            [$this, 'cleanUpTempDirectories']
36
-        );
37
-    }
23
+	public function setHooks(): void
24
+	{
25
+		add_action(
26
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
27
+			[$this, 'cleanUpJunkTransactions']
28
+		);
29
+		add_action(
30
+			'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs',
31
+			[$this, 'cleanUpOldGatewayLogs']
32
+		);
33
+		add_action(
34
+			'AHEE__EE_Cron_Tasks__clean_up_temp_directories',
35
+			[$this, 'cleanUpTempDirectories']
36
+		);
37
+	}
38 38
 
39 39
 
40
-    /**
41
-     * callback for 'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'
42
-     * which is set up during activation to run on an hourly cron
43
-     *
44
-     * @throws EE_Error
45
-     * @throws DomainException
46
-     * @throws ReflectionException
47
-     */
48
-    public function cleanUpJunkTransactions(): void
49
-    {
50
-        if (DbStatus::isOnline()) {
51
-            EED_Ticket_Sales_Monitor::reset_reservation_counts();
52
-            EEM_Transaction::instance()->delete_junk_transactions();
53
-            EEM_Registration::instance()->delete_registrations_with_no_transaction();
54
-            EEM_Line_Item::instance()->delete_line_items_with_no_transaction();
55
-        }
56
-    }
40
+	/**
41
+	 * callback for 'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'
42
+	 * which is set up during activation to run on an hourly cron
43
+	 *
44
+	 * @throws EE_Error
45
+	 * @throws DomainException
46
+	 * @throws ReflectionException
47
+	 */
48
+	public function cleanUpJunkTransactions(): void
49
+	{
50
+		if (DbStatus::isOnline()) {
51
+			EED_Ticket_Sales_Monitor::reset_reservation_counts();
52
+			EEM_Transaction::instance()->delete_junk_transactions();
53
+			EEM_Registration::instance()->delete_registrations_with_no_transaction();
54
+			EEM_Line_Item::instance()->delete_line_items_with_no_transaction();
55
+		}
56
+	}
57 57
 
58 58
 
59
-    /**
60
-     * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
61
-     *
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     * @throws Exception
65
-     */
66
-    public function cleanUpOldGatewayLogs(): void
67
-    {
68
-        if (DbStatus::isOnline()) {
69
-            $reg_config               = $this->loader->getShared(EE_Registration_Config::class);
70
-            $time_diff_for_comparison = apply_filters(
71
-                'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
72
-                '-' . $reg_config->gateway_log_lifespan
73
-            );
74
-            EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
75
-        }
76
-    }
59
+	/**
60
+	 * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
61
+	 *
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 * @throws Exception
65
+	 */
66
+	public function cleanUpOldGatewayLogs(): void
67
+	{
68
+		if (DbStatus::isOnline()) {
69
+			$reg_config               = $this->loader->getShared(EE_Registration_Config::class);
70
+			$time_diff_for_comparison = apply_filters(
71
+				'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
72
+				'-' . $reg_config->gateway_log_lifespan
73
+			);
74
+			EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
75
+		}
76
+	}
77 77
 
78 78
 
79
-    /**
80
-     * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
81
-     *
82
-     * @throws EE_Error
83
-     * @throws ReflectionException
84
-     * @throws Exception
85
-     */
86
-    public function cleanUpTempDirectories(): void
87
-    {
88
-        if (DbStatus::isOnline()) {
89
-            $base_folder = apply_filters(
90
-                'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_folder',
91
-                EVENT_ESPRESSO_UPLOAD_DIR
92
-            );
93
-            $temp_batch_dir = $base_folder . JobHandlerFile::temp_folder_name;
94
-            EEH_File::delete($temp_batch_dir);
95
-        }
96
-    }
79
+	/**
80
+	 * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
81
+	 *
82
+	 * @throws EE_Error
83
+	 * @throws ReflectionException
84
+	 * @throws Exception
85
+	 */
86
+	public function cleanUpTempDirectories(): void
87
+	{
88
+		if (DbStatus::isOnline()) {
89
+			$base_folder = apply_filters(
90
+				'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_folder',
91
+				EVENT_ESPRESSO_UPLOAD_DIR
92
+			);
93
+			$temp_batch_dir = $base_folder . JobHandlerFile::temp_folder_name;
94
+			EEH_File::delete($temp_batch_dir);
95
+		}
96
+	}
97 97
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
             $reg_config               = $this->loader->getShared(EE_Registration_Config::class);
70 70
             $time_diff_for_comparison = apply_filters(
71 71
                 'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
72
-                '-' . $reg_config->gateway_log_lifespan
72
+                '-'.$reg_config->gateway_log_lifespan
73 73
             );
74 74
             EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
75 75
         }
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
                 'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_folder',
91 91
                 EVENT_ESPRESSO_UPLOAD_DIR
92 92
             );
93
-            $temp_batch_dir = $base_folder . JobHandlerFile::temp_folder_name;
93
+            $temp_batch_dir = $base_folder.JobHandlerFile::temp_folder_name;
94 94
             EEH_File::delete($temp_batch_dir);
95 95
         }
96 96
     }
Please login to merge, or discard this patch.
core/domain/services/graphql/Utilities.php 1 patch
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -12,99 +12,99 @@
 block discarded – undo
12 12
  */
13 13
 class Utilities
14 14
 {
15
-    /**
16
-     * This sets up the "allowed" args, and translates the GraphQL-friendly keys to model
17
-     * friendly keys.
18
-     *
19
-     * @param array $where_args
20
-     * @param array $arg_mapping        Array where keys are GQL field names and values are EE modal field names
21
-     * @param array $id_fields          The fields to convert from global IDs to DB IDs.
22
-     * @param array $options            Additional parameters for modifying args: [
23
-     *                                  'include_all_args' => bool, // will return ALL args in $where_args if true
24
-     *                                  'use_IN_operator' => bool, // arrays of IDs will use SQL IN clause if true
25
-     *                                  ]
26
-     * @return array
27
-     */
28
-    public function sanitizeWhereArgs(
29
-        array $where_args,
30
-        array $arg_mapping,
31
-        array $id_fields,
32
-        array $options = []
33
-    ): array {
34
-        // if "include_all_args" is true, then the incoming $where_args array
35
-        // will be copied to the outgoing $where_params prior to sanitizing the fields.
36
-        // so ALL elements in the $where_args array will be present in the $where_params array
37
-        $include_all_args = isset($options['include_all_args'])
38
-            ? filter_var($options['include_all_args'], FILTER_VALIDATE_BOOLEAN)
39
-            : false;
40
-        // if "use_IN_operator" is true, then any ID args found in the $id_fields array
41
-        // will have their values converted to use an SQL "IN" clause format
42
-        // if the value returned from Relay::fromGlobalId() is an array of IDs
43
-        $use_IN_operator = isset($options['use_IN_operator'])
44
-                           && filter_var($options['use_IN_operator'], FILTER_VALIDATE_BOOLEAN);
45
-        $where_params    = $include_all_args ? $where_args : [];
46
-        foreach ($where_args as $arg => $value) {
47
-            if (! array_key_exists($arg, $arg_mapping)) {
48
-                continue;
49
-            }
50
-            if (is_array($value) && ! empty($value)) {
51
-                $value = array_map(
52
-                    static function ($value) {
53
-                        if (is_string($value)) {
54
-                            $value = sanitize_text_field($value);
55
-                        }
56
-                        return $value;
57
-                    },
58
-                    $value
59
-                );
60
-            } elseif (is_string($value)) {
61
-                $value = sanitize_text_field($value);
62
-            }
63
-            if (in_array($arg, $id_fields, true)) {
64
-                $ID = $this->convertFromGlobalId($value);
65
-                // Use the proper operator.
66
-                $value = $use_IN_operator && is_array($ID) ? ['IN', $ID] : $ID;
67
-            }
68
-            $where_params[ $arg_mapping[ $arg ] ] = $value;
69
-        }
70
-        return $where_params;
71
-    }
15
+	/**
16
+	 * This sets up the "allowed" args, and translates the GraphQL-friendly keys to model
17
+	 * friendly keys.
18
+	 *
19
+	 * @param array $where_args
20
+	 * @param array $arg_mapping        Array where keys are GQL field names and values are EE modal field names
21
+	 * @param array $id_fields          The fields to convert from global IDs to DB IDs.
22
+	 * @param array $options            Additional parameters for modifying args: [
23
+	 *                                  'include_all_args' => bool, // will return ALL args in $where_args if true
24
+	 *                                  'use_IN_operator' => bool, // arrays of IDs will use SQL IN clause if true
25
+	 *                                  ]
26
+	 * @return array
27
+	 */
28
+	public function sanitizeWhereArgs(
29
+		array $where_args,
30
+		array $arg_mapping,
31
+		array $id_fields,
32
+		array $options = []
33
+	): array {
34
+		// if "include_all_args" is true, then the incoming $where_args array
35
+		// will be copied to the outgoing $where_params prior to sanitizing the fields.
36
+		// so ALL elements in the $where_args array will be present in the $where_params array
37
+		$include_all_args = isset($options['include_all_args'])
38
+			? filter_var($options['include_all_args'], FILTER_VALIDATE_BOOLEAN)
39
+			: false;
40
+		// if "use_IN_operator" is true, then any ID args found in the $id_fields array
41
+		// will have their values converted to use an SQL "IN" clause format
42
+		// if the value returned from Relay::fromGlobalId() is an array of IDs
43
+		$use_IN_operator = isset($options['use_IN_operator'])
44
+						   && filter_var($options['use_IN_operator'], FILTER_VALIDATE_BOOLEAN);
45
+		$where_params    = $include_all_args ? $where_args : [];
46
+		foreach ($where_args as $arg => $value) {
47
+			if (! array_key_exists($arg, $arg_mapping)) {
48
+				continue;
49
+			}
50
+			if (is_array($value) && ! empty($value)) {
51
+				$value = array_map(
52
+					static function ($value) {
53
+						if (is_string($value)) {
54
+							$value = sanitize_text_field($value);
55
+						}
56
+						return $value;
57
+					},
58
+					$value
59
+				);
60
+			} elseif (is_string($value)) {
61
+				$value = sanitize_text_field($value);
62
+			}
63
+			if (in_array($arg, $id_fields, true)) {
64
+				$ID = $this->convertFromGlobalId($value);
65
+				// Use the proper operator.
66
+				$value = $use_IN_operator && is_array($ID) ? ['IN', $ID] : $ID;
67
+			}
68
+			$where_params[ $arg_mapping[ $arg ] ] = $value;
69
+		}
70
+		return $where_params;
71
+	}
72 72
 
73 73
 
74
-    /**
75
-     * Converts global ID to DB ID.
76
-     *
77
-     * @param string|string[] $ID
78
-     * @return mixed
79
-     */
80
-    public function convertFromGlobalId($ID)
81
-    {
82
-        if (is_array($ID)) {
83
-            return array_map([$this, 'convertFromGlobalId'], $ID);
84
-        }
85
-        $parts = Relay::fromGlobalId($ID);
86
-        return ! empty($parts['id']) ? $parts['id'] : null;
87
-    }
74
+	/**
75
+	 * Converts global ID to DB ID.
76
+	 *
77
+	 * @param string|string[] $ID
78
+	 * @return mixed
79
+	 */
80
+	public function convertFromGlobalId($ID)
81
+	{
82
+		if (is_array($ID)) {
83
+			return array_map([$this, 'convertFromGlobalId'], $ID);
84
+		}
85
+		$parts = Relay::fromGlobalId($ID);
86
+		return ! empty($parts['id']) ? $parts['id'] : null;
87
+	}
88 88
 
89 89
 
90
-    /**
91
-     * Convert the DB ID into GID
92
-     *
93
-     * @param string    $type
94
-     * @param int|int[] $ID
95
-     * @return mixed
96
-     */
97
-    public function convertToGlobalId(string $type, $ID)
98
-    {
99
-        $convertToGlobalId = [$this, 'convertToGlobalId'];
100
-        if (is_array($ID)) {
101
-            return array_map(
102
-                static function ($id) use ($convertToGlobalId, $type) {
103
-                    return $convertToGlobalId($type, $id);
104
-                },
105
-                $ID
106
-            );
107
-        }
108
-        return Relay::toGlobalId($type, $ID);
109
-    }
90
+	/**
91
+	 * Convert the DB ID into GID
92
+	 *
93
+	 * @param string    $type
94
+	 * @param int|int[] $ID
95
+	 * @return mixed
96
+	 */
97
+	public function convertToGlobalId(string $type, $ID)
98
+	{
99
+		$convertToGlobalId = [$this, 'convertToGlobalId'];
100
+		if (is_array($ID)) {
101
+			return array_map(
102
+				static function ($id) use ($convertToGlobalId, $type) {
103
+					return $convertToGlobalId($type, $id);
104
+				},
105
+				$ID
106
+			);
107
+		}
108
+		return Relay::toGlobalId($type, $ID);
109
+	}
110 110
 }
Please login to merge, or discard this patch.