Completed
Branch BUG/fatal-with-paypal-debug-li... (3a6198)
by
unknown
17:39 queued 08:49
created
core/domain/services/assets/CoreAssetManager.php 2 patches
Indentation   +438 added lines, -438 removed lines patch added patch discarded remove patch
@@ -32,461 +32,461 @@
 block discarded – undo
32 32
 class CoreAssetManager extends AssetManager
33 33
 {
34 34
 
35
-    // WordPress core / Third party JS asset handles
36
-    const JS_HANDLE_JQUERY = 'jquery';
35
+	// WordPress core / Third party JS asset handles
36
+	const JS_HANDLE_JQUERY = 'jquery';
37 37
 
38
-    const JS_HANDLE_JQUERY_VALIDATE = 'jquery-validate';
38
+	const JS_HANDLE_JQUERY_VALIDATE = 'jquery-validate';
39 39
 
40
-    const JS_HANDLE_JQUERY_VALIDATE_EXTRA = 'jquery-validate-extra-methods';
40
+	const JS_HANDLE_JQUERY_VALIDATE_EXTRA = 'jquery-validate-extra-methods';
41 41
 
42
-    const JS_HANDLE_UNDERSCORE = 'underscore';
42
+	const JS_HANDLE_UNDERSCORE = 'underscore';
43 43
 
44
-    const JS_HANDLE_ACCOUNTING_CORE = 'ee-accounting-core';
44
+	const JS_HANDLE_ACCOUNTING_CORE = 'ee-accounting-core';
45 45
 
46
-    /**
47
-     * @since 4.9.71.p
48
-     */
49
-    const JS_HANDLE_REACT = 'react';
46
+	/**
47
+	 * @since 4.9.71.p
48
+	 */
49
+	const JS_HANDLE_REACT = 'react';
50 50
 
51
-    /**
52
-     * @since 4.9.71.p
53
-     */
54
-    const JS_HANDLE_REACT_DOM = 'react-dom';
51
+	/**
52
+	 * @since 4.9.71.p
53
+	 */
54
+	const JS_HANDLE_REACT_DOM = 'react-dom';
55 55
 
56
-    /**
57
-     * @since 4.9.71.p
58
-     */
59
-    const JS_HANDLE_LODASH = 'lodash';
56
+	/**
57
+	 * @since 4.9.71.p
58
+	 */
59
+	const JS_HANDLE_LODASH = 'lodash';
60 60
 
61
-    const JS_HANDLE_JS_CORE = 'eejs-core';
61
+	const JS_HANDLE_JS_CORE = 'eejs-core';
62 62
 
63
-    const JS_HANDLE_VENDOR = 'eventespresso-vendor';
63
+	const JS_HANDLE_VENDOR = 'eventespresso-vendor';
64 64
 
65
-    const JS_HANDLE_DATA_STORES = 'eventespresso-data-stores';
65
+	const JS_HANDLE_DATA_STORES = 'eventespresso-data-stores';
66 66
 
67
-    const JS_HANDLE_HELPERS = 'eventespresso-helpers';
67
+	const JS_HANDLE_HELPERS = 'eventespresso-helpers';
68 68
 
69
-    const JS_HANDLE_MODEL = 'eventespresso-model';
69
+	const JS_HANDLE_MODEL = 'eventespresso-model';
70 70
 
71
-    const JS_HANDLE_VALUE_OBJECTS = 'eventespresso-value-objects';
71
+	const JS_HANDLE_VALUE_OBJECTS = 'eventespresso-value-objects';
72 72
 
73
-    const JS_HANDLE_HOCS = 'eventespresso-hocs';
73
+	const JS_HANDLE_HOCS = 'eventespresso-hocs';
74 74
 
75
-    const JS_HANDLE_COMPONENTS = 'eventespresso-components';
75
+	const JS_HANDLE_COMPONENTS = 'eventespresso-components';
76 76
 
77
-    const JS_HANDLE_EDITOR_HOCS = 'eventespresso-editor-hocs';
78
-
79
-    const JS_HANDLE_VALIDATORS = 'eventespresso-validators';
77
+	const JS_HANDLE_EDITOR_HOCS = 'eventespresso-editor-hocs';
78
+
79
+	const JS_HANDLE_VALIDATORS = 'eventespresso-validators';
80 80
 
81
-    const JS_HANDLE_CORE = 'espresso_core';
81
+	const JS_HANDLE_CORE = 'espresso_core';
82 82
 
83
-    const JS_HANDLE_I18N = 'eei18n';
83
+	const JS_HANDLE_I18N = 'eei18n';
84 84
 
85
-    const JS_HANDLE_ACCOUNTING = 'ee-accounting';
86
-
87
-    const JS_HANDLE_WP_PLUGINS_PAGE = 'ee-wp-plugins-page';
88
-
89
-    // EE CSS assets handles
90
-    const CSS_HANDLE_DEFAULT = 'espresso_default';
91
-
92
-    const CSS_HANDLE_CUSTOM = 'espresso_custom_css';
93
-
94
-    const CSS_HANDLE_COMPONENTS = 'eventespresso-components';
95
-
96
-    const CSS_HANDLE_CORE_CSS_DEFAULT = 'eventespresso-core-css-default';
97
-
98
-    /**
99
-     * @var EE_Currency_Config $currency_config
100
-     */
101
-    protected $currency_config;
102
-
103
-    /**
104
-     * @var EE_Template_Config $template_config
105
-     */
106
-    protected $template_config;
107
-
108
-
109
-    /**
110
-     * CoreAssetRegister constructor.
111
-     *
112
-     * @param AssetCollection    $assets
113
-     * @param EE_Currency_Config $currency_config
114
-     * @param EE_Template_Config $template_config
115
-     * @param DomainInterface    $domain
116
-     * @param Registry           $registry
117
-     */
118
-    public function __construct(
119
-        AssetCollection $assets,
120
-        EE_Currency_Config $currency_config,
121
-        EE_Template_Config $template_config,
122
-        DomainInterface $domain,
123
-        Registry $registry
124
-    ) {
125
-        $this->currency_config = $currency_config;
126
-        $this->template_config = $template_config;
127
-        parent::__construct($domain, $assets, $registry);
128
-    }
129
-
130
-
131
-    /**
132
-     * @since 4.9.62.p
133
-     * @throws DomainException
134
-     * @throws DuplicateCollectionIdentifierException
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidDataTypeException
137
-     * @throws InvalidEntityException
138
-     * @throws InvalidInterfaceException
139
-     */
140
-    public function addAssets()
141
-    {
142
-        $this->addJavascriptFiles();
143
-        $this->addStylesheetFiles();
144
-    }
145
-
146
-
147
-    /**
148
-     * @since 4.9.62.p
149
-     * @throws DomainException
150
-     * @throws DuplicateCollectionIdentifierException
151
-     * @throws InvalidArgumentException
152
-     * @throws InvalidDataTypeException
153
-     * @throws InvalidEntityException
154
-     * @throws InvalidInterfaceException
155
-     */
156
-    public function addJavascriptFiles()
157
-    {
158
-        $this->loadCoreJs();
159
-        $this->loadJqueryValidate();
160
-        $this->loadAccountingJs();
161
-        add_action(
162
-            'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
163
-            array($this, 'loadQtipJs')
164
-        );
165
-        $this->registerAdminAssets();
166
-    }
167
-
168
-
169
-    /**
170
-     * @throws DuplicateCollectionIdentifierException
171
-     * @throws InvalidDataTypeException
172
-     * @throws InvalidEntityException
173
-     * @throws DomainException
174
-     * @since 4.9.62.p
175
-     */
176
-    public function addStylesheetFiles()
177
-    {
178
-        $this->loadCoreCss();
179
-    }
180
-
181
-
182
-    /**
183
-     * core default javascript
184
-     *
185
-     * @since 4.9.62.p
186
-     * @throws DomainException
187
-     * @throws DuplicateCollectionIdentifierException
188
-     * @throws InvalidArgumentException
189
-     * @throws InvalidDataTypeException
190
-     * @throws InvalidEntityException
191
-     * @throws InvalidInterfaceException
192
-     */
193
-    private function loadCoreJs()
194
-    {
195
-        // conditionally load third-party libraries that WP core MIGHT have.
196
-        $this->registerWpAssets();
197
-
198
-        $this->addJs(self::JS_HANDLE_JS_CORE)->setHasInlineData();
199
-        $this->addJs(self::JS_HANDLE_VENDOR);
200
-        $this->addJs(self::JS_HANDLE_VALIDATORS)->setRequiresTranslation();
201
-        $this->addJs(self::JS_HANDLE_HELPERS)->setRequiresTranslation();
202
-        $this->addJs(self::JS_HANDLE_MODEL)->setRequiresTranslation();
203
-        $this->addJs(self::JS_HANDLE_VALUE_OBJECTS)->setRequiresTranslation();
204
-        $this->addJs(self::JS_HANDLE_DATA_STORES)->setRequiresTranslation()->setInlineDataCallback(
205
-            static function () {
206
-                wp_add_inline_script(
207
-                    CoreAssetManager::JS_HANDLE_DATA_STORES,
208
-                    is_admin()
209
-                        ? 'wp.apiFetch.use( eejs.middleWares.apiFetch.capsMiddleware( eejs.middleWares.apiFetch.CONTEXT_CAPS_EDIT ) )'
210
-                        : 'wp.apiFetch.use( eejs.middleWares.apiFetch.capsMiddleware )'
211
-                );
212
-            }
213
-        );
214
-        $this->addJs(self::JS_HANDLE_HOCS, [self::JS_HANDLE_DATA_STORES])->setRequiresTranslation();
215
-        $this->addJs(self::JS_HANDLE_COMPONENTS, [self::JS_HANDLE_DATA_STORES])->setRequiresTranslation();
216
-        $this->addJs(self::JS_HANDLE_EDITOR_HOCS)->setRequiresTranslation();
217
-
218
-        $this->registry->addData('eejs_api_nonce', wp_create_nonce('wp_rest'));
219
-        $this->registry->addData(
220
-            'paths',
221
-            array(
222
-                'base_rest_route' => rest_url(),
223
-                'rest_route' => rest_url('ee/v4.8.36/'),
224
-                'collection_endpoints' => EED_Core_Rest_Api::getCollectionRoutesIndexedByModelName(),
225
-                'primary_keys' => EED_Core_Rest_Api::getPrimaryKeyNamesIndexedByModelName(),
226
-                'site_url' => site_url('/'),
227
-                'admin_url' => admin_url('/'),
228
-            )
229
-        );
230
-        // Event Espresso brand name
231
-        $this->registry->addData('brandName', Domain::brandName());
232
-        /** site formatting values **/
233
-        $this->registry->addData(
234
-            'site_formats',
235
-            array(
236
-                'date_formats' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats()
237
-            )
238
-        );
239
-        /** currency data **/
240
-        $this->registry->addData(
241
-            'currency_config',
242
-            $this->getCurrencySettings()
243
-        );
244
-        /** site timezone */
245
-        $this->registry->addData(
246
-            'default_timezone',
247
-            array(
248
-                'pretty' => EEH_DTT_Helper::get_timezone_string_for_display(),
249
-                'string' => get_option('timezone_string'),
250
-                'offset' => EEH_DTT_Helper::get_site_timezone_gmt_offset(),
251
-            )
252
-        );
253
-        /** site locale (user locale if user logged in) */
254
-        $this->registry->addData(
255
-            'locale',
256
-            array(
257
-                'user' => get_user_locale(),
258
-                'site' => get_locale()
259
-            )
260
-        );
261
-
262
-        $this->addJavascript(
263
-            CoreAssetManager::JS_HANDLE_CORE,
264
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
265
-            array(CoreAssetManager::JS_HANDLE_JQUERY)
266
-        )
267
-        ->setInlineDataCallback(
268
-            static function () {
269
-                wp_localize_script(
270
-                    CoreAssetManager::JS_HANDLE_CORE,
271
-                    CoreAssetManager::JS_HANDLE_I18N,
272
-                    EE_Registry::$i18n_js_strings
273
-                );
274
-            }
275
-        );
276
-    }
277
-
278
-
279
-    /**
280
-     * Registers vendor files that are bundled with a later version WP but might not be for the current version of
281
-     * WordPress in the running environment.
282
-     *
283
-     * @throws DuplicateCollectionIdentifierException
284
-     * @throws InvalidDataTypeException
285
-     * @throws InvalidEntityException
286
-     * @throws DomainException
287
-     * @since 4.9.71.p
288
-     */
289
-    private function registerWpAssets()
290
-    {
291
-        global $wp_version;
292
-        if (version_compare($wp_version, '5.0.beta', '>=')) {
293
-            return;
294
-        }
295
-        $this->addVendorJavascript(CoreAssetManager::JS_HANDLE_REACT, [], true, '16.6.0');
296
-        $this->addVendorJavascript(
297
-            CoreAssetManager::JS_HANDLE_REACT_DOM,
298
-            array(CoreAssetManager::JS_HANDLE_REACT),
299
-            true,
300
-            '16.6.0'
301
-        );
302
-        $this->addVendorJavascript(CoreAssetManager::JS_HANDLE_LODASH, [], true, '4.17.11')
303
-            ->setInlineDataCallback(
304
-                static function() {
305
-                    wp_add_inline_script(
306
-                        CoreAssetManager::JS_HANDLE_LODASH,
307
-                        'window.lodash = _.noConflict();'
308
-                    );
309
-                }
310
-            );
311
-    }
312
-
313
-
314
-    /**
315
-     * Returns configuration data for the accounting-js library.
316
-     * @since 4.9.71.p
317
-     * @return array
318
-     */
319
-    private function getAccountingSettings() {
320
-        return array(
321
-            'currency' => array(
322
-                'symbol'    => $this->currency_config->sign,
323
-                'format'    => array(
324
-                    'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
325
-                    'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
326
-                    'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
327
-                ),
328
-                'decimal'   => $this->currency_config->dec_mrk,
329
-                'thousand'  => $this->currency_config->thsnds,
330
-                'precision' => $this->currency_config->dec_plc,
331
-            ),
332
-            'number'   => array(
333
-                'precision' => $this->currency_config->dec_plc,
334
-                'thousand'  => $this->currency_config->thsnds,
335
-                'decimal'   => $this->currency_config->dec_mrk,
336
-            ),
337
-        );
338
-    }
339
-
340
-
341
-    /**
342
-     * Returns configuration data for the js Currency VO.
343
-     * @since 4.9.71.p
344
-     * @return array
345
-     */
346
-    private function getCurrencySettings()
347
-    {
348
-        return array(
349
-            'code' => $this->currency_config->code,
350
-            'singularLabel' => $this->currency_config->name,
351
-            'pluralLabel' => $this->currency_config->plural,
352
-            'sign' => $this->currency_config->sign,
353
-            'signB4' => $this->currency_config->sign_b4,
354
-            'decimalPlaces' => $this->currency_config->dec_plc,
355
-            'decimalMark' => $this->currency_config->dec_mrk,
356
-            'thousandsSeparator' => $this->currency_config->thsnds,
357
-        );
358
-    }
359
-
360
-
361
-    /**
362
-     * @throws DuplicateCollectionIdentifierException
363
-     * @throws InvalidDataTypeException
364
-     * @throws InvalidEntityException
365
-     * @throws DomainException
366
-     * @since 4.9.62.p
367
-     */
368
-    private function loadCoreCss()
369
-    {
370
-        if ($this->template_config->enable_default_style && ! is_admin()) {
371
-            $this->addStylesheet(
372
-                CoreAssetManager::CSS_HANDLE_DEFAULT,
373
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css')
374
-                    ? EVENT_ESPRESSO_UPLOAD_URL . 'css/espresso_default.css'
375
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
376
-                array('dashicons')
377
-            );
378
-            //Load custom style sheet if available
379
-            if ($this->template_config->custom_style_sheet !== null) {
380
-                $this->addStylesheet(
381
-                    CoreAssetManager::CSS_HANDLE_CUSTOM,
382
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
383
-                    array(CoreAssetManager::CSS_HANDLE_DEFAULT)
384
-                );
385
-            }
386
-        }
387
-        $this->addCss(self::CSS_HANDLE_CORE_CSS_DEFAULT, ['dashicons']);
388
-        $this->addCss(self::CSS_HANDLE_COMPONENTS, [self::CSS_HANDLE_CORE_CSS_DEFAULT]);
389
-    }
390
-
391
-
392
-    /**
393
-     * jQuery Validate for form validation
394
-     *
395
-     * @since 4.9.62.p
396
-     * @throws DomainException
397
-     * @throws DuplicateCollectionIdentifierException
398
-     * @throws InvalidDataTypeException
399
-     * @throws InvalidEntityException
400
-     */
401
-    private function loadJqueryValidate()
402
-    {
403
-        $this->addJavascript(
404
-            CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
405
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
406
-            array(CoreAssetManager::JS_HANDLE_JQUERY),
407
-            true,
408
-            '1.15.0'
409
-        );
410
-
411
-        $this->addJavascript(
412
-            CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
413
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
414
-            array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE),
415
-            true,
416
-            '1.15.0'
417
-        );
418
-    }
419
-
420
-
421
-    /**
422
-     * accounting.js for performing client-side calculations
423
-     *
424
-     * @since 4.9.62.p
425
-     * @throws DomainException
426
-     * @throws DuplicateCollectionIdentifierException
427
-     * @throws InvalidDataTypeException
428
-     * @throws InvalidEntityException
429
-     */
430
-    private function loadAccountingJs()
431
-    {
432
-        //accounting.js library
433
-        // @link http://josscrowcroft.github.io/accounting.js/
434
-        $this->addJavascript(
435
-            CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
436
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
437
-            array(CoreAssetManager::JS_HANDLE_UNDERSCORE),
438
-            true,
439
-            '0.3.2'
440
-        );
441
-
442
-        $this->addJavascript(
443
-            CoreAssetManager::JS_HANDLE_ACCOUNTING,
444
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
445
-            array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
446
-        )
447
-        ->setInlineDataCallback(
448
-            function () {
449
-                 wp_localize_script(
450
-                     CoreAssetManager::JS_HANDLE_ACCOUNTING,
451
-                     'EE_ACCOUNTING_CFG',
452
-                     $this->getAccountingSettings()
453
-                 );
454
-            }
455
-        );
456
-    }
457
-
458
-
459
-    /**
460
-     * registers assets for cleaning your ears
461
-     *
462
-     * @param JavascriptAsset $script
463
-     */
464
-    public function loadQtipJs(JavascriptAsset $script)
465
-    {
466
-        // qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
467
-        // can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
468
-        if (
469
-            $script->handle() === CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE
470
-            && apply_filters('FHEE_load_qtip', false)
471
-        ) {
472
-            EEH_Qtip_Loader::instance()->register_and_enqueue();
473
-        }
474
-    }
475
-
476
-
477
-    /**
478
-     * assets that are used in the WordPress admin
479
-     *
480
-     * @throws DuplicateCollectionIdentifierException
481
-     * @throws InvalidDataTypeException
482
-     * @throws InvalidEntityException
483
-     * @throws DomainException
484
-     * @since 4.9.62.p
485
-     */
486
-    private function registerAdminAssets()
487
-    {
488
-        $this->addJs(self::JS_HANDLE_WP_PLUGINS_PAGE)->setRequiresTranslation();
489
-        // note usage of the "JS_HANDLE.." constant is intentional here because css uses the same handle.
490
-        $this->addCss(self::JS_HANDLE_WP_PLUGINS_PAGE);
491
-    }
85
+	const JS_HANDLE_ACCOUNTING = 'ee-accounting';
86
+
87
+	const JS_HANDLE_WP_PLUGINS_PAGE = 'ee-wp-plugins-page';
88
+
89
+	// EE CSS assets handles
90
+	const CSS_HANDLE_DEFAULT = 'espresso_default';
91
+
92
+	const CSS_HANDLE_CUSTOM = 'espresso_custom_css';
93
+
94
+	const CSS_HANDLE_COMPONENTS = 'eventespresso-components';
95
+
96
+	const CSS_HANDLE_CORE_CSS_DEFAULT = 'eventespresso-core-css-default';
97
+
98
+	/**
99
+	 * @var EE_Currency_Config $currency_config
100
+	 */
101
+	protected $currency_config;
102
+
103
+	/**
104
+	 * @var EE_Template_Config $template_config
105
+	 */
106
+	protected $template_config;
107
+
108
+
109
+	/**
110
+	 * CoreAssetRegister constructor.
111
+	 *
112
+	 * @param AssetCollection    $assets
113
+	 * @param EE_Currency_Config $currency_config
114
+	 * @param EE_Template_Config $template_config
115
+	 * @param DomainInterface    $domain
116
+	 * @param Registry           $registry
117
+	 */
118
+	public function __construct(
119
+		AssetCollection $assets,
120
+		EE_Currency_Config $currency_config,
121
+		EE_Template_Config $template_config,
122
+		DomainInterface $domain,
123
+		Registry $registry
124
+	) {
125
+		$this->currency_config = $currency_config;
126
+		$this->template_config = $template_config;
127
+		parent::__construct($domain, $assets, $registry);
128
+	}
129
+
130
+
131
+	/**
132
+	 * @since 4.9.62.p
133
+	 * @throws DomainException
134
+	 * @throws DuplicateCollectionIdentifierException
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws InvalidEntityException
138
+	 * @throws InvalidInterfaceException
139
+	 */
140
+	public function addAssets()
141
+	{
142
+		$this->addJavascriptFiles();
143
+		$this->addStylesheetFiles();
144
+	}
145
+
146
+
147
+	/**
148
+	 * @since 4.9.62.p
149
+	 * @throws DomainException
150
+	 * @throws DuplicateCollectionIdentifierException
151
+	 * @throws InvalidArgumentException
152
+	 * @throws InvalidDataTypeException
153
+	 * @throws InvalidEntityException
154
+	 * @throws InvalidInterfaceException
155
+	 */
156
+	public function addJavascriptFiles()
157
+	{
158
+		$this->loadCoreJs();
159
+		$this->loadJqueryValidate();
160
+		$this->loadAccountingJs();
161
+		add_action(
162
+			'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
163
+			array($this, 'loadQtipJs')
164
+		);
165
+		$this->registerAdminAssets();
166
+	}
167
+
168
+
169
+	/**
170
+	 * @throws DuplicateCollectionIdentifierException
171
+	 * @throws InvalidDataTypeException
172
+	 * @throws InvalidEntityException
173
+	 * @throws DomainException
174
+	 * @since 4.9.62.p
175
+	 */
176
+	public function addStylesheetFiles()
177
+	{
178
+		$this->loadCoreCss();
179
+	}
180
+
181
+
182
+	/**
183
+	 * core default javascript
184
+	 *
185
+	 * @since 4.9.62.p
186
+	 * @throws DomainException
187
+	 * @throws DuplicateCollectionIdentifierException
188
+	 * @throws InvalidArgumentException
189
+	 * @throws InvalidDataTypeException
190
+	 * @throws InvalidEntityException
191
+	 * @throws InvalidInterfaceException
192
+	 */
193
+	private function loadCoreJs()
194
+	{
195
+		// conditionally load third-party libraries that WP core MIGHT have.
196
+		$this->registerWpAssets();
197
+
198
+		$this->addJs(self::JS_HANDLE_JS_CORE)->setHasInlineData();
199
+		$this->addJs(self::JS_HANDLE_VENDOR);
200
+		$this->addJs(self::JS_HANDLE_VALIDATORS)->setRequiresTranslation();
201
+		$this->addJs(self::JS_HANDLE_HELPERS)->setRequiresTranslation();
202
+		$this->addJs(self::JS_HANDLE_MODEL)->setRequiresTranslation();
203
+		$this->addJs(self::JS_HANDLE_VALUE_OBJECTS)->setRequiresTranslation();
204
+		$this->addJs(self::JS_HANDLE_DATA_STORES)->setRequiresTranslation()->setInlineDataCallback(
205
+			static function () {
206
+				wp_add_inline_script(
207
+					CoreAssetManager::JS_HANDLE_DATA_STORES,
208
+					is_admin()
209
+						? 'wp.apiFetch.use( eejs.middleWares.apiFetch.capsMiddleware( eejs.middleWares.apiFetch.CONTEXT_CAPS_EDIT ) )'
210
+						: 'wp.apiFetch.use( eejs.middleWares.apiFetch.capsMiddleware )'
211
+				);
212
+			}
213
+		);
214
+		$this->addJs(self::JS_HANDLE_HOCS, [self::JS_HANDLE_DATA_STORES])->setRequiresTranslation();
215
+		$this->addJs(self::JS_HANDLE_COMPONENTS, [self::JS_HANDLE_DATA_STORES])->setRequiresTranslation();
216
+		$this->addJs(self::JS_HANDLE_EDITOR_HOCS)->setRequiresTranslation();
217
+
218
+		$this->registry->addData('eejs_api_nonce', wp_create_nonce('wp_rest'));
219
+		$this->registry->addData(
220
+			'paths',
221
+			array(
222
+				'base_rest_route' => rest_url(),
223
+				'rest_route' => rest_url('ee/v4.8.36/'),
224
+				'collection_endpoints' => EED_Core_Rest_Api::getCollectionRoutesIndexedByModelName(),
225
+				'primary_keys' => EED_Core_Rest_Api::getPrimaryKeyNamesIndexedByModelName(),
226
+				'site_url' => site_url('/'),
227
+				'admin_url' => admin_url('/'),
228
+			)
229
+		);
230
+		// Event Espresso brand name
231
+		$this->registry->addData('brandName', Domain::brandName());
232
+		/** site formatting values **/
233
+		$this->registry->addData(
234
+			'site_formats',
235
+			array(
236
+				'date_formats' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats()
237
+			)
238
+		);
239
+		/** currency data **/
240
+		$this->registry->addData(
241
+			'currency_config',
242
+			$this->getCurrencySettings()
243
+		);
244
+		/** site timezone */
245
+		$this->registry->addData(
246
+			'default_timezone',
247
+			array(
248
+				'pretty' => EEH_DTT_Helper::get_timezone_string_for_display(),
249
+				'string' => get_option('timezone_string'),
250
+				'offset' => EEH_DTT_Helper::get_site_timezone_gmt_offset(),
251
+			)
252
+		);
253
+		/** site locale (user locale if user logged in) */
254
+		$this->registry->addData(
255
+			'locale',
256
+			array(
257
+				'user' => get_user_locale(),
258
+				'site' => get_locale()
259
+			)
260
+		);
261
+
262
+		$this->addJavascript(
263
+			CoreAssetManager::JS_HANDLE_CORE,
264
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
265
+			array(CoreAssetManager::JS_HANDLE_JQUERY)
266
+		)
267
+		->setInlineDataCallback(
268
+			static function () {
269
+				wp_localize_script(
270
+					CoreAssetManager::JS_HANDLE_CORE,
271
+					CoreAssetManager::JS_HANDLE_I18N,
272
+					EE_Registry::$i18n_js_strings
273
+				);
274
+			}
275
+		);
276
+	}
277
+
278
+
279
+	/**
280
+	 * Registers vendor files that are bundled with a later version WP but might not be for the current version of
281
+	 * WordPress in the running environment.
282
+	 *
283
+	 * @throws DuplicateCollectionIdentifierException
284
+	 * @throws InvalidDataTypeException
285
+	 * @throws InvalidEntityException
286
+	 * @throws DomainException
287
+	 * @since 4.9.71.p
288
+	 */
289
+	private function registerWpAssets()
290
+	{
291
+		global $wp_version;
292
+		if (version_compare($wp_version, '5.0.beta', '>=')) {
293
+			return;
294
+		}
295
+		$this->addVendorJavascript(CoreAssetManager::JS_HANDLE_REACT, [], true, '16.6.0');
296
+		$this->addVendorJavascript(
297
+			CoreAssetManager::JS_HANDLE_REACT_DOM,
298
+			array(CoreAssetManager::JS_HANDLE_REACT),
299
+			true,
300
+			'16.6.0'
301
+		);
302
+		$this->addVendorJavascript(CoreAssetManager::JS_HANDLE_LODASH, [], true, '4.17.11')
303
+			->setInlineDataCallback(
304
+				static function() {
305
+					wp_add_inline_script(
306
+						CoreAssetManager::JS_HANDLE_LODASH,
307
+						'window.lodash = _.noConflict();'
308
+					);
309
+				}
310
+			);
311
+	}
312
+
313
+
314
+	/**
315
+	 * Returns configuration data for the accounting-js library.
316
+	 * @since 4.9.71.p
317
+	 * @return array
318
+	 */
319
+	private function getAccountingSettings() {
320
+		return array(
321
+			'currency' => array(
322
+				'symbol'    => $this->currency_config->sign,
323
+				'format'    => array(
324
+					'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
325
+					'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
326
+					'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
327
+				),
328
+				'decimal'   => $this->currency_config->dec_mrk,
329
+				'thousand'  => $this->currency_config->thsnds,
330
+				'precision' => $this->currency_config->dec_plc,
331
+			),
332
+			'number'   => array(
333
+				'precision' => $this->currency_config->dec_plc,
334
+				'thousand'  => $this->currency_config->thsnds,
335
+				'decimal'   => $this->currency_config->dec_mrk,
336
+			),
337
+		);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Returns configuration data for the js Currency VO.
343
+	 * @since 4.9.71.p
344
+	 * @return array
345
+	 */
346
+	private function getCurrencySettings()
347
+	{
348
+		return array(
349
+			'code' => $this->currency_config->code,
350
+			'singularLabel' => $this->currency_config->name,
351
+			'pluralLabel' => $this->currency_config->plural,
352
+			'sign' => $this->currency_config->sign,
353
+			'signB4' => $this->currency_config->sign_b4,
354
+			'decimalPlaces' => $this->currency_config->dec_plc,
355
+			'decimalMark' => $this->currency_config->dec_mrk,
356
+			'thousandsSeparator' => $this->currency_config->thsnds,
357
+		);
358
+	}
359
+
360
+
361
+	/**
362
+	 * @throws DuplicateCollectionIdentifierException
363
+	 * @throws InvalidDataTypeException
364
+	 * @throws InvalidEntityException
365
+	 * @throws DomainException
366
+	 * @since 4.9.62.p
367
+	 */
368
+	private function loadCoreCss()
369
+	{
370
+		if ($this->template_config->enable_default_style && ! is_admin()) {
371
+			$this->addStylesheet(
372
+				CoreAssetManager::CSS_HANDLE_DEFAULT,
373
+				is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css')
374
+					? EVENT_ESPRESSO_UPLOAD_URL . 'css/espresso_default.css'
375
+					: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
376
+				array('dashicons')
377
+			);
378
+			//Load custom style sheet if available
379
+			if ($this->template_config->custom_style_sheet !== null) {
380
+				$this->addStylesheet(
381
+					CoreAssetManager::CSS_HANDLE_CUSTOM,
382
+					EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
383
+					array(CoreAssetManager::CSS_HANDLE_DEFAULT)
384
+				);
385
+			}
386
+		}
387
+		$this->addCss(self::CSS_HANDLE_CORE_CSS_DEFAULT, ['dashicons']);
388
+		$this->addCss(self::CSS_HANDLE_COMPONENTS, [self::CSS_HANDLE_CORE_CSS_DEFAULT]);
389
+	}
390
+
391
+
392
+	/**
393
+	 * jQuery Validate for form validation
394
+	 *
395
+	 * @since 4.9.62.p
396
+	 * @throws DomainException
397
+	 * @throws DuplicateCollectionIdentifierException
398
+	 * @throws InvalidDataTypeException
399
+	 * @throws InvalidEntityException
400
+	 */
401
+	private function loadJqueryValidate()
402
+	{
403
+		$this->addJavascript(
404
+			CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
405
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
406
+			array(CoreAssetManager::JS_HANDLE_JQUERY),
407
+			true,
408
+			'1.15.0'
409
+		);
410
+
411
+		$this->addJavascript(
412
+			CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
413
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
414
+			array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE),
415
+			true,
416
+			'1.15.0'
417
+		);
418
+	}
419
+
420
+
421
+	/**
422
+	 * accounting.js for performing client-side calculations
423
+	 *
424
+	 * @since 4.9.62.p
425
+	 * @throws DomainException
426
+	 * @throws DuplicateCollectionIdentifierException
427
+	 * @throws InvalidDataTypeException
428
+	 * @throws InvalidEntityException
429
+	 */
430
+	private function loadAccountingJs()
431
+	{
432
+		//accounting.js library
433
+		// @link http://josscrowcroft.github.io/accounting.js/
434
+		$this->addJavascript(
435
+			CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
436
+			EE_THIRD_PARTY_URL . 'accounting/accounting.js',
437
+			array(CoreAssetManager::JS_HANDLE_UNDERSCORE),
438
+			true,
439
+			'0.3.2'
440
+		);
441
+
442
+		$this->addJavascript(
443
+			CoreAssetManager::JS_HANDLE_ACCOUNTING,
444
+			EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
445
+			array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
446
+		)
447
+		->setInlineDataCallback(
448
+			function () {
449
+				 wp_localize_script(
450
+					 CoreAssetManager::JS_HANDLE_ACCOUNTING,
451
+					 'EE_ACCOUNTING_CFG',
452
+					 $this->getAccountingSettings()
453
+				 );
454
+			}
455
+		);
456
+	}
457
+
458
+
459
+	/**
460
+	 * registers assets for cleaning your ears
461
+	 *
462
+	 * @param JavascriptAsset $script
463
+	 */
464
+	public function loadQtipJs(JavascriptAsset $script)
465
+	{
466
+		// qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
467
+		// can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
468
+		if (
469
+			$script->handle() === CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE
470
+			&& apply_filters('FHEE_load_qtip', false)
471
+		) {
472
+			EEH_Qtip_Loader::instance()->register_and_enqueue();
473
+		}
474
+	}
475
+
476
+
477
+	/**
478
+	 * assets that are used in the WordPress admin
479
+	 *
480
+	 * @throws DuplicateCollectionIdentifierException
481
+	 * @throws InvalidDataTypeException
482
+	 * @throws InvalidEntityException
483
+	 * @throws DomainException
484
+	 * @since 4.9.62.p
485
+	 */
486
+	private function registerAdminAssets()
487
+	{
488
+		$this->addJs(self::JS_HANDLE_WP_PLUGINS_PAGE)->setRequiresTranslation();
489
+		// note usage of the "JS_HANDLE.." constant is intentional here because css uses the same handle.
490
+		$this->addCss(self::JS_HANDLE_WP_PLUGINS_PAGE);
491
+	}
492 492
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
         $this->addJs(self::JS_HANDLE_MODEL)->setRequiresTranslation();
203 203
         $this->addJs(self::JS_HANDLE_VALUE_OBJECTS)->setRequiresTranslation();
204 204
         $this->addJs(self::JS_HANDLE_DATA_STORES)->setRequiresTranslation()->setInlineDataCallback(
205
-            static function () {
205
+            static function() {
206 206
                 wp_add_inline_script(
207 207
                     CoreAssetManager::JS_HANDLE_DATA_STORES,
208 208
                     is_admin()
@@ -261,11 +261,11 @@  discard block
 block discarded – undo
261 261
 
262 262
         $this->addJavascript(
263 263
             CoreAssetManager::JS_HANDLE_CORE,
264
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
264
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
265 265
             array(CoreAssetManager::JS_HANDLE_JQUERY)
266 266
         )
267 267
         ->setInlineDataCallback(
268
-            static function () {
268
+            static function() {
269 269
                 wp_localize_script(
270 270
                     CoreAssetManager::JS_HANDLE_CORE,
271 271
                     CoreAssetManager::JS_HANDLE_I18N,
@@ -370,16 +370,16 @@  discard block
 block discarded – undo
370 370
         if ($this->template_config->enable_default_style && ! is_admin()) {
371 371
             $this->addStylesheet(
372 372
                 CoreAssetManager::CSS_HANDLE_DEFAULT,
373
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css')
373
+                is_readable(EVENT_ESPRESSO_UPLOAD_DIR.'css/espresso_default.css')
374 374
                     ? EVENT_ESPRESSO_UPLOAD_URL . 'css/espresso_default.css'
375
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
375
+                    : EE_GLOBAL_ASSETS_URL.'css/espresso_default.css',
376 376
                 array('dashicons')
377 377
             );
378 378
             //Load custom style sheet if available
379 379
             if ($this->template_config->custom_style_sheet !== null) {
380 380
                 $this->addStylesheet(
381 381
                     CoreAssetManager::CSS_HANDLE_CUSTOM,
382
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
382
+                    EVENT_ESPRESSO_UPLOAD_URL.'css/'.$this->template_config->custom_style_sheet,
383 383
                     array(CoreAssetManager::CSS_HANDLE_DEFAULT)
384 384
                 );
385 385
             }
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
     {
403 403
         $this->addJavascript(
404 404
             CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
405
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
405
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
406 406
             array(CoreAssetManager::JS_HANDLE_JQUERY),
407 407
             true,
408 408
             '1.15.0'
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 
411 411
         $this->addJavascript(
412 412
             CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
413
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
413
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
414 414
             array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE),
415 415
             true,
416 416
             '1.15.0'
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
         // @link http://josscrowcroft.github.io/accounting.js/
434 434
         $this->addJavascript(
435 435
             CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
436
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
436
+            EE_THIRD_PARTY_URL.'accounting/accounting.js',
437 437
             array(CoreAssetManager::JS_HANDLE_UNDERSCORE),
438 438
             true,
439 439
             '0.3.2'
@@ -441,11 +441,11 @@  discard block
 block discarded – undo
441 441
 
442 442
         $this->addJavascript(
443 443
             CoreAssetManager::JS_HANDLE_ACCOUNTING,
444
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
444
+            EE_GLOBAL_ASSETS_URL.'scripts/ee-accounting-config.js',
445 445
             array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
446 446
         )
447 447
         ->setInlineDataCallback(
448
-            function () {
448
+            function() {
449 449
                  wp_localize_script(
450 450
                      CoreAssetManager::JS_HANDLE_ACCOUNTING,
451 451
                      'EE_ACCOUNTING_CFG',
Please login to merge, or discard this patch.
core/EE_Load_Textdomain.core.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -36,19 +36,19 @@  discard block
 block discarded – undo
36 36
     {
37 37
         EE_Load_Textdomain::loadTranslationsForLocale();
38 38
         // now load the textdomain
39
-        if (!empty(EE_Load_Textdomain::$locale)) {
40
-            $github_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-' . EE_Load_Textdomain::$locale . '.mo';
39
+        if ( ! empty(EE_Load_Textdomain::$locale)) {
40
+            $github_mo_path = EE_LANGUAGES_SAFE_DIR.'event_espresso-'.EE_Load_Textdomain::$locale.'.mo';
41 41
             if (is_readable($github_mo_path)) {
42 42
                 load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
43 43
                 return;
44 44
             }
45
-            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
45
+            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR.'event_espresso-4-'.EE_Load_Textdomain::$locale.'.mo';
46 46
             if (is_readable($glotpress_mo_path)) {
47 47
                 load_textdomain('event_espresso', $glotpress_mo_path);
48 48
                 return;
49 49
             }
50 50
         }
51
-        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
51
+        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME).'/languages/');
52 52
     }
53 53
 
54 54
 
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
         if (empty(EE_Load_Textdomain::$locale)) {
72 72
             return;
73 73
         }
74
-        $language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
74
+        $language_check_option_name = 'ee_lang_check_'.EE_Load_Textdomain::$locale.'_'.EVENT_ESPRESSO_VERSION;
75 75
         // check if language files has already been sideloaded
76 76
         if (get_option($language_check_option_name)) {
77 77
             return;
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
 
82 82
         // load sideloader and sideload the .POT file as this should always be included.
83 83
         $sideloader_args = array(
84
-            '_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
85
-            '_download_from'   => $repo_base_URL .'.pot?raw=true',
84
+            '_upload_to'     => EE_PLUGIN_DIR_PATH.'languages/',
85
+            '_download_from'   => $repo_base_URL.'.pot?raw=true',
86 86
             '_new_file_name' => 'event_espresso.pot',
87 87
         );
88 88
         /** @var EEH_Sideloader $sideloader */
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
             update_option($language_check_option_name, 1);
96 96
             return;
97 97
         }
98
-        $repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
99
-        $file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
98
+        $repo_locale_URL = $repo_base_URL.'-'.EE_Load_Textdomain::$locale;
99
+        $file_name_base = 'event_espresso-'.EE_Load_Textdomain::$locale;
100 100
 
101 101
         // made it here so let's get the language files from the github repo, first the .mo file
102 102
         $sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
Please login to merge, or discard this patch.
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -13,105 +13,105 @@
 block discarded – undo
13 13
 class EE_Load_Textdomain extends EE_Base
14 14
 {
15 15
 
16
-    /**
17
-     * holds the current lang in WP
18
-     *
19
-     * @var string
20
-     */
21
-    private static $locale;
16
+	/**
17
+	 * holds the current lang in WP
18
+	 *
19
+	 * @var string
20
+	 */
21
+	private static $locale;
22 22
 
23 23
 
24
-    /**
25
-     * this takes care of retrieving a matching textdomain for event espresso for the current WPLANG from EE GitHub
26
-     * repo (if necessary) and then loading it for translations. should only be called in wp plugins_loaded callback
27
-     *
28
-     * @return void
29
-     * @throws EE_Error
30
-     * @throws InvalidArgumentException
31
-     * @throws ReflectionException
32
-     * @throws InvalidDataTypeException
33
-     * @throws InvalidInterfaceException
34
-     */
35
-    public static function load_textdomain()
36
-    {
37
-        EE_Load_Textdomain::loadTranslationsForLocale();
38
-        // now load the textdomain
39
-        if (!empty(EE_Load_Textdomain::$locale)) {
40
-            $github_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-' . EE_Load_Textdomain::$locale . '.mo';
41
-            if (is_readable($github_mo_path)) {
42
-                load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
43
-                return;
44
-            }
45
-            $glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
46
-            if (is_readable($glotpress_mo_path)) {
47
-                load_textdomain('event_espresso', $glotpress_mo_path);
48
-                return;
49
-            }
50
-        }
51
-        load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
52
-    }
24
+	/**
25
+	 * this takes care of retrieving a matching textdomain for event espresso for the current WPLANG from EE GitHub
26
+	 * repo (if necessary) and then loading it for translations. should only be called in wp plugins_loaded callback
27
+	 *
28
+	 * @return void
29
+	 * @throws EE_Error
30
+	 * @throws InvalidArgumentException
31
+	 * @throws ReflectionException
32
+	 * @throws InvalidDataTypeException
33
+	 * @throws InvalidInterfaceException
34
+	 */
35
+	public static function load_textdomain()
36
+	{
37
+		EE_Load_Textdomain::loadTranslationsForLocale();
38
+		// now load the textdomain
39
+		if (!empty(EE_Load_Textdomain::$locale)) {
40
+			$github_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-' . EE_Load_Textdomain::$locale . '.mo';
41
+			if (is_readable($github_mo_path)) {
42
+				load_plugin_textdomain('event_espresso', false, EE_LANGUAGES_SAFE_LOC);
43
+				return;
44
+			}
45
+			$glotpress_mo_path = EE_LANGUAGES_SAFE_DIR . 'event_espresso-4-' . EE_Load_Textdomain::$locale . '.mo';
46
+			if (is_readable($glotpress_mo_path)) {
47
+				load_textdomain('event_espresso', $glotpress_mo_path);
48
+				return;
49
+			}
50
+		}
51
+		load_plugin_textdomain('event_espresso', false, dirname(EE_PLUGIN_BASENAME) . '/languages/');
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * The purpose of this method is to sideload all of the lang files for EE, this includes the POT file and also the PO/MO files for the given WPLANG locale (if necessary).
57
-     *
58
-     * @access private
59
-     * @static
60
-     * @return void
61
-     * @throws EE_Error
62
-     * @throws InvalidArgumentException
63
-     * @throws ReflectionException
64
-     * @throws InvalidDataTypeException
65
-     * @throws InvalidInterfaceException
66
-     */
67
-    private static function loadTranslationsForLocale()
68
-    {
69
-        EE_Load_Textdomain::$locale = get_locale();
70
-        // can't download a language file if a language isn't set <taps temple>
71
-        if (empty(EE_Load_Textdomain::$locale)) {
72
-            return;
73
-        }
74
-        $language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
75
-        // check if language files has already been sideloaded
76
-        if (get_option($language_check_option_name)) {
77
-            return;
78
-        }
55
+	/**
56
+	 * The purpose of this method is to sideload all of the lang files for EE, this includes the POT file and also the PO/MO files for the given WPLANG locale (if necessary).
57
+	 *
58
+	 * @access private
59
+	 * @static
60
+	 * @return void
61
+	 * @throws EE_Error
62
+	 * @throws InvalidArgumentException
63
+	 * @throws ReflectionException
64
+	 * @throws InvalidDataTypeException
65
+	 * @throws InvalidInterfaceException
66
+	 */
67
+	private static function loadTranslationsForLocale()
68
+	{
69
+		EE_Load_Textdomain::$locale = get_locale();
70
+		// can't download a language file if a language isn't set <taps temple>
71
+		if (empty(EE_Load_Textdomain::$locale)) {
72
+			return;
73
+		}
74
+		$language_check_option_name = 'ee_lang_check_' . EE_Load_Textdomain::$locale . '_' . EVENT_ESPRESSO_VERSION;
75
+		// check if language files has already been sideloaded
76
+		if (get_option($language_check_option_name)) {
77
+			return;
78
+		}
79 79
 
80
-        $repo_base_URL = 'https://github.com/eventespresso/languages-ee4/blob/master/event_espresso';
80
+		$repo_base_URL = 'https://github.com/eventespresso/languages-ee4/blob/master/event_espresso';
81 81
 
82
-        // load sideloader and sideload the .POT file as this should always be included.
83
-        $sideloader_args = array(
84
-            '_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
85
-            '_download_from'   => $repo_base_URL .'.pot?raw=true',
86
-            '_new_file_name' => 'event_espresso.pot',
87
-        );
88
-        /** @var EEH_Sideloader $sideloader */
89
-        $sideloader = EE_Registry::instance()->load_helper('Sideloader', $sideloader_args, false);
90
-        // sideload the .POT file only for main site of the network, or if not running Multisite.
91
-        if (is_main_site()) {
92
-            $sideloader->sideload();
93
-        }
82
+		// load sideloader and sideload the .POT file as this should always be included.
83
+		$sideloader_args = array(
84
+			'_upload_to'     => EE_PLUGIN_DIR_PATH . 'languages/',
85
+			'_download_from'   => $repo_base_URL .'.pot?raw=true',
86
+			'_new_file_name' => 'event_espresso.pot',
87
+		);
88
+		/** @var EEH_Sideloader $sideloader */
89
+		$sideloader = EE_Registry::instance()->load_helper('Sideloader', $sideloader_args, false);
90
+		// sideload the .POT file only for main site of the network, or if not running Multisite.
91
+		if (is_main_site()) {
92
+			$sideloader->sideload();
93
+		}
94 94
 
95
-        // if locale is "en_US" then lets just get out, since Event Espresso core is already "en_US"
96
-        if (EE_Load_Textdomain::$locale === 'en_US') {
97
-            // but set option first else we'll forever be downloading the pot file
98
-            update_option($language_check_option_name, 1);
99
-            return;
100
-        }
101
-        $repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
102
-        $file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
95
+		// if locale is "en_US" then lets just get out, since Event Espresso core is already "en_US"
96
+		if (EE_Load_Textdomain::$locale === 'en_US') {
97
+			// but set option first else we'll forever be downloading the pot file
98
+			update_option($language_check_option_name, 1);
99
+			return;
100
+		}
101
+		$repo_locale_URL = $repo_base_URL . '-' . EE_Load_Textdomain::$locale;
102
+		$file_name_base = 'event_espresso-' . EE_Load_Textdomain::$locale;
103 103
 
104
-        // made it here so let's get the language files from the github repo, first the .mo file
105
-        $sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
106
-        $sideloader->set_new_file_name("{$file_name_base}.mo");
107
-        $sideloader->sideload();
104
+		// made it here so let's get the language files from the github repo, first the .mo file
105
+		$sideloader->set_download_from("{$repo_locale_URL}.mo?raw=true");
106
+		$sideloader->set_new_file_name("{$file_name_base}.mo");
107
+		$sideloader->sideload();
108 108
 
109
-        // now the .po file:
110
-        $sideloader->set_download_from("{$repo_locale_URL}.po?raw=true");
111
-        $sideloader->set_new_file_name("{$file_name_base}.po");
112
-        $sideloader->sideload();
109
+		// now the .po file:
110
+		$sideloader->set_download_from("{$repo_locale_URL}.po?raw=true");
111
+		$sideloader->set_new_file_name("{$file_name_base}.po");
112
+		$sideloader->sideload();
113 113
 
114
-        // set option so the above only runs when EE updates.
115
-        update_option($language_check_option_name, 1);
116
-    }
114
+		// set option so the above only runs when EE updates.
115
+		update_option($language_check_option_name, 1);
116
+	}
117 117
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6444 added lines, -6444 removed lines patch added patch discarded remove patch
@@ -35,6450 +35,6450 @@
 block discarded – undo
35 35
 abstract class EEM_Base extends EE_Base implements ResettableInterface
36 36
 {
37 37
 
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    private static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    __(
561
-                        '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.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            __(
680
-                                '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.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
-     *                                        array( array(
852
-     *                                        'OR'=>array(
853
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
-     *                                        )
856
-     *                                        ),
857
-     *                                        'limit'=>10,
858
-     *                                        'group_by'=>'TXN_ID'
859
-     *                                        ));
860
-     *                                        get all the answers to the question titled "shirt size" for event with id
861
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
-     *                                        'Question.QST_display_text'=>'shirt size',
863
-     *                                        'Registration.Event.EVT_ID'=>12
864
-     *                                        ),
865
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
866
-     *                                        ));
867
-     * @throws EE_Error
868
-     */
869
-    public function get_all($query_params = array())
870
-    {
871
-        if (isset($query_params['limit'])
872
-            && ! isset($query_params['group_by'])
873
-        ) {
874
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
-        }
876
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
-    }
878
-
879
-
880
-
881
-    /**
882
-     * Modifies the query parameters so we only get back model objects
883
-     * that "belong" to the current user
884
-     *
885
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     */
888
-    public function alter_query_params_to_only_include_mine($query_params = array())
889
-    {
890
-        $wp_user_field_name = $this->wp_user_field_name();
891
-        if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
-        }
894
-        return $query_params;
895
-    }
896
-
897
-
898
-
899
-    /**
900
-     * Returns the name of the field's name that points to the WP_User table
901
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
-     * foreign key to the WP_User table)
903
-     *
904
-     * @return string|boolean string on success, boolean false when there is no
905
-     * foreign key to the WP_User table
906
-     */
907
-    public function wp_user_field_name()
908
-    {
909
-        try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
911
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
-                $last_model_name = end($models_to_follow_to_wp_users);
913
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
-            } else {
916
-                $model_with_fk_to_wp_users = $this;
917
-                $model_chain_to_wp_user = '';
918
-            }
919
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
921
-        } catch (EE_Error $e) {
922
-            return false;
923
-        }
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
930
-     * (or transiently-related model) has a foreign key to the wp_users table;
931
-     * useful for finding if model objects of this type are 'owned' by the current user.
932
-     * This is an empty string when the foreign key is on this model and when it isn't,
933
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
934
-     * (or transiently-related model)
935
-     *
936
-     * @return string
937
-     */
938
-    public function model_chain_to_wp_user()
939
-    {
940
-        return $this->_model_chain_to_wp_user;
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
-     * like how registrations don't have a foreign key to wp_users, but the
948
-     * events they are for are), or is unrelated to wp users.
949
-     * generally available
950
-     *
951
-     * @return boolean
952
-     */
953
-    public function is_owned()
954
-    {
955
-        if ($this->model_chain_to_wp_user()) {
956
-            return true;
957
-        }
958
-        try {
959
-            $this->get_foreign_key_to('WP_User');
960
-            return true;
961
-        } catch (EE_Error $e) {
962
-            return false;
963
-        }
964
-    }
965
-
966
-
967
-    /**
968
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
-     * the model)
971
-     *
972
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
-     *                                  fields on the model, and the models we joined to in the query. However, you can
976
-     *                                  override this and set the select to "*", or a specific column name, like
977
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
-     *                                  the aliases used to refer to this selection, and values are to be
980
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
-     * @throws EE_Error
984
-     * @throws InvalidArgumentException
985
-     */
986
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
-    {
988
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
-        ;
990
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
991
-        $select_expressions = $columns_to_select === null
992
-            ? $this->_construct_default_select_sql($model_query_info)
993
-            : '';
994
-        if ($this->_custom_selections instanceof CustomSelects) {
995
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
-            $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
998
-                : $custom_expressions;
999
-        }
1000
-
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
-     * method of including extra select information.
1010
-     *
1011
-     * @param array             $query_params
1012
-     * @param null|array|string $columns_to_select
1013
-     * @return null|CustomSelects
1014
-     * @throws InvalidArgumentException
1015
-     */
1016
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
-    {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
-            return null;
1020
-        }
1021
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
-        return new CustomSelects($selects);
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1030
-     * but you can use the model query params to more easily
1031
-     * take care of joins, field preparation etc.
1032
-     *
1033
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
-    }
1050
-
1051
-
1052
-
1053
-    /**
1054
-     * For creating a custom select statement
1055
-     *
1056
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
-     *                                 SQL, and 1=>is the datatype
1059
-     * @throws EE_Error
1060
-     * @return string
1061
-     */
1062
-    private function _construct_select_from_input($columns_to_select)
1063
-    {
1064
-        if (is_array($columns_to_select)) {
1065
-            $select_sql_array = array();
1066
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
-                    throw new EE_Error(
1069
-                        sprintf(
1070
-                            __(
1071
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
-                                'event_espresso'
1073
-                            ),
1074
-                            $selection_and_datatype,
1075
-                            $alias
1076
-                        )
1077
-                    );
1078
-                }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
-                    throw new EE_Error(
1081
-                        sprintf(
1082
-                            esc_html__(
1083
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
-                                'event_espresso'
1085
-                            ),
1086
-                            $selection_and_datatype[1],
1087
-                            $selection_and_datatype[0],
1088
-                            $alias,
1089
-                            implode(', ', $this->_valid_wpdb_data_types)
1090
-                        )
1091
-                    );
1092
-                }
1093
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
-            }
1095
-            $columns_to_select_string = implode(', ', $select_sql_array);
1096
-        } else {
1097
-            $columns_to_select_string = $columns_to_select;
1098
-        }
1099
-        return $columns_to_select_string;
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
-     *
1107
-     * @return string
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function primary_key_name()
1111
-    {
1112
-        return $this->get_primary_key_field()->get_name();
1113
-    }
1114
-
1115
-
1116
-
1117
-    /**
1118
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
-     * If there is no primary key on this model, $id is treated as primary key string
1120
-     *
1121
-     * @param mixed $id int or string, depending on the type of the model's primary key
1122
-     * @return EE_Base_Class
1123
-     */
1124
-    public function get_one_by_ID($id)
1125
-    {
1126
-        if ($this->get_from_entity_map($id)) {
1127
-            return $this->get_from_entity_map($id);
1128
-        }
1129
-        return $this->get_one(
1130
-            $this->alter_query_params_to_restrict_by_ID(
1131
-                $id,
1132
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
-            )
1134
-        );
1135
-    }
1136
-
1137
-
1138
-
1139
-    /**
1140
-     * Alters query parameters to only get items with this ID are returned.
1141
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1142
-     * or could just be a simple primary key ID
1143
-     *
1144
-     * @param int   $id
1145
-     * @param array $query_params
1146
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1147
-     * @throws EE_Error
1148
-     */
1149
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1150
-    {
1151
-        if (! isset($query_params[0])) {
1152
-            $query_params[0] = array();
1153
-        }
1154
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1155
-        if ($conditions_from_id === null) {
1156
-            $query_params[0][ $this->primary_key_name() ] = $id;
1157
-        } else {
1158
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1159
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1160
-        }
1161
-        return $query_params;
1162
-    }
1163
-
1164
-
1165
-
1166
-    /**
1167
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1168
-     * array. If no item is found, null is returned.
1169
-     *
1170
-     * @param array $query_params like EEM_Base's $query_params variable.
1171
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1172
-     * @throws EE_Error
1173
-     */
1174
-    public function get_one($query_params = array())
1175
-    {
1176
-        if (! is_array($query_params)) {
1177
-            EE_Error::doing_it_wrong(
1178
-                'EEM_Base::get_one',
1179
-                sprintf(
1180
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1181
-                    gettype($query_params)
1182
-                ),
1183
-                '4.6.0'
1184
-            );
1185
-            $query_params = array();
1186
-        }
1187
-        $query_params['limit'] = 1;
1188
-        $items = $this->get_all($query_params);
1189
-        if (empty($items)) {
1190
-            return null;
1191
-        }
1192
-        return array_shift($items);
1193
-    }
1194
-
1195
-
1196
-
1197
-    /**
1198
-     * Returns the next x number of items in sequence from the given value as
1199
-     * found in the database matching the given query conditions.
1200
-     *
1201
-     * @param mixed $current_field_value    Value used for the reference point.
1202
-     * @param null  $field_to_order_by      What field is used for the
1203
-     *                                      reference point.
1204
-     * @param int   $limit                  How many to return.
1205
-     * @param array $query_params           Extra conditions on the query.
1206
-     * @param null  $columns_to_select      If left null, then an array of
1207
-     *                                      EE_Base_Class objects is returned,
1208
-     *                                      otherwise you can indicate just the
1209
-     *                                      columns you want returned.
1210
-     * @return EE_Base_Class[]|array
1211
-     * @throws EE_Error
1212
-     */
1213
-    public function next_x(
1214
-        $current_field_value,
1215
-        $field_to_order_by = null,
1216
-        $limit = 1,
1217
-        $query_params = array(),
1218
-        $columns_to_select = null
1219
-    ) {
1220
-        return $this->_get_consecutive(
1221
-            $current_field_value,
1222
-            '>',
1223
-            $field_to_order_by,
1224
-            $limit,
1225
-            $query_params,
1226
-            $columns_to_select
1227
-        );
1228
-    }
1229
-
1230
-
1231
-
1232
-    /**
1233
-     * Returns the previous x number of items in sequence from the given value
1234
-     * as found in the database matching the given query conditions.
1235
-     *
1236
-     * @param mixed $current_field_value    Value used for the reference point.
1237
-     * @param null  $field_to_order_by      What field is used for the
1238
-     *                                      reference point.
1239
-     * @param int   $limit                  How many to return.
1240
-     * @param array $query_params           Extra conditions on the query.
1241
-     * @param null  $columns_to_select      If left null, then an array of
1242
-     *                                      EE_Base_Class objects is returned,
1243
-     *                                      otherwise you can indicate just the
1244
-     *                                      columns you want returned.
1245
-     * @return EE_Base_Class[]|array
1246
-     * @throws EE_Error
1247
-     */
1248
-    public function previous_x(
1249
-        $current_field_value,
1250
-        $field_to_order_by = null,
1251
-        $limit = 1,
1252
-        $query_params = array(),
1253
-        $columns_to_select = null
1254
-    ) {
1255
-        return $this->_get_consecutive(
1256
-            $current_field_value,
1257
-            '<',
1258
-            $field_to_order_by,
1259
-            $limit,
1260
-            $query_params,
1261
-            $columns_to_select
1262
-        );
1263
-    }
1264
-
1265
-
1266
-
1267
-    /**
1268
-     * Returns the next item in sequence from the given value as found in the
1269
-     * database matching the given query conditions.
1270
-     *
1271
-     * @param mixed $current_field_value    Value used for the reference point.
1272
-     * @param null  $field_to_order_by      What field is used for the
1273
-     *                                      reference point.
1274
-     * @param array $query_params           Extra conditions on the query.
1275
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1276
-     *                                      object is returned, otherwise you
1277
-     *                                      can indicate just the columns you
1278
-     *                                      want and a single array indexed by
1279
-     *                                      the columns will be returned.
1280
-     * @return EE_Base_Class|null|array()
1281
-     * @throws EE_Error
1282
-     */
1283
-    public function next(
1284
-        $current_field_value,
1285
-        $field_to_order_by = null,
1286
-        $query_params = array(),
1287
-        $columns_to_select = null
1288
-    ) {
1289
-        $results = $this->_get_consecutive(
1290
-            $current_field_value,
1291
-            '>',
1292
-            $field_to_order_by,
1293
-            1,
1294
-            $query_params,
1295
-            $columns_to_select
1296
-        );
1297
-        return empty($results) ? null : reset($results);
1298
-    }
1299
-
1300
-
1301
-
1302
-    /**
1303
-     * Returns the previous item in sequence from the given value as found in
1304
-     * the database matching the given query conditions.
1305
-     *
1306
-     * @param mixed $current_field_value    Value used for the reference point.
1307
-     * @param null  $field_to_order_by      What field is used for the
1308
-     *                                      reference point.
1309
-     * @param array $query_params           Extra conditions on the query.
1310
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1311
-     *                                      object is returned, otherwise you
1312
-     *                                      can indicate just the columns you
1313
-     *                                      want and a single array indexed by
1314
-     *                                      the columns will be returned.
1315
-     * @return EE_Base_Class|null|array()
1316
-     * @throws EE_Error
1317
-     */
1318
-    public function previous(
1319
-        $current_field_value,
1320
-        $field_to_order_by = null,
1321
-        $query_params = array(),
1322
-        $columns_to_select = null
1323
-    ) {
1324
-        $results = $this->_get_consecutive(
1325
-            $current_field_value,
1326
-            '<',
1327
-            $field_to_order_by,
1328
-            1,
1329
-            $query_params,
1330
-            $columns_to_select
1331
-        );
1332
-        return empty($results) ? null : reset($results);
1333
-    }
1334
-
1335
-
1336
-
1337
-    /**
1338
-     * Returns the a consecutive number of items in sequence from the given
1339
-     * value as found in the database matching the given query conditions.
1340
-     *
1341
-     * @param mixed  $current_field_value   Value used for the reference point.
1342
-     * @param string $operand               What operand is used for the sequence.
1343
-     * @param string $field_to_order_by     What field is used for the reference point.
1344
-     * @param int    $limit                 How many to return.
1345
-     * @param array  $query_params          Extra conditions on the query.
1346
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1347
-     *                                      otherwise you can indicate just the columns you want returned.
1348
-     * @return EE_Base_Class[]|array
1349
-     * @throws EE_Error
1350
-     */
1351
-    protected function _get_consecutive(
1352
-        $current_field_value,
1353
-        $operand = '>',
1354
-        $field_to_order_by = null,
1355
-        $limit = 1,
1356
-        $query_params = array(),
1357
-        $columns_to_select = null
1358
-    ) {
1359
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1360
-        if (empty($field_to_order_by)) {
1361
-            if ($this->has_primary_key_field()) {
1362
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1363
-            } else {
1364
-                if (WP_DEBUG) {
1365
-                    throw new EE_Error(__(
1366
-                        '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).',
1367
-                        'event_espresso'
1368
-                    ));
1369
-                }
1370
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1371
-                return array();
1372
-            }
1373
-        }
1374
-        if (! is_array($query_params)) {
1375
-            EE_Error::doing_it_wrong(
1376
-                'EEM_Base::_get_consecutive',
1377
-                sprintf(
1378
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1379
-                    gettype($query_params)
1380
-                ),
1381
-                '4.6.0'
1382
-            );
1383
-            $query_params = array();
1384
-        }
1385
-        // let's add the where query param for consecutive look up.
1386
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1387
-        $query_params['limit'] = $limit;
1388
-        // set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1390
-        $query_params['order_by'] = $operand === '>'
1391
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
-        if (empty($columns_to_select)) {
1395
-            return $this->get_all($query_params);
1396
-        }
1397
-        // getting just the fields
1398
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        // note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        // and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        // if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        // if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            throw new EE_Error(sprintf(__(
1469
-                '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.',
1470
-                'event_espresso'
1471
-            ), $field_name));
1472
-        }
1473
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1474
-        // the field.
1475
-        $this->_timezone = $field_settings->get_timezone();
1476
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1477
-    }
1478
-
1479
-
1480
-
1481
-    /**
1482
-     * This returns the current time in a format setup for a query on this model.
1483
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1484
-     * it will return:
1485
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1486
-     *  NOW
1487
-     *  - or a unix timestamp (equivalent to time())
1488
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1489
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1490
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1491
-     * @since 4.6.x
1492
-     * @param string $field_name       The field the current time is needed for.
1493
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1494
-     *                                 formatted string matching the set format for the field in the set timezone will
1495
-     *                                 be returned.
1496
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1497
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1498
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1499
-     *                                 exception is triggered.
1500
-     */
1501
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1502
-    {
1503
-        $formats = $this->get_formats_for($field_name);
1504
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1505
-        if ($timestamp) {
1506
-            return $DateTime->format('U');
1507
-        }
1508
-        // not returning timestamp, so return formatted string in timezone.
1509
-        switch ($what) {
1510
-            case 'time':
1511
-                return $DateTime->format($formats[1]);
1512
-                break;
1513
-            case 'date':
1514
-                return $DateTime->format($formats[0]);
1515
-                break;
1516
-            default:
1517
-                return $DateTime->format(implode(' ', $formats));
1518
-                break;
1519
-        }
1520
-    }
1521
-
1522
-
1523
-
1524
-    /**
1525
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1526
-     * for the model are.  Returns a DateTime object.
1527
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1528
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1529
-     * ignored.
1530
-     *
1531
-     * @param string $field_name      The field being setup.
1532
-     * @param string $timestring      The date time string being used.
1533
-     * @param string $incoming_format The format for the time string.
1534
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1535
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1536
-     *                                format is
1537
-     *                                'U', this is ignored.
1538
-     * @return DateTime
1539
-     * @throws EE_Error
1540
-     */
1541
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1542
-    {
1543
-        // just using this to ensure the timezone is set correctly internally
1544
-        $this->get_formats_for($field_name);
1545
-        // load EEH_DTT_Helper
1546
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1547
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1548
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1549
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1550
-    }
1551
-
1552
-
1553
-
1554
-    /**
1555
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1556
-     *
1557
-     * @return EE_Table_Base[]
1558
-     */
1559
-    public function get_tables()
1560
-    {
1561
-        return $this->_tables;
1562
-    }
1563
-
1564
-
1565
-
1566
-    /**
1567
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1568
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1569
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1570
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1571
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1572
-     * model object with EVT_ID = 1
1573
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1574
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1575
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1576
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1577
-     * are not specified)
1578
-     *
1579
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1580
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1581
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1582
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1583
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1584
-     *                                         ID=34, we'd use this method as follows:
1585
-     *                                         EEM_Transaction::instance()->update(
1586
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1587
-     *                                         array(array('TXN_ID'=>34)));
1588
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1589
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1590
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1591
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1592
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1593
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1594
-     *                                         TRUE, it is assumed that you've already called
1595
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1596
-     *                                         malicious javascript. However, if
1597
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1598
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1599
-     *                                         and every other field, before insertion. We provide this parameter
1600
-     *                                         because model objects perform their prepare_for_set function on all
1601
-     *                                         their values, and so don't need to be called again (and in many cases,
1602
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1603
-     *                                         prepare_for_set method...)
1604
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1605
-     *                                         in this model's entity map according to $fields_n_values that match
1606
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1607
-     *                                         by setting this to FALSE, but be aware that model objects being used
1608
-     *                                         could get out-of-sync with the database
1609
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1610
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1611
-     *                                         bad)
1612
-     * @throws EE_Error
1613
-     */
1614
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1615
-    {
1616
-        if (! is_array($query_params)) {
1617
-            EE_Error::doing_it_wrong(
1618
-                'EEM_Base::update',
1619
-                sprintf(
1620
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1621
-                    gettype($query_params)
1622
-                ),
1623
-                '4.6.0'
1624
-            );
1625
-            $query_params = array();
1626
-        }
1627
-        /**
1628
-         * Action called before a model update call has been made.
1629
-         *
1630
-         * @param EEM_Base $model
1631
-         * @param array    $fields_n_values the updated fields and their new values
1632
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1633
-         */
1634
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1635
-        /**
1636
-         * Filters the fields about to be updated given the query parameters. You can provide the
1637
-         * $query_params to $this->get_all() to find exactly which records will be updated
1638
-         *
1639
-         * @param array    $fields_n_values fields and their new values
1640
-         * @param EEM_Base $model           the model being queried
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        $fields_n_values = (array) apply_filters(
1644
-            'FHEE__EEM_Base__update__fields_n_values',
1645
-            $fields_n_values,
1646
-            $this,
1647
-            $query_params
1648
-        );
1649
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1650
-        // to do that, for each table, verify that it's PK isn't null.
1651
-        $tables = $this->get_tables();
1652
-        // 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
1653
-        // NOTE: we should make this code more efficient by NOT querying twice
1654
-        // before the real update, but that needs to first go through ALPHA testing
1655
-        // as it's dangerous. says Mike August 8 2014
1656
-        // we want to make sure the default_where strategy is ignored
1657
-        $this->_ignore_where_strategy = true;
1658
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1659
-        foreach ($wpdb_select_results as $wpdb_result) {
1660
-            // type cast stdClass as array
1661
-            $wpdb_result = (array) $wpdb_result;
1662
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1663
-            if ($this->has_primary_key_field()) {
1664
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1665
-            } else {
1666
-                // 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)
1667
-                $main_table_pk_value = null;
1668
-            }
1669
-            // 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
1670
-            // 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
1671
-            if (count($tables) > 1) {
1672
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1673
-                // in that table, and so we'll want to insert one
1674
-                foreach ($tables as $table_obj) {
1675
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1676
-                    // if there is no private key for this table on the results, it means there's no entry
1677
-                    // in this table, right? so insert a row in the current table, using any fields available
1678
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1679
-                           && $wpdb_result[ $this_table_pk_column ])
1680
-                    ) {
1681
-                        $success = $this->_insert_into_specific_table(
1682
-                            $table_obj,
1683
-                            $fields_n_values,
1684
-                            $main_table_pk_value
1685
-                        );
1686
-                        // if we died here, report the error
1687
-                        if (! $success) {
1688
-                            return false;
1689
-                        }
1690
-                    }
1691
-                }
1692
-            }
1693
-            //              //and now check that if we have cached any models by that ID on the model, that
1694
-            //              //they also get updated properly
1695
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1696
-            //              if( $model_object ){
1697
-            //                  foreach( $fields_n_values as $field => $value ){
1698
-            //                      $model_object->set($field, $value);
1699
-            // let's make sure default_where strategy is followed now
1700
-            $this->_ignore_where_strategy = false;
1701
-        }
1702
-        // if we want to keep model objects in sync, AND
1703
-        // if this wasn't called from a model object (to update itself)
1704
-        // then we want to make sure we keep all the existing
1705
-        // model objects in sync with the db
1706
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1707
-            if ($this->has_primary_key_field()) {
1708
-                $model_objs_affected_ids = $this->get_col($query_params);
1709
-            } else {
1710
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1711
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1712
-                $model_objs_affected_ids = array();
1713
-                foreach ($models_affected_key_columns as $row) {
1714
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1715
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1716
-                }
1717
-            }
1718
-            if (! $model_objs_affected_ids) {
1719
-                // wait wait wait- if nothing was affected let's stop here
1720
-                return 0;
1721
-            }
1722
-            foreach ($model_objs_affected_ids as $id) {
1723
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1724
-                if ($model_obj_in_entity_map) {
1725
-                    foreach ($fields_n_values as $field => $new_value) {
1726
-                        $model_obj_in_entity_map->set($field, $new_value);
1727
-                    }
1728
-                }
1729
-            }
1730
-            // if there is a primary key on this model, we can now do a slight optimization
1731
-            if ($this->has_primary_key_field()) {
1732
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1733
-                $query_params = array(
1734
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1735
-                    'limit'                    => count($model_objs_affected_ids),
1736
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1737
-                );
1738
-            }
1739
-        }
1740
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1741
-        $SQL = "UPDATE "
1742
-               . $model_query_info->get_full_join_sql()
1743
-               . " SET "
1744
-               . $this->_construct_update_sql($fields_n_values)
1745
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1746
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1747
-        /**
1748
-         * Action called after a model update call has been made.
1749
-         *
1750
-         * @param EEM_Base $model
1751
-         * @param array    $fields_n_values the updated fields and their new values
1752
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1753
-         * @param int      $rows_affected
1754
-         */
1755
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1756
-        return $rows_affected;// how many supposedly got updated
1757
-    }
1758
-
1759
-
1760
-
1761
-    /**
1762
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1763
-     * are teh values of the field specified (or by default the primary key field)
1764
-     * that matched the query params. Note that you should pass the name of the
1765
-     * model FIELD, not the database table's column name.
1766
-     *
1767
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1768
-     * @param string $field_to_select
1769
-     * @return array just like $wpdb->get_col()
1770
-     * @throws EE_Error
1771
-     */
1772
-    public function get_col($query_params = array(), $field_to_select = null)
1773
-    {
1774
-        if ($field_to_select) {
1775
-            $field = $this->field_settings_for($field_to_select);
1776
-        } elseif ($this->has_primary_key_field()) {
1777
-            $field = $this->get_primary_key_field();
1778
-        } else {
1779
-            // no primary key, just grab the first column
1780
-            $field = reset($this->field_settings());
1781
-        }
1782
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1783
-        $select_expressions = $field->get_qualified_column();
1784
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1785
-        return $this->_do_wpdb_query('get_col', array($SQL));
1786
-    }
1787
-
1788
-
1789
-
1790
-    /**
1791
-     * Returns a single column value for a single row from the database
1792
-     *
1793
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1794
-     * @param string $field_to_select @see EEM_Base::get_col()
1795
-     * @return string
1796
-     * @throws EE_Error
1797
-     */
1798
-    public function get_var($query_params = array(), $field_to_select = null)
1799
-    {
1800
-        $query_params['limit'] = 1;
1801
-        $col = $this->get_col($query_params, $field_to_select);
1802
-        if (! empty($col)) {
1803
-            return reset($col);
1804
-        }
1805
-        return null;
1806
-    }
1807
-
1808
-
1809
-
1810
-    /**
1811
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1812
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1813
-     * injection, but currently no further filtering is done
1814
-     *
1815
-     * @global      $wpdb
1816
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1817
-     *                               be updated to in the DB
1818
-     * @return string of SQL
1819
-     * @throws EE_Error
1820
-     */
1821
-    public function _construct_update_sql($fields_n_values)
1822
-    {
1823
-        /** @type WPDB $wpdb */
1824
-        global $wpdb;
1825
-        $cols_n_values = array();
1826
-        foreach ($fields_n_values as $field_name => $value) {
1827
-            $field_obj = $this->field_settings_for($field_name);
1828
-            // if the value is NULL, we want to assign the value to that.
1829
-            // wpdb->prepare doesn't really handle that properly
1830
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1831
-            $value_sql = $prepared_value === null ? 'NULL'
1832
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1833
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1834
-        }
1835
-        return implode(",", $cols_n_values);
1836
-    }
1837
-
1838
-
1839
-
1840
-    /**
1841
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1842
-     * Performs a HARD delete, meaning the database row should always be removed,
1843
-     * not just have a flag field on it switched
1844
-     * Wrapper for EEM_Base::delete_permanently()
1845
-     *
1846
-     * @param mixed $id
1847
-     * @param boolean $allow_blocking
1848
-     * @return int the number of rows deleted
1849
-     * @throws EE_Error
1850
-     */
1851
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1852
-    {
1853
-        return $this->delete_permanently(
1854
-            array(
1855
-                array($this->get_primary_key_field()->get_name() => $id),
1856
-                'limit' => 1,
1857
-            ),
1858
-            $allow_blocking
1859
-        );
1860
-    }
1861
-
1862
-
1863
-
1864
-    /**
1865
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1866
-     * Wrapper for EEM_Base::delete()
1867
-     *
1868
-     * @param mixed $id
1869
-     * @param boolean $allow_blocking
1870
-     * @return int the number of rows deleted
1871
-     * @throws EE_Error
1872
-     */
1873
-    public function delete_by_ID($id, $allow_blocking = true)
1874
-    {
1875
-        return $this->delete(
1876
-            array(
1877
-                array($this->get_primary_key_field()->get_name() => $id),
1878
-                'limit' => 1,
1879
-            ),
1880
-            $allow_blocking
1881
-        );
1882
-    }
1883
-
1884
-
1885
-
1886
-    /**
1887
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1888
-     * meaning if the model has a field that indicates its been "trashed" or
1889
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1890
-     *
1891
-     * @see EEM_Base::delete_permanently
1892
-     * @param array   $query_params
1893
-     * @param boolean $allow_blocking
1894
-     * @return int how many rows got deleted
1895
-     * @throws EE_Error
1896
-     */
1897
-    public function delete($query_params, $allow_blocking = true)
1898
-    {
1899
-        return $this->delete_permanently($query_params, $allow_blocking);
1900
-    }
1901
-
1902
-
1903
-
1904
-    /**
1905
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1906
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1907
-     * as archived, not actually deleted
1908
-     *
1909
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1910
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1911
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1912
-     *                                deletes regardless of other objects which may depend on it. Its generally
1913
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1914
-     *                                DB
1915
-     * @return int how many rows got deleted
1916
-     * @throws EE_Error
1917
-     */
1918
-    public function delete_permanently($query_params, $allow_blocking = true)
1919
-    {
1920
-        /**
1921
-         * Action called just before performing a real deletion query. You can use the
1922
-         * model and its $query_params to find exactly which items will be deleted
1923
-         *
1924
-         * @param EEM_Base $model
1925
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1926
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1927
-         *                                 to block (prevent) this deletion
1928
-         */
1929
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1930
-        // some MySQL databases may be running safe mode, which may restrict
1931
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1932
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1933
-        // to delete them
1934
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1935
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1936
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1937
-            $columns_and_ids_for_deleting
1938
-        );
1939
-        /**
1940
-         * Allows client code to act on the items being deleted before the query is actually executed.
1941
-         *
1942
-         * @param EEM_Base $this  The model instance being acted on.
1943
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1944
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1945
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1946
-         *                                                  derived from the incoming query parameters.
1947
-         *                                                  @see details on the structure of this array in the phpdocs
1948
-         *                                                  for the `_get_ids_for_delete_method`
1949
-         *
1950
-         */
1951
-        do_action(
1952
-            'AHEE__EEM_Base__delete__before_query',
1953
-            $this,
1954
-            $query_params,
1955
-            $allow_blocking,
1956
-            $columns_and_ids_for_deleting
1957
-        );
1958
-        if ($deletion_where_query_part) {
1959
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1960
-            $table_aliases = array_keys($this->_tables);
1961
-            $SQL = "DELETE "
1962
-                   . implode(", ", $table_aliases)
1963
-                   . " FROM "
1964
-                   . $model_query_info->get_full_join_sql()
1965
-                   . " WHERE "
1966
-                   . $deletion_where_query_part;
1967
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1968
-        } else {
1969
-            $rows_deleted = 0;
1970
-        }
1971
-
1972
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1973
-        // there was no error with the delete query.
1974
-        if ($this->has_primary_key_field()
1975
-            && $rows_deleted !== false
1976
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1977
-        ) {
1978
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1979
-            foreach ($ids_for_removal as $id) {
1980
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1981
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1982
-                }
1983
-            }
1984
-
1985
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1986
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1987
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1988
-            // (although it is possible).
1989
-            // Note this can be skipped by using the provided filter and returning false.
1990
-            if (apply_filters(
1991
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1992
-                ! $this instanceof EEM_Extra_Meta,
1993
-                $this
1994
-            )) {
1995
-                EEM_Extra_Meta::instance()->delete_permanently(array(
1996
-                    0 => array(
1997
-                        'EXM_type' => $this->get_this_model_name(),
1998
-                        'OBJ_ID'   => array(
1999
-                            'IN',
2000
-                            $ids_for_removal
2001
-                        )
2002
-                    )
2003
-                ));
2004
-            }
2005
-        }
2006
-
2007
-        /**
2008
-         * Action called just after performing a real deletion query. Although at this point the
2009
-         * items should have been deleted
2010
-         *
2011
-         * @param EEM_Base $model
2012
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2013
-         * @param int      $rows_deleted
2014
-         */
2015
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2016
-        return $rows_deleted;// how many supposedly got deleted
2017
-    }
2018
-
2019
-
2020
-
2021
-    /**
2022
-     * Checks all the relations that throw error messages when there are blocking related objects
2023
-     * for related model objects. If there are any related model objects on those relations,
2024
-     * adds an EE_Error, and return true
2025
-     *
2026
-     * @param EE_Base_Class|int $this_model_obj_or_id
2027
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2028
-     *                                                 should be ignored when determining whether there are related
2029
-     *                                                 model objects which block this model object's deletion. Useful
2030
-     *                                                 if you know A is related to B and are considering deleting A,
2031
-     *                                                 but want to see if A has any other objects blocking its deletion
2032
-     *                                                 before removing the relation between A and B
2033
-     * @return boolean
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2037
-    {
2038
-        // first, if $ignore_this_model_obj was supplied, get its model
2039
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2040
-            $ignored_model = $ignore_this_model_obj->get_model();
2041
-        } else {
2042
-            $ignored_model = null;
2043
-        }
2044
-        // now check all the relations of $this_model_obj_or_id and see if there
2045
-        // are any related model objects blocking it?
2046
-        $is_blocked = false;
2047
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2048
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2049
-                // if $ignore_this_model_obj was supplied, then for the query
2050
-                // on that model needs to be told to ignore $ignore_this_model_obj
2051
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2052
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2053
-                        array(
2054
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2055
-                                '!=',
2056
-                                $ignore_this_model_obj->ID(),
2057
-                            ),
2058
-                        ),
2059
-                    ));
2060
-                } else {
2061
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2062
-                }
2063
-                if ($related_model_objects) {
2064
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2065
-                    $is_blocked = true;
2066
-                }
2067
-            }
2068
-        }
2069
-        return $is_blocked;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2075
-     * @param array $row_results_for_deleting
2076
-     * @param bool  $allow_blocking
2077
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2078
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2079
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2080
-     *                 deleted. Example:
2081
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2082
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2083
-     *                 where each element is a group of columns and values that get deleted. Example:
2084
-     *                      array(
2085
-     *                          0 => array(
2086
-     *                              'Term_Relationship.object_id' => 1
2087
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2088
-     *                          ),
2089
-     *                          1 => array(
2090
-     *                              'Term_Relationship.object_id' => 1
2091
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2092
-     *                          )
2093
-     *                      )
2094
-     * @throws EE_Error
2095
-     */
2096
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2097
-    {
2098
-        $ids_to_delete_indexed_by_column = array();
2099
-        if ($this->has_primary_key_field()) {
2100
-            $primary_table = $this->_get_main_table();
2101
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2102
-            $other_tables = $this->_get_other_tables();
2103
-            $ids_to_delete_indexed_by_column = $query = array();
2104
-            foreach ($row_results_for_deleting as $item_to_delete) {
2105
-                // before we mark this item for deletion,
2106
-                // make sure there's no related entities blocking its deletion (if we're checking)
2107
-                if ($allow_blocking
2108
-                    && $this->delete_is_blocked_by_related_models(
2109
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2110
-                    )
2111
-                ) {
2112
-                    continue;
2113
-                }
2114
-                // primary table deletes
2115
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2116
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2117
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2118
-                }
2119
-            }
2120
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2121
-            $fields = $this->get_combined_primary_key_fields();
2122
-            foreach ($row_results_for_deleting as $item_to_delete) {
2123
-                $ids_to_delete_indexed_by_column_for_row = array();
2124
-                foreach ($fields as $cpk_field) {
2125
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2126
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2127
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2128
-                    }
2129
-                }
2130
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2131
-            }
2132
-        } else {
2133
-            // so there's no primary key and no combined key...
2134
-            // sorry, can't help you
2135
-            throw new EE_Error(
2136
-                sprintf(
2137
-                    __(
2138
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2139
-                        "event_espresso"
2140
-                    ),
2141
-                    get_class($this)
2142
-                )
2143
-            );
2144
-        }
2145
-        return $ids_to_delete_indexed_by_column;
2146
-    }
2147
-
2148
-
2149
-    /**
2150
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2151
-     * the corresponding query_part for the query performing the delete.
2152
-     *
2153
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2154
-     * @return string
2155
-     * @throws EE_Error
2156
-     */
2157
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2158
-    {
2159
-        $query_part = '';
2160
-        if (empty($ids_to_delete_indexed_by_column)) {
2161
-            return $query_part;
2162
-        } elseif ($this->has_primary_key_field()) {
2163
-            $query = array();
2164
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2165
-                // make sure we have unique $ids
2166
-                $ids = array_unique($ids);
2167
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2168
-            }
2169
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2170
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2171
-            $ways_to_identify_a_row = array();
2172
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2173
-                $values_for_each_combined_primary_key_for_a_row = array();
2174
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2175
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2176
-                }
2177
-                $ways_to_identify_a_row[] = '('
2178
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2179
-                                            . ')';
2180
-            }
2181
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2182
-        }
2183
-        return $query_part;
2184
-    }
2185
-
2186
-
2187
-
2188
-    /**
2189
-     * Gets the model field by the fully qualified name
2190
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2191
-     * @return EE_Model_Field_Base
2192
-     */
2193
-    public function get_field_by_column($qualified_column_name)
2194
-    {
2195
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2196
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2197
-                return $field_obj;
2198
-            }
2199
-        }
2200
-        throw new EE_Error(
2201
-            sprintf(
2202
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2203
-                $this->get_this_model_name(),
2204
-                $qualified_column_name
2205
-            )
2206
-        );
2207
-    }
2208
-
2209
-
2210
-
2211
-    /**
2212
-     * Count all the rows that match criteria the model query params.
2213
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2214
-     * column
2215
-     *
2216
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2217
-     * @param string $field_to_count field on model to count by (not column name)
2218
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2219
-     *                               that by the setting $distinct to TRUE;
2220
-     * @return int
2221
-     * @throws EE_Error
2222
-     */
2223
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2224
-    {
2225
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2226
-        if ($field_to_count) {
2227
-            $field_obj = $this->field_settings_for($field_to_count);
2228
-            $column_to_count = $field_obj->get_qualified_column();
2229
-        } elseif ($this->has_primary_key_field()) {
2230
-            $pk_field_obj = $this->get_primary_key_field();
2231
-            $column_to_count = $pk_field_obj->get_qualified_column();
2232
-        } else {
2233
-            // there's no primary key
2234
-            // if we're counting distinct items, and there's no primary key,
2235
-            // we need to list out the columns for distinction;
2236
-            // otherwise we can just use star
2237
-            if ($distinct) {
2238
-                $columns_to_use = array();
2239
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2240
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2241
-                }
2242
-                $column_to_count = implode(',', $columns_to_use);
2243
-            } else {
2244
-                $column_to_count = '*';
2245
-            }
2246
-        }
2247
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2248
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2249
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2250
-    }
2251
-
2252
-
2253
-
2254
-    /**
2255
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2256
-     *
2257
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2258
-     * @param string $field_to_sum name of field (array key in $_fields array)
2259
-     * @return float
2260
-     * @throws EE_Error
2261
-     */
2262
-    public function sum($query_params, $field_to_sum = null)
2263
-    {
2264
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2265
-        if ($field_to_sum) {
2266
-            $field_obj = $this->field_settings_for($field_to_sum);
2267
-        } else {
2268
-            $field_obj = $this->get_primary_key_field();
2269
-        }
2270
-        $column_to_count = $field_obj->get_qualified_column();
2271
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2272
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2273
-        $data_type = $field_obj->get_wpdb_data_type();
2274
-        if ($data_type === '%d' || $data_type === '%s') {
2275
-            return (float) $return_value;
2276
-        }
2277
-        // must be %f
2278
-        return (float) $return_value;
2279
-    }
2280
-
2281
-
2282
-
2283
-    /**
2284
-     * Just calls the specified method on $wpdb with the given arguments
2285
-     * Consolidates a little extra error handling code
2286
-     *
2287
-     * @param string $wpdb_method
2288
-     * @param array  $arguments_to_provide
2289
-     * @throws EE_Error
2290
-     * @global wpdb  $wpdb
2291
-     * @return mixed
2292
-     */
2293
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2294
-    {
2295
-        // if we're in maintenance mode level 2, DON'T run any queries
2296
-        // because level 2 indicates the database needs updating and
2297
-        // is probably out of sync with the code
2298
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2299
-            throw new EE_Error(sprintf(__(
2300
-                "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.",
2301
-                "event_espresso"
2302
-            )));
2303
-        }
2304
-        /** @type WPDB $wpdb */
2305
-        global $wpdb;
2306
-        if (! method_exists($wpdb, $wpdb_method)) {
2307
-            throw new EE_Error(sprintf(__(
2308
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2309
-                'event_espresso'
2310
-            ), $wpdb_method));
2311
-        }
2312
-        if (WP_DEBUG) {
2313
-            $old_show_errors_value = $wpdb->show_errors;
2314
-            $wpdb->show_errors(false);
2315
-        }
2316
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2317
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2318
-        if (WP_DEBUG) {
2319
-            $wpdb->show_errors($old_show_errors_value);
2320
-            if (! empty($wpdb->last_error)) {
2321
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2322
-            }
2323
-            if ($result === false) {
2324
-                throw new EE_Error(sprintf(__(
2325
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2326
-                    'event_espresso'
2327
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2328
-            }
2329
-        } elseif ($result === false) {
2330
-            EE_Error::add_error(
2331
-                sprintf(
2332
-                    __(
2333
-                        '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"',
2334
-                        'event_espresso'
2335
-                    ),
2336
-                    $wpdb_method,
2337
-                    var_export($arguments_to_provide, true),
2338
-                    $wpdb->last_error
2339
-                ),
2340
-                __FILE__,
2341
-                __FUNCTION__,
2342
-                __LINE__
2343
-            );
2344
-        }
2345
-        return $result;
2346
-    }
2347
-
2348
-
2349
-
2350
-    /**
2351
-     * Attempts to run the indicated WPDB method with the provided arguments,
2352
-     * and if there's an error tries to verify the DB is correct. Uses
2353
-     * the static property EEM_Base::$_db_verification_level to determine whether
2354
-     * we should try to fix the EE core db, the addons, or just give up
2355
-     *
2356
-     * @param string $wpdb_method
2357
-     * @param array  $arguments_to_provide
2358
-     * @return mixed
2359
-     */
2360
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2361
-    {
2362
-        /** @type WPDB $wpdb */
2363
-        global $wpdb;
2364
-        $wpdb->last_error = null;
2365
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2366
-        // was there an error running the query? but we don't care on new activations
2367
-        // (we're going to setup the DB anyway on new activations)
2368
-        if (($result === false || ! empty($wpdb->last_error))
2369
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2370
-        ) {
2371
-            switch (EEM_Base::$_db_verification_level) {
2372
-                case EEM_Base::db_verified_none:
2373
-                    // let's double-check core's DB
2374
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2375
-                    break;
2376
-                case EEM_Base::db_verified_core:
2377
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2378
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2379
-                    break;
2380
-                case EEM_Base::db_verified_addons:
2381
-                    // ummmm... you in trouble
2382
-                    return $result;
2383
-                    break;
2384
-            }
2385
-            if (! empty($error_message)) {
2386
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2387
-                trigger_error($error_message);
2388
-            }
2389
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2390
-        }
2391
-        return $result;
2392
-    }
2393
-
2394
-
2395
-
2396
-    /**
2397
-     * Verifies the EE core database is up-to-date and records that we've done it on
2398
-     * EEM_Base::$_db_verification_level
2399
-     *
2400
-     * @param string $wpdb_method
2401
-     * @param array  $arguments_to_provide
2402
-     * @return string
2403
-     */
2404
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2405
-    {
2406
-        /** @type WPDB $wpdb */
2407
-        global $wpdb;
2408
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2409
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2410
-        $error_message = sprintf(
2411
-            __(
2412
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2413
-                'event_espresso'
2414
-            ),
2415
-            $wpdb->last_error,
2416
-            $wpdb_method,
2417
-            wp_json_encode($arguments_to_provide)
2418
-        );
2419
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2420
-        return $error_message;
2421
-    }
2422
-
2423
-
2424
-
2425
-    /**
2426
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2427
-     * EEM_Base::$_db_verification_level
2428
-     *
2429
-     * @param $wpdb_method
2430
-     * @param $arguments_to_provide
2431
-     * @return string
2432
-     */
2433
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2434
-    {
2435
-        /** @type WPDB $wpdb */
2436
-        global $wpdb;
2437
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2438
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2439
-        $error_message = sprintf(
2440
-            __(
2441
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2442
-                'event_espresso'
2443
-            ),
2444
-            $wpdb->last_error,
2445
-            $wpdb_method,
2446
-            wp_json_encode($arguments_to_provide)
2447
-        );
2448
-        EE_System::instance()->initialize_addons();
2449
-        return $error_message;
2450
-    }
2451
-
2452
-
2453
-
2454
-    /**
2455
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2456
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2457
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2458
-     * ..."
2459
-     *
2460
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2461
-     * @return string
2462
-     */
2463
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2464
-    {
2465
-        return " FROM " . $model_query_info->get_full_join_sql() .
2466
-               $model_query_info->get_where_sql() .
2467
-               $model_query_info->get_group_by_sql() .
2468
-               $model_query_info->get_having_sql() .
2469
-               $model_query_info->get_order_by_sql() .
2470
-               $model_query_info->get_limit_sql();
2471
-    }
2472
-
2473
-
2474
-
2475
-    /**
2476
-     * Set to easily debug the next X queries ran from this model.
2477
-     *
2478
-     * @param int $count
2479
-     */
2480
-    public function show_next_x_db_queries($count = 1)
2481
-    {
2482
-        $this->_show_next_x_db_queries = $count;
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * @param $sql_query
2489
-     */
2490
-    public function show_db_query_if_previously_requested($sql_query)
2491
-    {
2492
-        if ($this->_show_next_x_db_queries > 0) {
2493
-            echo $sql_query;
2494
-            $this->_show_next_x_db_queries--;
2495
-        }
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2502
-     * There are the 3 cases:
2503
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2504
-     * $otherModelObject has no ID, it is first saved.
2505
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2506
-     * has no ID, it is first saved.
2507
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2508
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2509
-     * join table
2510
-     *
2511
-     * @param        EE_Base_Class                     /int $thisModelObject
2512
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2513
-     * @param string $relationName                     , key in EEM_Base::_relations
2514
-     *                                                 an attendee to a group, you also want to specify which role they
2515
-     *                                                 will have in that group. So you would use this parameter to
2516
-     *                                                 specify array('role-column-name'=>'role-id')
2517
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2518
-     *                                                 to for relation to methods that allow you to further specify
2519
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2520
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2521
-     *                                                 because these will be inserted in any new rows created as well.
2522
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2523
-     * @throws EE_Error
2524
-     */
2525
-    public function add_relationship_to(
2526
-        $id_or_obj,
2527
-        $other_model_id_or_obj,
2528
-        $relationName,
2529
-        $extra_join_model_fields_n_values = array()
2530
-    ) {
2531
-        $relation_obj = $this->related_settings_for($relationName);
2532
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2533
-    }
2534
-
2535
-
2536
-
2537
-    /**
2538
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2539
-     * There are the 3 cases:
2540
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2541
-     * error
2542
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2543
-     * an error
2544
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2545
-     *
2546
-     * @param        EE_Base_Class /int $id_or_obj
2547
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2548
-     * @param string $relationName key in EEM_Base::_relations
2549
-     * @return boolean of success
2550
-     * @throws EE_Error
2551
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2552
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2553
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2554
-     *                             because these will be inserted in any new rows created as well.
2555
-     */
2556
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2557
-    {
2558
-        $relation_obj = $this->related_settings_for($relationName);
2559
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2560
-    }
2561
-
2562
-
2563
-
2564
-    /**
2565
-     * @param mixed           $id_or_obj
2566
-     * @param string          $relationName
2567
-     * @param array           $where_query_params
2568
-     * @param EE_Base_Class[] objects to which relations were removed
2569
-     * @return \EE_Base_Class[]
2570
-     * @throws EE_Error
2571
-     */
2572
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2573
-    {
2574
-        $relation_obj = $this->related_settings_for($relationName);
2575
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2576
-    }
2577
-
2578
-
2579
-
2580
-    /**
2581
-     * Gets all the related items of the specified $model_name, using $query_params.
2582
-     * Note: by default, we remove the "default query params"
2583
-     * because we want to get even deleted items etc.
2584
-     *
2585
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2586
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2587
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2588
-     * @return EE_Base_Class[]
2589
-     * @throws EE_Error
2590
-     */
2591
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2592
-    {
2593
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2594
-        $relation_settings = $this->related_settings_for($model_name);
2595
-        return $relation_settings->get_all_related($model_obj, $query_params);
2596
-    }
2597
-
2598
-
2599
-
2600
-    /**
2601
-     * Deletes all the model objects across the relation indicated by $model_name
2602
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2603
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2604
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2605
-     *
2606
-     * @param EE_Base_Class|int|string $id_or_obj
2607
-     * @param string                   $model_name
2608
-     * @param array                    $query_params
2609
-     * @return int how many deleted
2610
-     * @throws EE_Error
2611
-     */
2612
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2613
-    {
2614
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2615
-        $relation_settings = $this->related_settings_for($model_name);
2616
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2617
-    }
2618
-
2619
-
2620
-
2621
-    /**
2622
-     * Hard deletes all the model objects across the relation indicated by $model_name
2623
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2624
-     * the model objects can't be hard deleted because of blocking related model objects,
2625
-     * just does a soft-delete on them instead.
2626
-     *
2627
-     * @param EE_Base_Class|int|string $id_or_obj
2628
-     * @param string                   $model_name
2629
-     * @param array                    $query_params
2630
-     * @return int how many deleted
2631
-     * @throws EE_Error
2632
-     */
2633
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2634
-    {
2635
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2636
-        $relation_settings = $this->related_settings_for($model_name);
2637
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2638
-    }
2639
-
2640
-
2641
-
2642
-    /**
2643
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2644
-     * unless otherwise specified in the $query_params
2645
-     *
2646
-     * @param        int             /EE_Base_Class $id_or_obj
2647
-     * @param string $model_name     like 'Event', or 'Registration'
2648
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2649
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2650
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2651
-     *                               that by the setting $distinct to TRUE;
2652
-     * @return int
2653
-     * @throws EE_Error
2654
-     */
2655
-    public function count_related(
2656
-        $id_or_obj,
2657
-        $model_name,
2658
-        $query_params = array(),
2659
-        $field_to_count = null,
2660
-        $distinct = false
2661
-    ) {
2662
-        $related_model = $this->get_related_model_obj($model_name);
2663
-        // we're just going to use the query params on the related model's normal get_all query,
2664
-        // except add a condition to say to match the current mod
2665
-        if (! isset($query_params['default_where_conditions'])) {
2666
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2667
-        }
2668
-        $this_model_name = $this->get_this_model_name();
2669
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2670
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2671
-        return $related_model->count($query_params, $field_to_count, $distinct);
2672
-    }
2673
-
2674
-
2675
-
2676
-    /**
2677
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2678
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2679
-     *
2680
-     * @param        int           /EE_Base_Class $id_or_obj
2681
-     * @param string $model_name   like 'Event', or 'Registration'
2682
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2683
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2684
-     * @return float
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2688
-    {
2689
-        $related_model = $this->get_related_model_obj($model_name);
2690
-        if (! is_array($query_params)) {
2691
-            EE_Error::doing_it_wrong(
2692
-                'EEM_Base::sum_related',
2693
-                sprintf(
2694
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2695
-                    gettype($query_params)
2696
-                ),
2697
-                '4.6.0'
2698
-            );
2699
-            $query_params = array();
2700
-        }
2701
-        // we're just going to use the query params on the related model's normal get_all query,
2702
-        // except add a condition to say to match the current mod
2703
-        if (! isset($query_params['default_where_conditions'])) {
2704
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2705
-        }
2706
-        $this_model_name = $this->get_this_model_name();
2707
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2708
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2709
-        return $related_model->sum($query_params, $field_to_sum);
2710
-    }
2711
-
2712
-
2713
-
2714
-    /**
2715
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2716
-     * $modelObject
2717
-     *
2718
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2719
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2720
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2721
-     * @return EE_Base_Class
2722
-     * @throws EE_Error
2723
-     */
2724
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2725
-    {
2726
-        $query_params['limit'] = 1;
2727
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2728
-        if ($results) {
2729
-            return array_shift($results);
2730
-        }
2731
-        return null;
2732
-    }
2733
-
2734
-
2735
-
2736
-    /**
2737
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2738
-     *
2739
-     * @return string
2740
-     */
2741
-    public function get_this_model_name()
2742
-    {
2743
-        return str_replace("EEM_", "", get_class($this));
2744
-    }
2745
-
2746
-
2747
-
2748
-    /**
2749
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2750
-     *
2751
-     * @return EE_Any_Foreign_Model_Name_Field
2752
-     * @throws EE_Error
2753
-     */
2754
-    public function get_field_containing_related_model_name()
2755
-    {
2756
-        foreach ($this->field_settings(true) as $field) {
2757
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2758
-                $field_with_model_name = $field;
2759
-            }
2760
-        }
2761
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2762
-            throw new EE_Error(sprintf(
2763
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2764
-                $this->get_this_model_name()
2765
-            ));
2766
-        }
2767
-        return $field_with_model_name;
2768
-    }
2769
-
2770
-
2771
-
2772
-    /**
2773
-     * Inserts a new entry into the database, for each table.
2774
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2775
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2776
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2777
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2778
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2779
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2780
-     *
2781
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2782
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2783
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2784
-     *                              of EEM_Base)
2785
-     * @return int|string new primary key on main table that got inserted
2786
-     * @throws EE_Error
2787
-     */
2788
-    public function insert($field_n_values)
2789
-    {
2790
-        /**
2791
-         * Filters the fields and their values before inserting an item using the models
2792
-         *
2793
-         * @param array    $fields_n_values keys are the fields and values are their new values
2794
-         * @param EEM_Base $model           the model used
2795
-         */
2796
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2797
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2798
-            $main_table = $this->_get_main_table();
2799
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2800
-            if ($new_id !== false) {
2801
-                foreach ($this->_get_other_tables() as $other_table) {
2802
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2803
-                }
2804
-            }
2805
-            /**
2806
-             * Done just after attempting to insert a new model object
2807
-             *
2808
-             * @param EEM_Base   $model           used
2809
-             * @param array      $fields_n_values fields and their values
2810
-             * @param int|string the              ID of the newly-inserted model object
2811
-             */
2812
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2813
-            return $new_id;
2814
-        }
2815
-        return false;
2816
-    }
2817
-
2818
-
2819
-
2820
-    /**
2821
-     * Checks that the result would satisfy the unique indexes on this model
2822
-     *
2823
-     * @param array  $field_n_values
2824
-     * @param string $action
2825
-     * @return boolean
2826
-     * @throws EE_Error
2827
-     */
2828
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2829
-    {
2830
-        foreach ($this->unique_indexes() as $index_name => $index) {
2831
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2832
-            if ($this->exists(array($uniqueness_where_params))) {
2833
-                EE_Error::add_error(
2834
-                    sprintf(
2835
-                        __(
2836
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2837
-                            "event_espresso"
2838
-                        ),
2839
-                        $action,
2840
-                        $this->_get_class_name(),
2841
-                        $index_name,
2842
-                        implode(",", $index->field_names()),
2843
-                        http_build_query($uniqueness_where_params)
2844
-                    ),
2845
-                    __FILE__,
2846
-                    __FUNCTION__,
2847
-                    __LINE__
2848
-                );
2849
-                return false;
2850
-            }
2851
-        }
2852
-        return true;
2853
-    }
2854
-
2855
-
2856
-
2857
-    /**
2858
-     * Checks the database for an item that conflicts (ie, if this item were
2859
-     * saved to the DB would break some uniqueness requirement, like a primary key
2860
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2861
-     * can be either an EE_Base_Class or an array of fields n values
2862
-     *
2863
-     * @param EE_Base_Class|array $obj_or_fields_array
2864
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2865
-     *                                                 when looking for conflicts
2866
-     *                                                 (ie, if false, we ignore the model object's primary key
2867
-     *                                                 when finding "conflicts". If true, it's also considered).
2868
-     *                                                 Only works for INT primary key,
2869
-     *                                                 STRING primary keys cannot be ignored
2870
-     * @throws EE_Error
2871
-     * @return EE_Base_Class|array
2872
-     */
2873
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2874
-    {
2875
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2876
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2877
-        } elseif (is_array($obj_or_fields_array)) {
2878
-            $fields_n_values = $obj_or_fields_array;
2879
-        } else {
2880
-            throw new EE_Error(
2881
-                sprintf(
2882
-                    __(
2883
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2884
-                        "event_espresso"
2885
-                    ),
2886
-                    get_class($this),
2887
-                    $obj_or_fields_array
2888
-                )
2889
-            );
2890
-        }
2891
-        $query_params = array();
2892
-        if ($this->has_primary_key_field()
2893
-            && ($include_primary_key
2894
-                || $this->get_primary_key_field()
2895
-                   instanceof
2896
-                   EE_Primary_Key_String_Field)
2897
-            && isset($fields_n_values[ $this->primary_key_name() ])
2898
-        ) {
2899
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2900
-        }
2901
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2902
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2903
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2904
-        }
2905
-        // if there is nothing to base this search on, then we shouldn't find anything
2906
-        if (empty($query_params)) {
2907
-            return array();
2908
-        }
2909
-        return $this->get_one($query_params);
2910
-    }
2911
-
2912
-
2913
-
2914
-    /**
2915
-     * Like count, but is optimized and returns a boolean instead of an int
2916
-     *
2917
-     * @param array $query_params
2918
-     * @return boolean
2919
-     * @throws EE_Error
2920
-     */
2921
-    public function exists($query_params)
2922
-    {
2923
-        $query_params['limit'] = 1;
2924
-        return $this->count($query_params) > 0;
2925
-    }
2926
-
2927
-
2928
-
2929
-    /**
2930
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2931
-     *
2932
-     * @param int|string $id
2933
-     * @return boolean
2934
-     * @throws EE_Error
2935
-     */
2936
-    public function exists_by_ID($id)
2937
-    {
2938
-        return $this->exists(
2939
-            array(
2940
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2941
-                array(
2942
-                    $this->primary_key_name() => $id,
2943
-                ),
2944
-            )
2945
-        );
2946
-    }
2947
-
2948
-
2949
-
2950
-    /**
2951
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2952
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2953
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2954
-     * on the main table)
2955
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2956
-     * cases where we want to call it directly rather than via insert().
2957
-     *
2958
-     * @access   protected
2959
-     * @param EE_Table_Base $table
2960
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2961
-     *                                       float
2962
-     * @param int           $new_id          for now we assume only int keys
2963
-     * @throws EE_Error
2964
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2965
-     * @return int ID of new row inserted, or FALSE on failure
2966
-     */
2967
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2968
-    {
2969
-        global $wpdb;
2970
-        $insertion_col_n_values = array();
2971
-        $format_for_insertion = array();
2972
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2973
-        foreach ($fields_on_table as $field_name => $field_obj) {
2974
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2975
-            if ($field_obj->is_auto_increment()) {
2976
-                continue;
2977
-            }
2978
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2979
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2980
-            if ($prepared_value !== null) {
2981
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2982
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2983
-            }
2984
-        }
2985
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2986
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2987
-            // so add the fk to the main table as a column
2988
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2989
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2990
-        }
2991
-        // insert the new entry
2992
-        $result = $this->_do_wpdb_query(
2993
-            'insert',
2994
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
2995
-        );
2996
-        if ($result === false) {
2997
-            return false;
2998
-        }
2999
-        // ok, now what do we return for the ID of the newly-inserted thing?
3000
-        if ($this->has_primary_key_field()) {
3001
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3002
-                return $wpdb->insert_id;
3003
-            }
3004
-            // it's not an auto-increment primary key, so
3005
-            // it must have been supplied
3006
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3007
-        }
3008
-        // we can't return a  primary key because there is none. instead return
3009
-        // a unique string indicating this model
3010
-        return $this->get_index_primary_key_string($fields_n_values);
3011
-    }
3012
-
3013
-
3014
-
3015
-    /**
3016
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3017
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3018
-     * and there is no default, we pass it along. WPDB will take care of it)
3019
-     *
3020
-     * @param EE_Model_Field_Base $field_obj
3021
-     * @param array               $fields_n_values
3022
-     * @return mixed string|int|float depending on what the table column will be expecting
3023
-     * @throws EE_Error
3024
-     */
3025
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3026
-    {
3027
-        // if this field doesn't allow nullable, don't allow it
3028
-        if (! $field_obj->is_nullable()
3029
-            && (
3030
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3031
-                || $fields_n_values[ $field_obj->get_name() ] === null
3032
-            )
3033
-        ) {
3034
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3035
-        }
3036
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3037
-            ? $fields_n_values[ $field_obj->get_name() ]
3038
-            : null;
3039
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3040
-    }
3041
-
3042
-
3043
-
3044
-    /**
3045
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3046
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3047
-     * the field's prepare_for_set() method.
3048
-     *
3049
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3050
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3051
-     *                                   top of file)
3052
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3053
-     *                                   $value is a custom selection
3054
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3055
-     */
3056
-    private function _prepare_value_for_use_in_db($value, $field)
3057
-    {
3058
-        if ($field && $field instanceof EE_Model_Field_Base) {
3059
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3060
-            switch ($this->_values_already_prepared_by_model_object) {
3061
-                /** @noinspection PhpMissingBreakStatementInspection */
3062
-                case self::not_prepared_by_model_object:
3063
-                    $value = $field->prepare_for_set($value);
3064
-                // purposefully left out "return"
3065
-                case self::prepared_by_model_object:
3066
-                    /** @noinspection SuspiciousAssignmentsInspection */
3067
-                    $value = $field->prepare_for_use_in_db($value);
3068
-                case self::prepared_for_use_in_db:
3069
-                    // leave the value alone
3070
-            }
3071
-            return $value;
3072
-            // phpcs:enable
3073
-        }
3074
-        return $value;
3075
-    }
3076
-
3077
-
3078
-
3079
-    /**
3080
-     * Returns the main table on this model
3081
-     *
3082
-     * @return EE_Primary_Table
3083
-     * @throws EE_Error
3084
-     */
3085
-    protected function _get_main_table()
3086
-    {
3087
-        foreach ($this->_tables as $table) {
3088
-            if ($table instanceof EE_Primary_Table) {
3089
-                return $table;
3090
-            }
3091
-        }
3092
-        throw new EE_Error(sprintf(__(
3093
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3094
-            'event_espresso'
3095
-        ), get_class($this)));
3096
-    }
3097
-
3098
-
3099
-
3100
-    /**
3101
-     * table
3102
-     * returns EE_Primary_Table table name
3103
-     *
3104
-     * @return string
3105
-     * @throws EE_Error
3106
-     */
3107
-    public function table()
3108
-    {
3109
-        return $this->_get_main_table()->get_table_name();
3110
-    }
3111
-
3112
-
3113
-
3114
-    /**
3115
-     * table
3116
-     * returns first EE_Secondary_Table table name
3117
-     *
3118
-     * @return string
3119
-     */
3120
-    public function second_table()
3121
-    {
3122
-        // grab second table from tables array
3123
-        $second_table = end($this->_tables);
3124
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * get_table_obj_by_alias
3131
-     * returns table name given it's alias
3132
-     *
3133
-     * @param string $table_alias
3134
-     * @return EE_Primary_Table | EE_Secondary_Table
3135
-     */
3136
-    public function get_table_obj_by_alias($table_alias = '')
3137
-    {
3138
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3139
-    }
3140
-
3141
-
3142
-
3143
-    /**
3144
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3145
-     *
3146
-     * @return EE_Secondary_Table[]
3147
-     */
3148
-    protected function _get_other_tables()
3149
-    {
3150
-        $other_tables = array();
3151
-        foreach ($this->_tables as $table_alias => $table) {
3152
-            if ($table instanceof EE_Secondary_Table) {
3153
-                $other_tables[ $table_alias ] = $table;
3154
-            }
3155
-        }
3156
-        return $other_tables;
3157
-    }
3158
-
3159
-
3160
-
3161
-    /**
3162
-     * Finds all the fields that correspond to the given table
3163
-     *
3164
-     * @param string $table_alias , array key in EEM_Base::_tables
3165
-     * @return EE_Model_Field_Base[]
3166
-     */
3167
-    public function _get_fields_for_table($table_alias)
3168
-    {
3169
-        return $this->_fields[ $table_alias ];
3170
-    }
3171
-
3172
-
3173
-
3174
-    /**
3175
-     * Recurses through all the where parameters, and finds all the related models we'll need
3176
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3177
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3178
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3179
-     * related Registration, Transaction, and Payment models.
3180
-     *
3181
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3182
-     * @return EE_Model_Query_Info_Carrier
3183
-     * @throws EE_Error
3184
-     */
3185
-    public function _extract_related_models_from_query($query_params)
3186
-    {
3187
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3188
-        if (array_key_exists(0, $query_params)) {
3189
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3190
-        }
3191
-        if (array_key_exists('group_by', $query_params)) {
3192
-            if (is_array($query_params['group_by'])) {
3193
-                $this->_extract_related_models_from_sub_params_array_values(
3194
-                    $query_params['group_by'],
3195
-                    $query_info_carrier,
3196
-                    'group_by'
3197
-                );
3198
-            } elseif (! empty($query_params['group_by'])) {
3199
-                $this->_extract_related_model_info_from_query_param(
3200
-                    $query_params['group_by'],
3201
-                    $query_info_carrier,
3202
-                    'group_by'
3203
-                );
3204
-            }
3205
-        }
3206
-        if (array_key_exists('having', $query_params)) {
3207
-            $this->_extract_related_models_from_sub_params_array_keys(
3208
-                $query_params[0],
3209
-                $query_info_carrier,
3210
-                'having'
3211
-            );
3212
-        }
3213
-        if (array_key_exists('order_by', $query_params)) {
3214
-            if (is_array($query_params['order_by'])) {
3215
-                $this->_extract_related_models_from_sub_params_array_keys(
3216
-                    $query_params['order_by'],
3217
-                    $query_info_carrier,
3218
-                    'order_by'
3219
-                );
3220
-            } elseif (! empty($query_params['order_by'])) {
3221
-                $this->_extract_related_model_info_from_query_param(
3222
-                    $query_params['order_by'],
3223
-                    $query_info_carrier,
3224
-                    'order_by'
3225
-                );
3226
-            }
3227
-        }
3228
-        if (array_key_exists('force_join', $query_params)) {
3229
-            $this->_extract_related_models_from_sub_params_array_values(
3230
-                $query_params['force_join'],
3231
-                $query_info_carrier,
3232
-                'force_join'
3233
-            );
3234
-        }
3235
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3236
-        return $query_info_carrier;
3237
-    }
3238
-
3239
-
3240
-
3241
-    /**
3242
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3243
-     *
3244
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3245
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3246
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3247
-     * @throws EE_Error
3248
-     * @return \EE_Model_Query_Info_Carrier
3249
-     */
3250
-    private function _extract_related_models_from_sub_params_array_keys(
3251
-        $sub_query_params,
3252
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253
-        $query_param_type
3254
-    ) {
3255
-        if (! empty($sub_query_params)) {
3256
-            $sub_query_params = (array) $sub_query_params;
3257
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3259
-                $this->_extract_related_model_info_from_query_param(
3260
-                    $param,
3261
-                    $model_query_info_carrier,
3262
-                    $query_param_type
3263
-                );
3264
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3265
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3266
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3267
-                // of array('Registration.TXN_ID'=>23)
3268
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3269
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3270
-                    if (! is_array($possibly_array_of_params)) {
3271
-                        throw new EE_Error(sprintf(
3272
-                            __(
3273
-                                "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'))",
3274
-                                "event_espresso"
3275
-                            ),
3276
-                            $param,
3277
-                            $possibly_array_of_params
3278
-                        ));
3279
-                    }
3280
-                    $this->_extract_related_models_from_sub_params_array_keys(
3281
-                        $possibly_array_of_params,
3282
-                        $model_query_info_carrier,
3283
-                        $query_param_type
3284
-                    );
3285
-                } elseif ($query_param_type === 0 // ie WHERE
3286
-                          && is_array($possibly_array_of_params)
3287
-                          && isset($possibly_array_of_params[2])
3288
-                          && $possibly_array_of_params[2] == true
3289
-                ) {
3290
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3291
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3292
-                    // from which we should extract query parameters!
3293
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3294
-                        throw new EE_Error(sprintf(__(
3295
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3296
-                            "event_espresso"
3297
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3298
-                    }
3299
-                    $this->_extract_related_model_info_from_query_param(
3300
-                        $possibly_array_of_params[1],
3301
-                        $model_query_info_carrier,
3302
-                        $query_param_type
3303
-                    );
3304
-                }
3305
-            }
3306
-        }
3307
-        return $model_query_info_carrier;
3308
-    }
3309
-
3310
-
3311
-
3312
-    /**
3313
-     * For extracting related models from forced_joins, where the array values contain the info about what
3314
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3315
-     *
3316
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3317
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3318
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3319
-     * @throws EE_Error
3320
-     * @return \EE_Model_Query_Info_Carrier
3321
-     */
3322
-    private function _extract_related_models_from_sub_params_array_values(
3323
-        $sub_query_params,
3324
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3325
-        $query_param_type
3326
-    ) {
3327
-        if (! empty($sub_query_params)) {
3328
-            if (! is_array($sub_query_params)) {
3329
-                throw new EE_Error(sprintf(
3330
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3331
-                    $sub_query_params
3332
-                ));
3333
-            }
3334
-            foreach ($sub_query_params as $param) {
3335
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3336
-                $this->_extract_related_model_info_from_query_param(
3337
-                    $param,
3338
-                    $model_query_info_carrier,
3339
-                    $query_param_type
3340
-                );
3341
-            }
3342
-        }
3343
-        return $model_query_info_carrier;
3344
-    }
3345
-
3346
-
3347
-    /**
3348
-     * Extract all the query parts from  model query params
3349
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3350
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3351
-     * but use them in a different order. Eg, we need to know what models we are querying
3352
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3353
-     * other models before we can finalize the where clause SQL.
3354
-     *
3355
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3356
-     * @throws EE_Error
3357
-     * @return EE_Model_Query_Info_Carrier
3358
-     * @throws ModelConfigurationException
3359
-     */
3360
-    public function _create_model_query_info_carrier($query_params)
3361
-    {
3362
-        if (! is_array($query_params)) {
3363
-            EE_Error::doing_it_wrong(
3364
-                'EEM_Base::_create_model_query_info_carrier',
3365
-                sprintf(
3366
-                    __(
3367
-                        '$query_params should be an array, you passed a variable of type %s',
3368
-                        'event_espresso'
3369
-                    ),
3370
-                    gettype($query_params)
3371
-                ),
3372
-                '4.6.0'
3373
-            );
3374
-            $query_params = array();
3375
-        }
3376
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3377
-        // first check if we should alter the query to account for caps or not
3378
-        // because the caps might require us to do extra joins
3379
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3380
-            $query_params[0] = array_replace_recursive(
3381
-                $query_params[0],
3382
-                $this->caps_where_conditions(
3383
-                    $query_params['caps']
3384
-                )
3385
-            );
3386
-        }
3387
-
3388
-        // check if we should alter the query to remove data related to protected
3389
-        // custom post types
3390
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3391
-            $where_param_key_for_password = $this->modelChainAndPassword();
3392
-            // only include if related to a cpt where no password has been set
3393
-            $query_params[0]['OR*nopassword'] = array(
3394
-                $where_param_key_for_password => '',
3395
-                $where_param_key_for_password . '*' => array('IS_NULL')
3396
-            );
3397
-        }
3398
-        $query_object = $this->_extract_related_models_from_query($query_params);
3399
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3400
-        foreach ($query_params[0] as $key => $value) {
3401
-            if (is_int($key)) {
3402
-                throw new EE_Error(
3403
-                    sprintf(
3404
-                        __(
3405
-                            "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.",
3406
-                            "event_espresso"
3407
-                        ),
3408
-                        $key,
3409
-                        var_export($value, true),
3410
-                        var_export($query_params, true),
3411
-                        get_class($this)
3412
-                    )
3413
-                );
3414
-            }
3415
-        }
3416
-        if (array_key_exists('default_where_conditions', $query_params)
3417
-            && ! empty($query_params['default_where_conditions'])
3418
-        ) {
3419
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3420
-        } else {
3421
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3422
-        }
3423
-        $query_params[0] = array_merge(
3424
-            $this->_get_default_where_conditions_for_models_in_query(
3425
-                $query_object,
3426
-                $use_default_where_conditions,
3427
-                $query_params[0]
3428
-            ),
3429
-            $query_params[0]
3430
-        );
3431
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3432
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3433
-        // So we need to setup a subquery and use that for the main join.
3434
-        // Note for now this only works on the primary table for the model.
3435
-        // So for instance, you could set the limit array like this:
3436
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3437
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3438
-            $query_object->set_main_model_join_sql(
3439
-                $this->_construct_limit_join_select(
3440
-                    $query_params['on_join_limit'][0],
3441
-                    $query_params['on_join_limit'][1]
3442
-                )
3443
-            );
3444
-        }
3445
-        // set limit
3446
-        if (array_key_exists('limit', $query_params)) {
3447
-            if (is_array($query_params['limit'])) {
3448
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3449
-                    $e = sprintf(
3450
-                        __(
3451
-                            "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)",
3452
-                            "event_espresso"
3453
-                        ),
3454
-                        http_build_query($query_params['limit'])
3455
-                    );
3456
-                    throw new EE_Error($e . "|" . $e);
3457
-                }
3458
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3459
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3460
-            } elseif (! empty($query_params['limit'])) {
3461
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3462
-            }
3463
-        }
3464
-        // set order by
3465
-        if (array_key_exists('order_by', $query_params)) {
3466
-            if (is_array($query_params['order_by'])) {
3467
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3468
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3469
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3470
-                if (array_key_exists('order', $query_params)) {
3471
-                    throw new EE_Error(
3472
-                        sprintf(
3473
-                            __(
3474
-                                "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 ",
3475
-                                "event_espresso"
3476
-                            ),
3477
-                            get_class($this),
3478
-                            implode(", ", array_keys($query_params['order_by'])),
3479
-                            implode(", ", $query_params['order_by']),
3480
-                            $query_params['order']
3481
-                        )
3482
-                    );
3483
-                }
3484
-                $this->_extract_related_models_from_sub_params_array_keys(
3485
-                    $query_params['order_by'],
3486
-                    $query_object,
3487
-                    'order_by'
3488
-                );
3489
-                // assume it's an array of fields to order by
3490
-                $order_array = array();
3491
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3492
-                    $order = $this->_extract_order($order);
3493
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3494
-                }
3495
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3496
-            } elseif (! empty($query_params['order_by'])) {
3497
-                $this->_extract_related_model_info_from_query_param(
3498
-                    $query_params['order_by'],
3499
-                    $query_object,
3500
-                    'order',
3501
-                    $query_params['order_by']
3502
-                );
3503
-                $order = isset($query_params['order'])
3504
-                    ? $this->_extract_order($query_params['order'])
3505
-                    : 'DESC';
3506
-                $query_object->set_order_by_sql(
3507
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3508
-                );
3509
-            }
3510
-        }
3511
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3512
-        if (! array_key_exists('order_by', $query_params)
3513
-            && array_key_exists('order', $query_params)
3514
-            && ! empty($query_params['order'])
3515
-        ) {
3516
-            $pk_field = $this->get_primary_key_field();
3517
-            $order = $this->_extract_order($query_params['order']);
3518
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3519
-        }
3520
-        // set group by
3521
-        if (array_key_exists('group_by', $query_params)) {
3522
-            if (is_array($query_params['group_by'])) {
3523
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3524
-                $group_by_array = array();
3525
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3526
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3527
-                }
3528
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3529
-            } elseif (! empty($query_params['group_by'])) {
3530
-                $query_object->set_group_by_sql(
3531
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3532
-                );
3533
-            }
3534
-        }
3535
-        // set having
3536
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3537
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3538
-        }
3539
-        // now, just verify they didn't pass anything wack
3540
-        foreach ($query_params as $query_key => $query_value) {
3541
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3542
-                throw new EE_Error(
3543
-                    sprintf(
3544
-                        __(
3545
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3546
-                            'event_espresso'
3547
-                        ),
3548
-                        $query_key,
3549
-                        get_class($this),
3550
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3551
-                        implode(',', $this->_allowed_query_params)
3552
-                    )
3553
-                );
3554
-            }
3555
-        }
3556
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3557
-        if (empty($main_model_join_sql)) {
3558
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3559
-        }
3560
-        return $query_object;
3561
-    }
3562
-
3563
-
3564
-
3565
-    /**
3566
-     * Gets the where conditions that should be imposed on the query based on the
3567
-     * context (eg reading frontend, backend, edit or delete).
3568
-     *
3569
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3570
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3571
-     * @throws EE_Error
3572
-     */
3573
-    public function caps_where_conditions($context = self::caps_read)
3574
-    {
3575
-        EEM_Base::verify_is_valid_cap_context($context);
3576
-        $cap_where_conditions = array();
3577
-        $cap_restrictions = $this->caps_missing($context);
3578
-        /**
3579
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3580
-         */
3581
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3582
-            $cap_where_conditions = array_replace_recursive(
3583
-                $cap_where_conditions,
3584
-                $restriction_if_no_cap->get_default_where_conditions()
3585
-            );
3586
-        }
3587
-        return apply_filters(
3588
-            'FHEE__EEM_Base__caps_where_conditions__return',
3589
-            $cap_where_conditions,
3590
-            $this,
3591
-            $context,
3592
-            $cap_restrictions
3593
-        );
3594
-    }
3595
-
3596
-
3597
-
3598
-    /**
3599
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3600
-     * otherwise throws an exception
3601
-     *
3602
-     * @param string $should_be_order_string
3603
-     * @return string either ASC, asc, DESC or desc
3604
-     * @throws EE_Error
3605
-     */
3606
-    private function _extract_order($should_be_order_string)
3607
-    {
3608
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3609
-            return $should_be_order_string;
3610
-        }
3611
-        throw new EE_Error(
3612
-            sprintf(
3613
-                __(
3614
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3615
-                    "event_espresso"
3616
-                ),
3617
-                get_class($this),
3618
-                $should_be_order_string
3619
-            )
3620
-        );
3621
-    }
3622
-
3623
-
3624
-
3625
-    /**
3626
-     * Looks at all the models which are included in this query, and asks each
3627
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3628
-     * so they can be merged
3629
-     *
3630
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3631
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3632
-     *                                                                  'none' means NO default where conditions will
3633
-     *                                                                  be used AT ALL during this query.
3634
-     *                                                                  'other_models_only' means default where
3635
-     *                                                                  conditions from other models will be used, but
3636
-     *                                                                  not for this primary model. 'all', the default,
3637
-     *                                                                  means default where conditions will apply as
3638
-     *                                                                  normal
3639
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3640
-     * @throws EE_Error
3641
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3642
-     */
3643
-    private function _get_default_where_conditions_for_models_in_query(
3644
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3645
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3646
-        $where_query_params = array()
3647
-    ) {
3648
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3649
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3650
-            throw new EE_Error(sprintf(
3651
-                __(
3652
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3653
-                    "event_espresso"
3654
-                ),
3655
-                $use_default_where_conditions,
3656
-                implode(", ", $allowed_used_default_where_conditions_values)
3657
-            ));
3658
-        }
3659
-        $universal_query_params = array();
3660
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3661
-            $universal_query_params = $this->_get_default_where_conditions();
3662
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3663
-            $universal_query_params = $this->_get_minimum_where_conditions();
3664
-        }
3665
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3666
-            $related_model = $this->get_related_model_obj($model_name);
3667
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3668
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3669
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3670
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3671
-            } else {
3672
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3673
-                continue;
3674
-            }
3675
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3676
-                $related_model_universal_where_params,
3677
-                $where_query_params,
3678
-                $related_model,
3679
-                $model_relation_path
3680
-            );
3681
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3682
-                $universal_query_params,
3683
-                $overrides
3684
-            );
3685
-        }
3686
-        return $universal_query_params;
3687
-    }
3688
-
3689
-
3690
-
3691
-    /**
3692
-     * Determines whether or not we should use default where conditions for the model in question
3693
-     * (this model, or other related models).
3694
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3695
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3696
-     * We should use default where conditions on related models when they requested to use default where conditions
3697
-     * on all models, or specifically just on other related models
3698
-     * @param      $default_where_conditions_value
3699
-     * @param bool $for_this_model false means this is for OTHER related models
3700
-     * @return bool
3701
-     */
3702
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3703
-    {
3704
-        return (
3705
-                   $for_this_model
3706
-                   && in_array(
3707
-                       $default_where_conditions_value,
3708
-                       array(
3709
-                           EEM_Base::default_where_conditions_all,
3710
-                           EEM_Base::default_where_conditions_this_only,
3711
-                           EEM_Base::default_where_conditions_minimum_others,
3712
-                       ),
3713
-                       true
3714
-                   )
3715
-               )
3716
-               || (
3717
-                   ! $for_this_model
3718
-                   && in_array(
3719
-                       $default_where_conditions_value,
3720
-                       array(
3721
-                           EEM_Base::default_where_conditions_all,
3722
-                           EEM_Base::default_where_conditions_others_only,
3723
-                       ),
3724
-                       true
3725
-                   )
3726
-               );
3727
-    }
3728
-
3729
-    /**
3730
-     * Determines whether or not we should use default minimum conditions for the model in question
3731
-     * (this model, or other related models).
3732
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3733
-     * where conditions.
3734
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3735
-     * on this model or others
3736
-     * @param      $default_where_conditions_value
3737
-     * @param bool $for_this_model false means this is for OTHER related models
3738
-     * @return bool
3739
-     */
3740
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3741
-    {
3742
-        return (
3743
-                   $for_this_model
3744
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3745
-               )
3746
-               || (
3747
-                   ! $for_this_model
3748
-                   && in_array(
3749
-                       $default_where_conditions_value,
3750
-                       array(
3751
-                           EEM_Base::default_where_conditions_minimum_others,
3752
-                           EEM_Base::default_where_conditions_minimum_all,
3753
-                       ),
3754
-                       true
3755
-                   )
3756
-               );
3757
-    }
3758
-
3759
-
3760
-    /**
3761
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3762
-     * then we also add a special where condition which allows for that model's primary key
3763
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3764
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3765
-     *
3766
-     * @param array    $default_where_conditions
3767
-     * @param array    $provided_where_conditions
3768
-     * @param EEM_Base $model
3769
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3770
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3771
-     * @throws EE_Error
3772
-     */
3773
-    private function _override_defaults_or_make_null_friendly(
3774
-        $default_where_conditions,
3775
-        $provided_where_conditions,
3776
-        $model,
3777
-        $model_relation_path
3778
-    ) {
3779
-        $null_friendly_where_conditions = array();
3780
-        $none_overridden = true;
3781
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3782
-        foreach ($default_where_conditions as $key => $val) {
3783
-            if (isset($provided_where_conditions[ $key ])) {
3784
-                $none_overridden = false;
3785
-            } else {
3786
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3787
-            }
3788
-        }
3789
-        if ($none_overridden && $default_where_conditions) {
3790
-            if ($model->has_primary_key_field()) {
3791
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3792
-                                                                                . "."
3793
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3794
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	private static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					__(
561
+						'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.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							__(
680
+								'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.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
+	 *                                        array( array(
852
+	 *                                        'OR'=>array(
853
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
+	 *                                        )
856
+	 *                                        ),
857
+	 *                                        'limit'=>10,
858
+	 *                                        'group_by'=>'TXN_ID'
859
+	 *                                        ));
860
+	 *                                        get all the answers to the question titled "shirt size" for event with id
861
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
+	 *                                        'Question.QST_display_text'=>'shirt size',
863
+	 *                                        'Registration.Event.EVT_ID'=>12
864
+	 *                                        ),
865
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
866
+	 *                                        ));
867
+	 * @throws EE_Error
868
+	 */
869
+	public function get_all($query_params = array())
870
+	{
871
+		if (isset($query_params['limit'])
872
+			&& ! isset($query_params['group_by'])
873
+		) {
874
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
+		}
876
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
+	}
878
+
879
+
880
+
881
+	/**
882
+	 * Modifies the query parameters so we only get back model objects
883
+	 * that "belong" to the current user
884
+	 *
885
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 */
888
+	public function alter_query_params_to_only_include_mine($query_params = array())
889
+	{
890
+		$wp_user_field_name = $this->wp_user_field_name();
891
+		if ($wp_user_field_name) {
892
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
+		}
894
+		return $query_params;
895
+	}
896
+
897
+
898
+
899
+	/**
900
+	 * Returns the name of the field's name that points to the WP_User table
901
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
+	 * foreign key to the WP_User table)
903
+	 *
904
+	 * @return string|boolean string on success, boolean false when there is no
905
+	 * foreign key to the WP_User table
906
+	 */
907
+	public function wp_user_field_name()
908
+	{
909
+		try {
910
+			if (! empty($this->_model_chain_to_wp_user)) {
911
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
+				$last_model_name = end($models_to_follow_to_wp_users);
913
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
+			} else {
916
+				$model_with_fk_to_wp_users = $this;
917
+				$model_chain_to_wp_user = '';
918
+			}
919
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
921
+		} catch (EE_Error $e) {
922
+			return false;
923
+		}
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
930
+	 * (or transiently-related model) has a foreign key to the wp_users table;
931
+	 * useful for finding if model objects of this type are 'owned' by the current user.
932
+	 * This is an empty string when the foreign key is on this model and when it isn't,
933
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
934
+	 * (or transiently-related model)
935
+	 *
936
+	 * @return string
937
+	 */
938
+	public function model_chain_to_wp_user()
939
+	{
940
+		return $this->_model_chain_to_wp_user;
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
+	 * like how registrations don't have a foreign key to wp_users, but the
948
+	 * events they are for are), or is unrelated to wp users.
949
+	 * generally available
950
+	 *
951
+	 * @return boolean
952
+	 */
953
+	public function is_owned()
954
+	{
955
+		if ($this->model_chain_to_wp_user()) {
956
+			return true;
957
+		}
958
+		try {
959
+			$this->get_foreign_key_to('WP_User');
960
+			return true;
961
+		} catch (EE_Error $e) {
962
+			return false;
963
+		}
964
+	}
965
+
966
+
967
+	/**
968
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
+	 * the model)
971
+	 *
972
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
976
+	 *                                  override this and set the select to "*", or a specific column name, like
977
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
+	 *                                  the aliases used to refer to this selection, and values are to be
980
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
+	 * @throws EE_Error
984
+	 * @throws InvalidArgumentException
985
+	 */
986
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
+	{
988
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
+		;
990
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
991
+		$select_expressions = $columns_to_select === null
992
+			? $this->_construct_default_select_sql($model_query_info)
993
+			: '';
994
+		if ($this->_custom_selections instanceof CustomSelects) {
995
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
+			$select_expressions .= $select_expressions
997
+				? ', ' . $custom_expressions
998
+				: $custom_expressions;
999
+		}
1000
+
1001
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
+	 * method of including extra select information.
1010
+	 *
1011
+	 * @param array             $query_params
1012
+	 * @param null|array|string $columns_to_select
1013
+	 * @return null|CustomSelects
1014
+	 * @throws InvalidArgumentException
1015
+	 */
1016
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
+	{
1018
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
+			return null;
1020
+		}
1021
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
+		return new CustomSelects($selects);
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1030
+	 * but you can use the model query params to more easily
1031
+	 * take care of joins, field preparation etc.
1032
+	 *
1033
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
+	}
1050
+
1051
+
1052
+
1053
+	/**
1054
+	 * For creating a custom select statement
1055
+	 *
1056
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
+	 *                                 SQL, and 1=>is the datatype
1059
+	 * @throws EE_Error
1060
+	 * @return string
1061
+	 */
1062
+	private function _construct_select_from_input($columns_to_select)
1063
+	{
1064
+		if (is_array($columns_to_select)) {
1065
+			$select_sql_array = array();
1066
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
+					throw new EE_Error(
1069
+						sprintf(
1070
+							__(
1071
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
+								'event_espresso'
1073
+							),
1074
+							$selection_and_datatype,
1075
+							$alias
1076
+						)
1077
+					);
1078
+				}
1079
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
+					throw new EE_Error(
1081
+						sprintf(
1082
+							esc_html__(
1083
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
+								'event_espresso'
1085
+							),
1086
+							$selection_and_datatype[1],
1087
+							$selection_and_datatype[0],
1088
+							$alias,
1089
+							implode(', ', $this->_valid_wpdb_data_types)
1090
+						)
1091
+					);
1092
+				}
1093
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
+			}
1095
+			$columns_to_select_string = implode(', ', $select_sql_array);
1096
+		} else {
1097
+			$columns_to_select_string = $columns_to_select;
1098
+		}
1099
+		return $columns_to_select_string;
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
+	 *
1107
+	 * @return string
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function primary_key_name()
1111
+	{
1112
+		return $this->get_primary_key_field()->get_name();
1113
+	}
1114
+
1115
+
1116
+
1117
+	/**
1118
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
+	 * If there is no primary key on this model, $id is treated as primary key string
1120
+	 *
1121
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1122
+	 * @return EE_Base_Class
1123
+	 */
1124
+	public function get_one_by_ID($id)
1125
+	{
1126
+		if ($this->get_from_entity_map($id)) {
1127
+			return $this->get_from_entity_map($id);
1128
+		}
1129
+		return $this->get_one(
1130
+			$this->alter_query_params_to_restrict_by_ID(
1131
+				$id,
1132
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
+			)
1134
+		);
1135
+	}
1136
+
1137
+
1138
+
1139
+	/**
1140
+	 * Alters query parameters to only get items with this ID are returned.
1141
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1142
+	 * or could just be a simple primary key ID
1143
+	 *
1144
+	 * @param int   $id
1145
+	 * @param array $query_params
1146
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1147
+	 * @throws EE_Error
1148
+	 */
1149
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1150
+	{
1151
+		if (! isset($query_params[0])) {
1152
+			$query_params[0] = array();
1153
+		}
1154
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1155
+		if ($conditions_from_id === null) {
1156
+			$query_params[0][ $this->primary_key_name() ] = $id;
1157
+		} else {
1158
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1159
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1160
+		}
1161
+		return $query_params;
1162
+	}
1163
+
1164
+
1165
+
1166
+	/**
1167
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1168
+	 * array. If no item is found, null is returned.
1169
+	 *
1170
+	 * @param array $query_params like EEM_Base's $query_params variable.
1171
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1172
+	 * @throws EE_Error
1173
+	 */
1174
+	public function get_one($query_params = array())
1175
+	{
1176
+		if (! is_array($query_params)) {
1177
+			EE_Error::doing_it_wrong(
1178
+				'EEM_Base::get_one',
1179
+				sprintf(
1180
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1181
+					gettype($query_params)
1182
+				),
1183
+				'4.6.0'
1184
+			);
1185
+			$query_params = array();
1186
+		}
1187
+		$query_params['limit'] = 1;
1188
+		$items = $this->get_all($query_params);
1189
+		if (empty($items)) {
1190
+			return null;
1191
+		}
1192
+		return array_shift($items);
1193
+	}
1194
+
1195
+
1196
+
1197
+	/**
1198
+	 * Returns the next x number of items in sequence from the given value as
1199
+	 * found in the database matching the given query conditions.
1200
+	 *
1201
+	 * @param mixed $current_field_value    Value used for the reference point.
1202
+	 * @param null  $field_to_order_by      What field is used for the
1203
+	 *                                      reference point.
1204
+	 * @param int   $limit                  How many to return.
1205
+	 * @param array $query_params           Extra conditions on the query.
1206
+	 * @param null  $columns_to_select      If left null, then an array of
1207
+	 *                                      EE_Base_Class objects is returned,
1208
+	 *                                      otherwise you can indicate just the
1209
+	 *                                      columns you want returned.
1210
+	 * @return EE_Base_Class[]|array
1211
+	 * @throws EE_Error
1212
+	 */
1213
+	public function next_x(
1214
+		$current_field_value,
1215
+		$field_to_order_by = null,
1216
+		$limit = 1,
1217
+		$query_params = array(),
1218
+		$columns_to_select = null
1219
+	) {
1220
+		return $this->_get_consecutive(
1221
+			$current_field_value,
1222
+			'>',
1223
+			$field_to_order_by,
1224
+			$limit,
1225
+			$query_params,
1226
+			$columns_to_select
1227
+		);
1228
+	}
1229
+
1230
+
1231
+
1232
+	/**
1233
+	 * Returns the previous x number of items in sequence from the given value
1234
+	 * as found in the database matching the given query conditions.
1235
+	 *
1236
+	 * @param mixed $current_field_value    Value used for the reference point.
1237
+	 * @param null  $field_to_order_by      What field is used for the
1238
+	 *                                      reference point.
1239
+	 * @param int   $limit                  How many to return.
1240
+	 * @param array $query_params           Extra conditions on the query.
1241
+	 * @param null  $columns_to_select      If left null, then an array of
1242
+	 *                                      EE_Base_Class objects is returned,
1243
+	 *                                      otherwise you can indicate just the
1244
+	 *                                      columns you want returned.
1245
+	 * @return EE_Base_Class[]|array
1246
+	 * @throws EE_Error
1247
+	 */
1248
+	public function previous_x(
1249
+		$current_field_value,
1250
+		$field_to_order_by = null,
1251
+		$limit = 1,
1252
+		$query_params = array(),
1253
+		$columns_to_select = null
1254
+	) {
1255
+		return $this->_get_consecutive(
1256
+			$current_field_value,
1257
+			'<',
1258
+			$field_to_order_by,
1259
+			$limit,
1260
+			$query_params,
1261
+			$columns_to_select
1262
+		);
1263
+	}
1264
+
1265
+
1266
+
1267
+	/**
1268
+	 * Returns the next item in sequence from the given value as found in the
1269
+	 * database matching the given query conditions.
1270
+	 *
1271
+	 * @param mixed $current_field_value    Value used for the reference point.
1272
+	 * @param null  $field_to_order_by      What field is used for the
1273
+	 *                                      reference point.
1274
+	 * @param array $query_params           Extra conditions on the query.
1275
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1276
+	 *                                      object is returned, otherwise you
1277
+	 *                                      can indicate just the columns you
1278
+	 *                                      want and a single array indexed by
1279
+	 *                                      the columns will be returned.
1280
+	 * @return EE_Base_Class|null|array()
1281
+	 * @throws EE_Error
1282
+	 */
1283
+	public function next(
1284
+		$current_field_value,
1285
+		$field_to_order_by = null,
1286
+		$query_params = array(),
1287
+		$columns_to_select = null
1288
+	) {
1289
+		$results = $this->_get_consecutive(
1290
+			$current_field_value,
1291
+			'>',
1292
+			$field_to_order_by,
1293
+			1,
1294
+			$query_params,
1295
+			$columns_to_select
1296
+		);
1297
+		return empty($results) ? null : reset($results);
1298
+	}
1299
+
1300
+
1301
+
1302
+	/**
1303
+	 * Returns the previous item in sequence from the given value as found in
1304
+	 * the database matching the given query conditions.
1305
+	 *
1306
+	 * @param mixed $current_field_value    Value used for the reference point.
1307
+	 * @param null  $field_to_order_by      What field is used for the
1308
+	 *                                      reference point.
1309
+	 * @param array $query_params           Extra conditions on the query.
1310
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1311
+	 *                                      object is returned, otherwise you
1312
+	 *                                      can indicate just the columns you
1313
+	 *                                      want and a single array indexed by
1314
+	 *                                      the columns will be returned.
1315
+	 * @return EE_Base_Class|null|array()
1316
+	 * @throws EE_Error
1317
+	 */
1318
+	public function previous(
1319
+		$current_field_value,
1320
+		$field_to_order_by = null,
1321
+		$query_params = array(),
1322
+		$columns_to_select = null
1323
+	) {
1324
+		$results = $this->_get_consecutive(
1325
+			$current_field_value,
1326
+			'<',
1327
+			$field_to_order_by,
1328
+			1,
1329
+			$query_params,
1330
+			$columns_to_select
1331
+		);
1332
+		return empty($results) ? null : reset($results);
1333
+	}
1334
+
1335
+
1336
+
1337
+	/**
1338
+	 * Returns the a consecutive number of items in sequence from the given
1339
+	 * value as found in the database matching the given query conditions.
1340
+	 *
1341
+	 * @param mixed  $current_field_value   Value used for the reference point.
1342
+	 * @param string $operand               What operand is used for the sequence.
1343
+	 * @param string $field_to_order_by     What field is used for the reference point.
1344
+	 * @param int    $limit                 How many to return.
1345
+	 * @param array  $query_params          Extra conditions on the query.
1346
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1347
+	 *                                      otherwise you can indicate just the columns you want returned.
1348
+	 * @return EE_Base_Class[]|array
1349
+	 * @throws EE_Error
1350
+	 */
1351
+	protected function _get_consecutive(
1352
+		$current_field_value,
1353
+		$operand = '>',
1354
+		$field_to_order_by = null,
1355
+		$limit = 1,
1356
+		$query_params = array(),
1357
+		$columns_to_select = null
1358
+	) {
1359
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1360
+		if (empty($field_to_order_by)) {
1361
+			if ($this->has_primary_key_field()) {
1362
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1363
+			} else {
1364
+				if (WP_DEBUG) {
1365
+					throw new EE_Error(__(
1366
+						'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).',
1367
+						'event_espresso'
1368
+					));
1369
+				}
1370
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1371
+				return array();
1372
+			}
1373
+		}
1374
+		if (! is_array($query_params)) {
1375
+			EE_Error::doing_it_wrong(
1376
+				'EEM_Base::_get_consecutive',
1377
+				sprintf(
1378
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1379
+					gettype($query_params)
1380
+				),
1381
+				'4.6.0'
1382
+			);
1383
+			$query_params = array();
1384
+		}
1385
+		// let's add the where query param for consecutive look up.
1386
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1387
+		$query_params['limit'] = $limit;
1388
+		// set direction
1389
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1390
+		$query_params['order_by'] = $operand === '>'
1391
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
+		if (empty($columns_to_select)) {
1395
+			return $this->get_all($query_params);
1396
+		}
1397
+		// getting just the fields
1398
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		// note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		// and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		// if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		// if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			throw new EE_Error(sprintf(__(
1469
+				'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.',
1470
+				'event_espresso'
1471
+			), $field_name));
1472
+		}
1473
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1474
+		// the field.
1475
+		$this->_timezone = $field_settings->get_timezone();
1476
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1477
+	}
1478
+
1479
+
1480
+
1481
+	/**
1482
+	 * This returns the current time in a format setup for a query on this model.
1483
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1484
+	 * it will return:
1485
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1486
+	 *  NOW
1487
+	 *  - or a unix timestamp (equivalent to time())
1488
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1489
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1490
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1491
+	 * @since 4.6.x
1492
+	 * @param string $field_name       The field the current time is needed for.
1493
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1494
+	 *                                 formatted string matching the set format for the field in the set timezone will
1495
+	 *                                 be returned.
1496
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1497
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1498
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1499
+	 *                                 exception is triggered.
1500
+	 */
1501
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1502
+	{
1503
+		$formats = $this->get_formats_for($field_name);
1504
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1505
+		if ($timestamp) {
1506
+			return $DateTime->format('U');
1507
+		}
1508
+		// not returning timestamp, so return formatted string in timezone.
1509
+		switch ($what) {
1510
+			case 'time':
1511
+				return $DateTime->format($formats[1]);
1512
+				break;
1513
+			case 'date':
1514
+				return $DateTime->format($formats[0]);
1515
+				break;
1516
+			default:
1517
+				return $DateTime->format(implode(' ', $formats));
1518
+				break;
1519
+		}
1520
+	}
1521
+
1522
+
1523
+
1524
+	/**
1525
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1526
+	 * for the model are.  Returns a DateTime object.
1527
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1528
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1529
+	 * ignored.
1530
+	 *
1531
+	 * @param string $field_name      The field being setup.
1532
+	 * @param string $timestring      The date time string being used.
1533
+	 * @param string $incoming_format The format for the time string.
1534
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1535
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1536
+	 *                                format is
1537
+	 *                                'U', this is ignored.
1538
+	 * @return DateTime
1539
+	 * @throws EE_Error
1540
+	 */
1541
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1542
+	{
1543
+		// just using this to ensure the timezone is set correctly internally
1544
+		$this->get_formats_for($field_name);
1545
+		// load EEH_DTT_Helper
1546
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1547
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1548
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1549
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1550
+	}
1551
+
1552
+
1553
+
1554
+	/**
1555
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1556
+	 *
1557
+	 * @return EE_Table_Base[]
1558
+	 */
1559
+	public function get_tables()
1560
+	{
1561
+		return $this->_tables;
1562
+	}
1563
+
1564
+
1565
+
1566
+	/**
1567
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1568
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1569
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1570
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1571
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1572
+	 * model object with EVT_ID = 1
1573
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1574
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1575
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1576
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1577
+	 * are not specified)
1578
+	 *
1579
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1580
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1581
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1582
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1583
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1584
+	 *                                         ID=34, we'd use this method as follows:
1585
+	 *                                         EEM_Transaction::instance()->update(
1586
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1587
+	 *                                         array(array('TXN_ID'=>34)));
1588
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1589
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1590
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1591
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1592
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1593
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1594
+	 *                                         TRUE, it is assumed that you've already called
1595
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1596
+	 *                                         malicious javascript. However, if
1597
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1598
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1599
+	 *                                         and every other field, before insertion. We provide this parameter
1600
+	 *                                         because model objects perform their prepare_for_set function on all
1601
+	 *                                         their values, and so don't need to be called again (and in many cases,
1602
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1603
+	 *                                         prepare_for_set method...)
1604
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1605
+	 *                                         in this model's entity map according to $fields_n_values that match
1606
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1607
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1608
+	 *                                         could get out-of-sync with the database
1609
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1610
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1611
+	 *                                         bad)
1612
+	 * @throws EE_Error
1613
+	 */
1614
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1615
+	{
1616
+		if (! is_array($query_params)) {
1617
+			EE_Error::doing_it_wrong(
1618
+				'EEM_Base::update',
1619
+				sprintf(
1620
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1621
+					gettype($query_params)
1622
+				),
1623
+				'4.6.0'
1624
+			);
1625
+			$query_params = array();
1626
+		}
1627
+		/**
1628
+		 * Action called before a model update call has been made.
1629
+		 *
1630
+		 * @param EEM_Base $model
1631
+		 * @param array    $fields_n_values the updated fields and their new values
1632
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1633
+		 */
1634
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1635
+		/**
1636
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1637
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1638
+		 *
1639
+		 * @param array    $fields_n_values fields and their new values
1640
+		 * @param EEM_Base $model           the model being queried
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		$fields_n_values = (array) apply_filters(
1644
+			'FHEE__EEM_Base__update__fields_n_values',
1645
+			$fields_n_values,
1646
+			$this,
1647
+			$query_params
1648
+		);
1649
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1650
+		// to do that, for each table, verify that it's PK isn't null.
1651
+		$tables = $this->get_tables();
1652
+		// 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
1653
+		// NOTE: we should make this code more efficient by NOT querying twice
1654
+		// before the real update, but that needs to first go through ALPHA testing
1655
+		// as it's dangerous. says Mike August 8 2014
1656
+		// we want to make sure the default_where strategy is ignored
1657
+		$this->_ignore_where_strategy = true;
1658
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1659
+		foreach ($wpdb_select_results as $wpdb_result) {
1660
+			// type cast stdClass as array
1661
+			$wpdb_result = (array) $wpdb_result;
1662
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1663
+			if ($this->has_primary_key_field()) {
1664
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1665
+			} else {
1666
+				// 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)
1667
+				$main_table_pk_value = null;
1668
+			}
1669
+			// 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
1670
+			// 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
1671
+			if (count($tables) > 1) {
1672
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1673
+				// in that table, and so we'll want to insert one
1674
+				foreach ($tables as $table_obj) {
1675
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1676
+					// if there is no private key for this table on the results, it means there's no entry
1677
+					// in this table, right? so insert a row in the current table, using any fields available
1678
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1679
+						   && $wpdb_result[ $this_table_pk_column ])
1680
+					) {
1681
+						$success = $this->_insert_into_specific_table(
1682
+							$table_obj,
1683
+							$fields_n_values,
1684
+							$main_table_pk_value
1685
+						);
1686
+						// if we died here, report the error
1687
+						if (! $success) {
1688
+							return false;
1689
+						}
1690
+					}
1691
+				}
1692
+			}
1693
+			//              //and now check that if we have cached any models by that ID on the model, that
1694
+			//              //they also get updated properly
1695
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1696
+			//              if( $model_object ){
1697
+			//                  foreach( $fields_n_values as $field => $value ){
1698
+			//                      $model_object->set($field, $value);
1699
+			// let's make sure default_where strategy is followed now
1700
+			$this->_ignore_where_strategy = false;
1701
+		}
1702
+		// if we want to keep model objects in sync, AND
1703
+		// if this wasn't called from a model object (to update itself)
1704
+		// then we want to make sure we keep all the existing
1705
+		// model objects in sync with the db
1706
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1707
+			if ($this->has_primary_key_field()) {
1708
+				$model_objs_affected_ids = $this->get_col($query_params);
1709
+			} else {
1710
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1711
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1712
+				$model_objs_affected_ids = array();
1713
+				foreach ($models_affected_key_columns as $row) {
1714
+					$combined_index_key = $this->get_index_primary_key_string($row);
1715
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1716
+				}
1717
+			}
1718
+			if (! $model_objs_affected_ids) {
1719
+				// wait wait wait- if nothing was affected let's stop here
1720
+				return 0;
1721
+			}
1722
+			foreach ($model_objs_affected_ids as $id) {
1723
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1724
+				if ($model_obj_in_entity_map) {
1725
+					foreach ($fields_n_values as $field => $new_value) {
1726
+						$model_obj_in_entity_map->set($field, $new_value);
1727
+					}
1728
+				}
1729
+			}
1730
+			// if there is a primary key on this model, we can now do a slight optimization
1731
+			if ($this->has_primary_key_field()) {
1732
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1733
+				$query_params = array(
1734
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1735
+					'limit'                    => count($model_objs_affected_ids),
1736
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1737
+				);
1738
+			}
1739
+		}
1740
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1741
+		$SQL = "UPDATE "
1742
+			   . $model_query_info->get_full_join_sql()
1743
+			   . " SET "
1744
+			   . $this->_construct_update_sql($fields_n_values)
1745
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1746
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1747
+		/**
1748
+		 * Action called after a model update call has been made.
1749
+		 *
1750
+		 * @param EEM_Base $model
1751
+		 * @param array    $fields_n_values the updated fields and their new values
1752
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1753
+		 * @param int      $rows_affected
1754
+		 */
1755
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1756
+		return $rows_affected;// how many supposedly got updated
1757
+	}
1758
+
1759
+
1760
+
1761
+	/**
1762
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1763
+	 * are teh values of the field specified (or by default the primary key field)
1764
+	 * that matched the query params. Note that you should pass the name of the
1765
+	 * model FIELD, not the database table's column name.
1766
+	 *
1767
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1768
+	 * @param string $field_to_select
1769
+	 * @return array just like $wpdb->get_col()
1770
+	 * @throws EE_Error
1771
+	 */
1772
+	public function get_col($query_params = array(), $field_to_select = null)
1773
+	{
1774
+		if ($field_to_select) {
1775
+			$field = $this->field_settings_for($field_to_select);
1776
+		} elseif ($this->has_primary_key_field()) {
1777
+			$field = $this->get_primary_key_field();
1778
+		} else {
1779
+			// no primary key, just grab the first column
1780
+			$field = reset($this->field_settings());
1781
+		}
1782
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1783
+		$select_expressions = $field->get_qualified_column();
1784
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1785
+		return $this->_do_wpdb_query('get_col', array($SQL));
1786
+	}
1787
+
1788
+
1789
+
1790
+	/**
1791
+	 * Returns a single column value for a single row from the database
1792
+	 *
1793
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1794
+	 * @param string $field_to_select @see EEM_Base::get_col()
1795
+	 * @return string
1796
+	 * @throws EE_Error
1797
+	 */
1798
+	public function get_var($query_params = array(), $field_to_select = null)
1799
+	{
1800
+		$query_params['limit'] = 1;
1801
+		$col = $this->get_col($query_params, $field_to_select);
1802
+		if (! empty($col)) {
1803
+			return reset($col);
1804
+		}
1805
+		return null;
1806
+	}
1807
+
1808
+
1809
+
1810
+	/**
1811
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1812
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1813
+	 * injection, but currently no further filtering is done
1814
+	 *
1815
+	 * @global      $wpdb
1816
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1817
+	 *                               be updated to in the DB
1818
+	 * @return string of SQL
1819
+	 * @throws EE_Error
1820
+	 */
1821
+	public function _construct_update_sql($fields_n_values)
1822
+	{
1823
+		/** @type WPDB $wpdb */
1824
+		global $wpdb;
1825
+		$cols_n_values = array();
1826
+		foreach ($fields_n_values as $field_name => $value) {
1827
+			$field_obj = $this->field_settings_for($field_name);
1828
+			// if the value is NULL, we want to assign the value to that.
1829
+			// wpdb->prepare doesn't really handle that properly
1830
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1831
+			$value_sql = $prepared_value === null ? 'NULL'
1832
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1833
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1834
+		}
1835
+		return implode(",", $cols_n_values);
1836
+	}
1837
+
1838
+
1839
+
1840
+	/**
1841
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1842
+	 * Performs a HARD delete, meaning the database row should always be removed,
1843
+	 * not just have a flag field on it switched
1844
+	 * Wrapper for EEM_Base::delete_permanently()
1845
+	 *
1846
+	 * @param mixed $id
1847
+	 * @param boolean $allow_blocking
1848
+	 * @return int the number of rows deleted
1849
+	 * @throws EE_Error
1850
+	 */
1851
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1852
+	{
1853
+		return $this->delete_permanently(
1854
+			array(
1855
+				array($this->get_primary_key_field()->get_name() => $id),
1856
+				'limit' => 1,
1857
+			),
1858
+			$allow_blocking
1859
+		);
1860
+	}
1861
+
1862
+
1863
+
1864
+	/**
1865
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1866
+	 * Wrapper for EEM_Base::delete()
1867
+	 *
1868
+	 * @param mixed $id
1869
+	 * @param boolean $allow_blocking
1870
+	 * @return int the number of rows deleted
1871
+	 * @throws EE_Error
1872
+	 */
1873
+	public function delete_by_ID($id, $allow_blocking = true)
1874
+	{
1875
+		return $this->delete(
1876
+			array(
1877
+				array($this->get_primary_key_field()->get_name() => $id),
1878
+				'limit' => 1,
1879
+			),
1880
+			$allow_blocking
1881
+		);
1882
+	}
1883
+
1884
+
1885
+
1886
+	/**
1887
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1888
+	 * meaning if the model has a field that indicates its been "trashed" or
1889
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1890
+	 *
1891
+	 * @see EEM_Base::delete_permanently
1892
+	 * @param array   $query_params
1893
+	 * @param boolean $allow_blocking
1894
+	 * @return int how many rows got deleted
1895
+	 * @throws EE_Error
1896
+	 */
1897
+	public function delete($query_params, $allow_blocking = true)
1898
+	{
1899
+		return $this->delete_permanently($query_params, $allow_blocking);
1900
+	}
1901
+
1902
+
1903
+
1904
+	/**
1905
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1906
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1907
+	 * as archived, not actually deleted
1908
+	 *
1909
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1910
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1911
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1912
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1913
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1914
+	 *                                DB
1915
+	 * @return int how many rows got deleted
1916
+	 * @throws EE_Error
1917
+	 */
1918
+	public function delete_permanently($query_params, $allow_blocking = true)
1919
+	{
1920
+		/**
1921
+		 * Action called just before performing a real deletion query. You can use the
1922
+		 * model and its $query_params to find exactly which items will be deleted
1923
+		 *
1924
+		 * @param EEM_Base $model
1925
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1926
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1927
+		 *                                 to block (prevent) this deletion
1928
+		 */
1929
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1930
+		// some MySQL databases may be running safe mode, which may restrict
1931
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1932
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1933
+		// to delete them
1934
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1935
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1936
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1937
+			$columns_and_ids_for_deleting
1938
+		);
1939
+		/**
1940
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1941
+		 *
1942
+		 * @param EEM_Base $this  The model instance being acted on.
1943
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1944
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1945
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1946
+		 *                                                  derived from the incoming query parameters.
1947
+		 *                                                  @see details on the structure of this array in the phpdocs
1948
+		 *                                                  for the `_get_ids_for_delete_method`
1949
+		 *
1950
+		 */
1951
+		do_action(
1952
+			'AHEE__EEM_Base__delete__before_query',
1953
+			$this,
1954
+			$query_params,
1955
+			$allow_blocking,
1956
+			$columns_and_ids_for_deleting
1957
+		);
1958
+		if ($deletion_where_query_part) {
1959
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1960
+			$table_aliases = array_keys($this->_tables);
1961
+			$SQL = "DELETE "
1962
+				   . implode(", ", $table_aliases)
1963
+				   . " FROM "
1964
+				   . $model_query_info->get_full_join_sql()
1965
+				   . " WHERE "
1966
+				   . $deletion_where_query_part;
1967
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1968
+		} else {
1969
+			$rows_deleted = 0;
1970
+		}
1971
+
1972
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1973
+		// there was no error with the delete query.
1974
+		if ($this->has_primary_key_field()
1975
+			&& $rows_deleted !== false
1976
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1977
+		) {
1978
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1979
+			foreach ($ids_for_removal as $id) {
1980
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1981
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1982
+				}
1983
+			}
1984
+
1985
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1986
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1987
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1988
+			// (although it is possible).
1989
+			// Note this can be skipped by using the provided filter and returning false.
1990
+			if (apply_filters(
1991
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1992
+				! $this instanceof EEM_Extra_Meta,
1993
+				$this
1994
+			)) {
1995
+				EEM_Extra_Meta::instance()->delete_permanently(array(
1996
+					0 => array(
1997
+						'EXM_type' => $this->get_this_model_name(),
1998
+						'OBJ_ID'   => array(
1999
+							'IN',
2000
+							$ids_for_removal
2001
+						)
2002
+					)
2003
+				));
2004
+			}
2005
+		}
2006
+
2007
+		/**
2008
+		 * Action called just after performing a real deletion query. Although at this point the
2009
+		 * items should have been deleted
2010
+		 *
2011
+		 * @param EEM_Base $model
2012
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2013
+		 * @param int      $rows_deleted
2014
+		 */
2015
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2016
+		return $rows_deleted;// how many supposedly got deleted
2017
+	}
2018
+
2019
+
2020
+
2021
+	/**
2022
+	 * Checks all the relations that throw error messages when there are blocking related objects
2023
+	 * for related model objects. If there are any related model objects on those relations,
2024
+	 * adds an EE_Error, and return true
2025
+	 *
2026
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2027
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2028
+	 *                                                 should be ignored when determining whether there are related
2029
+	 *                                                 model objects which block this model object's deletion. Useful
2030
+	 *                                                 if you know A is related to B and are considering deleting A,
2031
+	 *                                                 but want to see if A has any other objects blocking its deletion
2032
+	 *                                                 before removing the relation between A and B
2033
+	 * @return boolean
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2037
+	{
2038
+		// first, if $ignore_this_model_obj was supplied, get its model
2039
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2040
+			$ignored_model = $ignore_this_model_obj->get_model();
2041
+		} else {
2042
+			$ignored_model = null;
2043
+		}
2044
+		// now check all the relations of $this_model_obj_or_id and see if there
2045
+		// are any related model objects blocking it?
2046
+		$is_blocked = false;
2047
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2048
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2049
+				// if $ignore_this_model_obj was supplied, then for the query
2050
+				// on that model needs to be told to ignore $ignore_this_model_obj
2051
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2052
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2053
+						array(
2054
+							$ignored_model->get_primary_key_field()->get_name() => array(
2055
+								'!=',
2056
+								$ignore_this_model_obj->ID(),
2057
+							),
2058
+						),
2059
+					));
2060
+				} else {
2061
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2062
+				}
2063
+				if ($related_model_objects) {
2064
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2065
+					$is_blocked = true;
2066
+				}
2067
+			}
2068
+		}
2069
+		return $is_blocked;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2075
+	 * @param array $row_results_for_deleting
2076
+	 * @param bool  $allow_blocking
2077
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2078
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2079
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2080
+	 *                 deleted. Example:
2081
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2082
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2083
+	 *                 where each element is a group of columns and values that get deleted. Example:
2084
+	 *                      array(
2085
+	 *                          0 => array(
2086
+	 *                              'Term_Relationship.object_id' => 1
2087
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2088
+	 *                          ),
2089
+	 *                          1 => array(
2090
+	 *                              'Term_Relationship.object_id' => 1
2091
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2092
+	 *                          )
2093
+	 *                      )
2094
+	 * @throws EE_Error
2095
+	 */
2096
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2097
+	{
2098
+		$ids_to_delete_indexed_by_column = array();
2099
+		if ($this->has_primary_key_field()) {
2100
+			$primary_table = $this->_get_main_table();
2101
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2102
+			$other_tables = $this->_get_other_tables();
2103
+			$ids_to_delete_indexed_by_column = $query = array();
2104
+			foreach ($row_results_for_deleting as $item_to_delete) {
2105
+				// before we mark this item for deletion,
2106
+				// make sure there's no related entities blocking its deletion (if we're checking)
2107
+				if ($allow_blocking
2108
+					&& $this->delete_is_blocked_by_related_models(
2109
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2110
+					)
2111
+				) {
2112
+					continue;
2113
+				}
2114
+				// primary table deletes
2115
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2116
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2117
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2118
+				}
2119
+			}
2120
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2121
+			$fields = $this->get_combined_primary_key_fields();
2122
+			foreach ($row_results_for_deleting as $item_to_delete) {
2123
+				$ids_to_delete_indexed_by_column_for_row = array();
2124
+				foreach ($fields as $cpk_field) {
2125
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2126
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2127
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2128
+					}
2129
+				}
2130
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2131
+			}
2132
+		} else {
2133
+			// so there's no primary key and no combined key...
2134
+			// sorry, can't help you
2135
+			throw new EE_Error(
2136
+				sprintf(
2137
+					__(
2138
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2139
+						"event_espresso"
2140
+					),
2141
+					get_class($this)
2142
+				)
2143
+			);
2144
+		}
2145
+		return $ids_to_delete_indexed_by_column;
2146
+	}
2147
+
2148
+
2149
+	/**
2150
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2151
+	 * the corresponding query_part for the query performing the delete.
2152
+	 *
2153
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2154
+	 * @return string
2155
+	 * @throws EE_Error
2156
+	 */
2157
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2158
+	{
2159
+		$query_part = '';
2160
+		if (empty($ids_to_delete_indexed_by_column)) {
2161
+			return $query_part;
2162
+		} elseif ($this->has_primary_key_field()) {
2163
+			$query = array();
2164
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2165
+				// make sure we have unique $ids
2166
+				$ids = array_unique($ids);
2167
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2168
+			}
2169
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2170
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2171
+			$ways_to_identify_a_row = array();
2172
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2173
+				$values_for_each_combined_primary_key_for_a_row = array();
2174
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2175
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2176
+				}
2177
+				$ways_to_identify_a_row[] = '('
2178
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2179
+											. ')';
2180
+			}
2181
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2182
+		}
2183
+		return $query_part;
2184
+	}
2185
+
2186
+
2187
+
2188
+	/**
2189
+	 * Gets the model field by the fully qualified name
2190
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2191
+	 * @return EE_Model_Field_Base
2192
+	 */
2193
+	public function get_field_by_column($qualified_column_name)
2194
+	{
2195
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2196
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2197
+				return $field_obj;
2198
+			}
2199
+		}
2200
+		throw new EE_Error(
2201
+			sprintf(
2202
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2203
+				$this->get_this_model_name(),
2204
+				$qualified_column_name
2205
+			)
2206
+		);
2207
+	}
2208
+
2209
+
2210
+
2211
+	/**
2212
+	 * Count all the rows that match criteria the model query params.
2213
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2214
+	 * column
2215
+	 *
2216
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2217
+	 * @param string $field_to_count field on model to count by (not column name)
2218
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2219
+	 *                               that by the setting $distinct to TRUE;
2220
+	 * @return int
2221
+	 * @throws EE_Error
2222
+	 */
2223
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2224
+	{
2225
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2226
+		if ($field_to_count) {
2227
+			$field_obj = $this->field_settings_for($field_to_count);
2228
+			$column_to_count = $field_obj->get_qualified_column();
2229
+		} elseif ($this->has_primary_key_field()) {
2230
+			$pk_field_obj = $this->get_primary_key_field();
2231
+			$column_to_count = $pk_field_obj->get_qualified_column();
2232
+		} else {
2233
+			// there's no primary key
2234
+			// if we're counting distinct items, and there's no primary key,
2235
+			// we need to list out the columns for distinction;
2236
+			// otherwise we can just use star
2237
+			if ($distinct) {
2238
+				$columns_to_use = array();
2239
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2240
+					$columns_to_use[] = $field_obj->get_qualified_column();
2241
+				}
2242
+				$column_to_count = implode(',', $columns_to_use);
2243
+			} else {
2244
+				$column_to_count = '*';
2245
+			}
2246
+		}
2247
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2248
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2249
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2250
+	}
2251
+
2252
+
2253
+
2254
+	/**
2255
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2256
+	 *
2257
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2258
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2259
+	 * @return float
2260
+	 * @throws EE_Error
2261
+	 */
2262
+	public function sum($query_params, $field_to_sum = null)
2263
+	{
2264
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2265
+		if ($field_to_sum) {
2266
+			$field_obj = $this->field_settings_for($field_to_sum);
2267
+		} else {
2268
+			$field_obj = $this->get_primary_key_field();
2269
+		}
2270
+		$column_to_count = $field_obj->get_qualified_column();
2271
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2272
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2273
+		$data_type = $field_obj->get_wpdb_data_type();
2274
+		if ($data_type === '%d' || $data_type === '%s') {
2275
+			return (float) $return_value;
2276
+		}
2277
+		// must be %f
2278
+		return (float) $return_value;
2279
+	}
2280
+
2281
+
2282
+
2283
+	/**
2284
+	 * Just calls the specified method on $wpdb with the given arguments
2285
+	 * Consolidates a little extra error handling code
2286
+	 *
2287
+	 * @param string $wpdb_method
2288
+	 * @param array  $arguments_to_provide
2289
+	 * @throws EE_Error
2290
+	 * @global wpdb  $wpdb
2291
+	 * @return mixed
2292
+	 */
2293
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2294
+	{
2295
+		// if we're in maintenance mode level 2, DON'T run any queries
2296
+		// because level 2 indicates the database needs updating and
2297
+		// is probably out of sync with the code
2298
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2299
+			throw new EE_Error(sprintf(__(
2300
+				"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.",
2301
+				"event_espresso"
2302
+			)));
2303
+		}
2304
+		/** @type WPDB $wpdb */
2305
+		global $wpdb;
2306
+		if (! method_exists($wpdb, $wpdb_method)) {
2307
+			throw new EE_Error(sprintf(__(
2308
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2309
+				'event_espresso'
2310
+			), $wpdb_method));
2311
+		}
2312
+		if (WP_DEBUG) {
2313
+			$old_show_errors_value = $wpdb->show_errors;
2314
+			$wpdb->show_errors(false);
2315
+		}
2316
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2317
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2318
+		if (WP_DEBUG) {
2319
+			$wpdb->show_errors($old_show_errors_value);
2320
+			if (! empty($wpdb->last_error)) {
2321
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2322
+			}
2323
+			if ($result === false) {
2324
+				throw new EE_Error(sprintf(__(
2325
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2326
+					'event_espresso'
2327
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2328
+			}
2329
+		} elseif ($result === false) {
2330
+			EE_Error::add_error(
2331
+				sprintf(
2332
+					__(
2333
+						'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"',
2334
+						'event_espresso'
2335
+					),
2336
+					$wpdb_method,
2337
+					var_export($arguments_to_provide, true),
2338
+					$wpdb->last_error
2339
+				),
2340
+				__FILE__,
2341
+				__FUNCTION__,
2342
+				__LINE__
2343
+			);
2344
+		}
2345
+		return $result;
2346
+	}
2347
+
2348
+
2349
+
2350
+	/**
2351
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2352
+	 * and if there's an error tries to verify the DB is correct. Uses
2353
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2354
+	 * we should try to fix the EE core db, the addons, or just give up
2355
+	 *
2356
+	 * @param string $wpdb_method
2357
+	 * @param array  $arguments_to_provide
2358
+	 * @return mixed
2359
+	 */
2360
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2361
+	{
2362
+		/** @type WPDB $wpdb */
2363
+		global $wpdb;
2364
+		$wpdb->last_error = null;
2365
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2366
+		// was there an error running the query? but we don't care on new activations
2367
+		// (we're going to setup the DB anyway on new activations)
2368
+		if (($result === false || ! empty($wpdb->last_error))
2369
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2370
+		) {
2371
+			switch (EEM_Base::$_db_verification_level) {
2372
+				case EEM_Base::db_verified_none:
2373
+					// let's double-check core's DB
2374
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2375
+					break;
2376
+				case EEM_Base::db_verified_core:
2377
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2378
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2379
+					break;
2380
+				case EEM_Base::db_verified_addons:
2381
+					// ummmm... you in trouble
2382
+					return $result;
2383
+					break;
2384
+			}
2385
+			if (! empty($error_message)) {
2386
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2387
+				trigger_error($error_message);
2388
+			}
2389
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2390
+		}
2391
+		return $result;
2392
+	}
2393
+
2394
+
2395
+
2396
+	/**
2397
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2398
+	 * EEM_Base::$_db_verification_level
2399
+	 *
2400
+	 * @param string $wpdb_method
2401
+	 * @param array  $arguments_to_provide
2402
+	 * @return string
2403
+	 */
2404
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2405
+	{
2406
+		/** @type WPDB $wpdb */
2407
+		global $wpdb;
2408
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2409
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2410
+		$error_message = sprintf(
2411
+			__(
2412
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2413
+				'event_espresso'
2414
+			),
2415
+			$wpdb->last_error,
2416
+			$wpdb_method,
2417
+			wp_json_encode($arguments_to_provide)
2418
+		);
2419
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2420
+		return $error_message;
2421
+	}
2422
+
2423
+
2424
+
2425
+	/**
2426
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2427
+	 * EEM_Base::$_db_verification_level
2428
+	 *
2429
+	 * @param $wpdb_method
2430
+	 * @param $arguments_to_provide
2431
+	 * @return string
2432
+	 */
2433
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2434
+	{
2435
+		/** @type WPDB $wpdb */
2436
+		global $wpdb;
2437
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2438
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2439
+		$error_message = sprintf(
2440
+			__(
2441
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2442
+				'event_espresso'
2443
+			),
2444
+			$wpdb->last_error,
2445
+			$wpdb_method,
2446
+			wp_json_encode($arguments_to_provide)
2447
+		);
2448
+		EE_System::instance()->initialize_addons();
2449
+		return $error_message;
2450
+	}
2451
+
2452
+
2453
+
2454
+	/**
2455
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2456
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2457
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2458
+	 * ..."
2459
+	 *
2460
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2461
+	 * @return string
2462
+	 */
2463
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2464
+	{
2465
+		return " FROM " . $model_query_info->get_full_join_sql() .
2466
+			   $model_query_info->get_where_sql() .
2467
+			   $model_query_info->get_group_by_sql() .
2468
+			   $model_query_info->get_having_sql() .
2469
+			   $model_query_info->get_order_by_sql() .
2470
+			   $model_query_info->get_limit_sql();
2471
+	}
2472
+
2473
+
2474
+
2475
+	/**
2476
+	 * Set to easily debug the next X queries ran from this model.
2477
+	 *
2478
+	 * @param int $count
2479
+	 */
2480
+	public function show_next_x_db_queries($count = 1)
2481
+	{
2482
+		$this->_show_next_x_db_queries = $count;
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * @param $sql_query
2489
+	 */
2490
+	public function show_db_query_if_previously_requested($sql_query)
2491
+	{
2492
+		if ($this->_show_next_x_db_queries > 0) {
2493
+			echo $sql_query;
2494
+			$this->_show_next_x_db_queries--;
2495
+		}
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2502
+	 * There are the 3 cases:
2503
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2504
+	 * $otherModelObject has no ID, it is first saved.
2505
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2506
+	 * has no ID, it is first saved.
2507
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2508
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2509
+	 * join table
2510
+	 *
2511
+	 * @param        EE_Base_Class                     /int $thisModelObject
2512
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2513
+	 * @param string $relationName                     , key in EEM_Base::_relations
2514
+	 *                                                 an attendee to a group, you also want to specify which role they
2515
+	 *                                                 will have in that group. So you would use this parameter to
2516
+	 *                                                 specify array('role-column-name'=>'role-id')
2517
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2518
+	 *                                                 to for relation to methods that allow you to further specify
2519
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2520
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2521
+	 *                                                 because these will be inserted in any new rows created as well.
2522
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2523
+	 * @throws EE_Error
2524
+	 */
2525
+	public function add_relationship_to(
2526
+		$id_or_obj,
2527
+		$other_model_id_or_obj,
2528
+		$relationName,
2529
+		$extra_join_model_fields_n_values = array()
2530
+	) {
2531
+		$relation_obj = $this->related_settings_for($relationName);
2532
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2533
+	}
2534
+
2535
+
2536
+
2537
+	/**
2538
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2539
+	 * There are the 3 cases:
2540
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2541
+	 * error
2542
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2543
+	 * an error
2544
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2545
+	 *
2546
+	 * @param        EE_Base_Class /int $id_or_obj
2547
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2548
+	 * @param string $relationName key in EEM_Base::_relations
2549
+	 * @return boolean of success
2550
+	 * @throws EE_Error
2551
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2552
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2553
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2554
+	 *                             because these will be inserted in any new rows created as well.
2555
+	 */
2556
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2557
+	{
2558
+		$relation_obj = $this->related_settings_for($relationName);
2559
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2560
+	}
2561
+
2562
+
2563
+
2564
+	/**
2565
+	 * @param mixed           $id_or_obj
2566
+	 * @param string          $relationName
2567
+	 * @param array           $where_query_params
2568
+	 * @param EE_Base_Class[] objects to which relations were removed
2569
+	 * @return \EE_Base_Class[]
2570
+	 * @throws EE_Error
2571
+	 */
2572
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2573
+	{
2574
+		$relation_obj = $this->related_settings_for($relationName);
2575
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2576
+	}
2577
+
2578
+
2579
+
2580
+	/**
2581
+	 * Gets all the related items of the specified $model_name, using $query_params.
2582
+	 * Note: by default, we remove the "default query params"
2583
+	 * because we want to get even deleted items etc.
2584
+	 *
2585
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2586
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2587
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2588
+	 * @return EE_Base_Class[]
2589
+	 * @throws EE_Error
2590
+	 */
2591
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2592
+	{
2593
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2594
+		$relation_settings = $this->related_settings_for($model_name);
2595
+		return $relation_settings->get_all_related($model_obj, $query_params);
2596
+	}
2597
+
2598
+
2599
+
2600
+	/**
2601
+	 * Deletes all the model objects across the relation indicated by $model_name
2602
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2603
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2604
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2605
+	 *
2606
+	 * @param EE_Base_Class|int|string $id_or_obj
2607
+	 * @param string                   $model_name
2608
+	 * @param array                    $query_params
2609
+	 * @return int how many deleted
2610
+	 * @throws EE_Error
2611
+	 */
2612
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2613
+	{
2614
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2615
+		$relation_settings = $this->related_settings_for($model_name);
2616
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2617
+	}
2618
+
2619
+
2620
+
2621
+	/**
2622
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2623
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2624
+	 * the model objects can't be hard deleted because of blocking related model objects,
2625
+	 * just does a soft-delete on them instead.
2626
+	 *
2627
+	 * @param EE_Base_Class|int|string $id_or_obj
2628
+	 * @param string                   $model_name
2629
+	 * @param array                    $query_params
2630
+	 * @return int how many deleted
2631
+	 * @throws EE_Error
2632
+	 */
2633
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2634
+	{
2635
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2636
+		$relation_settings = $this->related_settings_for($model_name);
2637
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2638
+	}
2639
+
2640
+
2641
+
2642
+	/**
2643
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2644
+	 * unless otherwise specified in the $query_params
2645
+	 *
2646
+	 * @param        int             /EE_Base_Class $id_or_obj
2647
+	 * @param string $model_name     like 'Event', or 'Registration'
2648
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2649
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2650
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2651
+	 *                               that by the setting $distinct to TRUE;
2652
+	 * @return int
2653
+	 * @throws EE_Error
2654
+	 */
2655
+	public function count_related(
2656
+		$id_or_obj,
2657
+		$model_name,
2658
+		$query_params = array(),
2659
+		$field_to_count = null,
2660
+		$distinct = false
2661
+	) {
2662
+		$related_model = $this->get_related_model_obj($model_name);
2663
+		// we're just going to use the query params on the related model's normal get_all query,
2664
+		// except add a condition to say to match the current mod
2665
+		if (! isset($query_params['default_where_conditions'])) {
2666
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2667
+		}
2668
+		$this_model_name = $this->get_this_model_name();
2669
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2670
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2671
+		return $related_model->count($query_params, $field_to_count, $distinct);
2672
+	}
2673
+
2674
+
2675
+
2676
+	/**
2677
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2678
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2679
+	 *
2680
+	 * @param        int           /EE_Base_Class $id_or_obj
2681
+	 * @param string $model_name   like 'Event', or 'Registration'
2682
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2683
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2684
+	 * @return float
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2688
+	{
2689
+		$related_model = $this->get_related_model_obj($model_name);
2690
+		if (! is_array($query_params)) {
2691
+			EE_Error::doing_it_wrong(
2692
+				'EEM_Base::sum_related',
2693
+				sprintf(
2694
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2695
+					gettype($query_params)
2696
+				),
2697
+				'4.6.0'
2698
+			);
2699
+			$query_params = array();
2700
+		}
2701
+		// we're just going to use the query params on the related model's normal get_all query,
2702
+		// except add a condition to say to match the current mod
2703
+		if (! isset($query_params['default_where_conditions'])) {
2704
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2705
+		}
2706
+		$this_model_name = $this->get_this_model_name();
2707
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2708
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2709
+		return $related_model->sum($query_params, $field_to_sum);
2710
+	}
2711
+
2712
+
2713
+
2714
+	/**
2715
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2716
+	 * $modelObject
2717
+	 *
2718
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2719
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2720
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2721
+	 * @return EE_Base_Class
2722
+	 * @throws EE_Error
2723
+	 */
2724
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2725
+	{
2726
+		$query_params['limit'] = 1;
2727
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2728
+		if ($results) {
2729
+			return array_shift($results);
2730
+		}
2731
+		return null;
2732
+	}
2733
+
2734
+
2735
+
2736
+	/**
2737
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2738
+	 *
2739
+	 * @return string
2740
+	 */
2741
+	public function get_this_model_name()
2742
+	{
2743
+		return str_replace("EEM_", "", get_class($this));
2744
+	}
2745
+
2746
+
2747
+
2748
+	/**
2749
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2750
+	 *
2751
+	 * @return EE_Any_Foreign_Model_Name_Field
2752
+	 * @throws EE_Error
2753
+	 */
2754
+	public function get_field_containing_related_model_name()
2755
+	{
2756
+		foreach ($this->field_settings(true) as $field) {
2757
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2758
+				$field_with_model_name = $field;
2759
+			}
2760
+		}
2761
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2762
+			throw new EE_Error(sprintf(
2763
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2764
+				$this->get_this_model_name()
2765
+			));
2766
+		}
2767
+		return $field_with_model_name;
2768
+	}
2769
+
2770
+
2771
+
2772
+	/**
2773
+	 * Inserts a new entry into the database, for each table.
2774
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2775
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2776
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2777
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2778
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2779
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2780
+	 *
2781
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2782
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2783
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2784
+	 *                              of EEM_Base)
2785
+	 * @return int|string new primary key on main table that got inserted
2786
+	 * @throws EE_Error
2787
+	 */
2788
+	public function insert($field_n_values)
2789
+	{
2790
+		/**
2791
+		 * Filters the fields and their values before inserting an item using the models
2792
+		 *
2793
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2794
+		 * @param EEM_Base $model           the model used
2795
+		 */
2796
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2797
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2798
+			$main_table = $this->_get_main_table();
2799
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2800
+			if ($new_id !== false) {
2801
+				foreach ($this->_get_other_tables() as $other_table) {
2802
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2803
+				}
2804
+			}
2805
+			/**
2806
+			 * Done just after attempting to insert a new model object
2807
+			 *
2808
+			 * @param EEM_Base   $model           used
2809
+			 * @param array      $fields_n_values fields and their values
2810
+			 * @param int|string the              ID of the newly-inserted model object
2811
+			 */
2812
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2813
+			return $new_id;
2814
+		}
2815
+		return false;
2816
+	}
2817
+
2818
+
2819
+
2820
+	/**
2821
+	 * Checks that the result would satisfy the unique indexes on this model
2822
+	 *
2823
+	 * @param array  $field_n_values
2824
+	 * @param string $action
2825
+	 * @return boolean
2826
+	 * @throws EE_Error
2827
+	 */
2828
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2829
+	{
2830
+		foreach ($this->unique_indexes() as $index_name => $index) {
2831
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2832
+			if ($this->exists(array($uniqueness_where_params))) {
2833
+				EE_Error::add_error(
2834
+					sprintf(
2835
+						__(
2836
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2837
+							"event_espresso"
2838
+						),
2839
+						$action,
2840
+						$this->_get_class_name(),
2841
+						$index_name,
2842
+						implode(",", $index->field_names()),
2843
+						http_build_query($uniqueness_where_params)
2844
+					),
2845
+					__FILE__,
2846
+					__FUNCTION__,
2847
+					__LINE__
2848
+				);
2849
+				return false;
2850
+			}
2851
+		}
2852
+		return true;
2853
+	}
2854
+
2855
+
2856
+
2857
+	/**
2858
+	 * Checks the database for an item that conflicts (ie, if this item were
2859
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2860
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2861
+	 * can be either an EE_Base_Class or an array of fields n values
2862
+	 *
2863
+	 * @param EE_Base_Class|array $obj_or_fields_array
2864
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2865
+	 *                                                 when looking for conflicts
2866
+	 *                                                 (ie, if false, we ignore the model object's primary key
2867
+	 *                                                 when finding "conflicts". If true, it's also considered).
2868
+	 *                                                 Only works for INT primary key,
2869
+	 *                                                 STRING primary keys cannot be ignored
2870
+	 * @throws EE_Error
2871
+	 * @return EE_Base_Class|array
2872
+	 */
2873
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2874
+	{
2875
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2876
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2877
+		} elseif (is_array($obj_or_fields_array)) {
2878
+			$fields_n_values = $obj_or_fields_array;
2879
+		} else {
2880
+			throw new EE_Error(
2881
+				sprintf(
2882
+					__(
2883
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2884
+						"event_espresso"
2885
+					),
2886
+					get_class($this),
2887
+					$obj_or_fields_array
2888
+				)
2889
+			);
2890
+		}
2891
+		$query_params = array();
2892
+		if ($this->has_primary_key_field()
2893
+			&& ($include_primary_key
2894
+				|| $this->get_primary_key_field()
2895
+				   instanceof
2896
+				   EE_Primary_Key_String_Field)
2897
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2898
+		) {
2899
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2900
+		}
2901
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2902
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2903
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2904
+		}
2905
+		// if there is nothing to base this search on, then we shouldn't find anything
2906
+		if (empty($query_params)) {
2907
+			return array();
2908
+		}
2909
+		return $this->get_one($query_params);
2910
+	}
2911
+
2912
+
2913
+
2914
+	/**
2915
+	 * Like count, but is optimized and returns a boolean instead of an int
2916
+	 *
2917
+	 * @param array $query_params
2918
+	 * @return boolean
2919
+	 * @throws EE_Error
2920
+	 */
2921
+	public function exists($query_params)
2922
+	{
2923
+		$query_params['limit'] = 1;
2924
+		return $this->count($query_params) > 0;
2925
+	}
2926
+
2927
+
2928
+
2929
+	/**
2930
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2931
+	 *
2932
+	 * @param int|string $id
2933
+	 * @return boolean
2934
+	 * @throws EE_Error
2935
+	 */
2936
+	public function exists_by_ID($id)
2937
+	{
2938
+		return $this->exists(
2939
+			array(
2940
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2941
+				array(
2942
+					$this->primary_key_name() => $id,
2943
+				),
2944
+			)
2945
+		);
2946
+	}
2947
+
2948
+
2949
+
2950
+	/**
2951
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2952
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2953
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2954
+	 * on the main table)
2955
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2956
+	 * cases where we want to call it directly rather than via insert().
2957
+	 *
2958
+	 * @access   protected
2959
+	 * @param EE_Table_Base $table
2960
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2961
+	 *                                       float
2962
+	 * @param int           $new_id          for now we assume only int keys
2963
+	 * @throws EE_Error
2964
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2965
+	 * @return int ID of new row inserted, or FALSE on failure
2966
+	 */
2967
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2968
+	{
2969
+		global $wpdb;
2970
+		$insertion_col_n_values = array();
2971
+		$format_for_insertion = array();
2972
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2973
+		foreach ($fields_on_table as $field_name => $field_obj) {
2974
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2975
+			if ($field_obj->is_auto_increment()) {
2976
+				continue;
2977
+			}
2978
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2979
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2980
+			if ($prepared_value !== null) {
2981
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2982
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2983
+			}
2984
+		}
2985
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2986
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2987
+			// so add the fk to the main table as a column
2988
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2989
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2990
+		}
2991
+		// insert the new entry
2992
+		$result = $this->_do_wpdb_query(
2993
+			'insert',
2994
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
2995
+		);
2996
+		if ($result === false) {
2997
+			return false;
2998
+		}
2999
+		// ok, now what do we return for the ID of the newly-inserted thing?
3000
+		if ($this->has_primary_key_field()) {
3001
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3002
+				return $wpdb->insert_id;
3003
+			}
3004
+			// it's not an auto-increment primary key, so
3005
+			// it must have been supplied
3006
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3007
+		}
3008
+		// we can't return a  primary key because there is none. instead return
3009
+		// a unique string indicating this model
3010
+		return $this->get_index_primary_key_string($fields_n_values);
3011
+	}
3012
+
3013
+
3014
+
3015
+	/**
3016
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3017
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3018
+	 * and there is no default, we pass it along. WPDB will take care of it)
3019
+	 *
3020
+	 * @param EE_Model_Field_Base $field_obj
3021
+	 * @param array               $fields_n_values
3022
+	 * @return mixed string|int|float depending on what the table column will be expecting
3023
+	 * @throws EE_Error
3024
+	 */
3025
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3026
+	{
3027
+		// if this field doesn't allow nullable, don't allow it
3028
+		if (! $field_obj->is_nullable()
3029
+			&& (
3030
+				! isset($fields_n_values[ $field_obj->get_name() ])
3031
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3032
+			)
3033
+		) {
3034
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3035
+		}
3036
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3037
+			? $fields_n_values[ $field_obj->get_name() ]
3038
+			: null;
3039
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3040
+	}
3041
+
3042
+
3043
+
3044
+	/**
3045
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3046
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3047
+	 * the field's prepare_for_set() method.
3048
+	 *
3049
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3050
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3051
+	 *                                   top of file)
3052
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3053
+	 *                                   $value is a custom selection
3054
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3055
+	 */
3056
+	private function _prepare_value_for_use_in_db($value, $field)
3057
+	{
3058
+		if ($field && $field instanceof EE_Model_Field_Base) {
3059
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3060
+			switch ($this->_values_already_prepared_by_model_object) {
3061
+				/** @noinspection PhpMissingBreakStatementInspection */
3062
+				case self::not_prepared_by_model_object:
3063
+					$value = $field->prepare_for_set($value);
3064
+				// purposefully left out "return"
3065
+				case self::prepared_by_model_object:
3066
+					/** @noinspection SuspiciousAssignmentsInspection */
3067
+					$value = $field->prepare_for_use_in_db($value);
3068
+				case self::prepared_for_use_in_db:
3069
+					// leave the value alone
3070
+			}
3071
+			return $value;
3072
+			// phpcs:enable
3073
+		}
3074
+		return $value;
3075
+	}
3076
+
3077
+
3078
+
3079
+	/**
3080
+	 * Returns the main table on this model
3081
+	 *
3082
+	 * @return EE_Primary_Table
3083
+	 * @throws EE_Error
3084
+	 */
3085
+	protected function _get_main_table()
3086
+	{
3087
+		foreach ($this->_tables as $table) {
3088
+			if ($table instanceof EE_Primary_Table) {
3089
+				return $table;
3090
+			}
3091
+		}
3092
+		throw new EE_Error(sprintf(__(
3093
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3094
+			'event_espresso'
3095
+		), get_class($this)));
3096
+	}
3097
+
3098
+
3099
+
3100
+	/**
3101
+	 * table
3102
+	 * returns EE_Primary_Table table name
3103
+	 *
3104
+	 * @return string
3105
+	 * @throws EE_Error
3106
+	 */
3107
+	public function table()
3108
+	{
3109
+		return $this->_get_main_table()->get_table_name();
3110
+	}
3111
+
3112
+
3113
+
3114
+	/**
3115
+	 * table
3116
+	 * returns first EE_Secondary_Table table name
3117
+	 *
3118
+	 * @return string
3119
+	 */
3120
+	public function second_table()
3121
+	{
3122
+		// grab second table from tables array
3123
+		$second_table = end($this->_tables);
3124
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * get_table_obj_by_alias
3131
+	 * returns table name given it's alias
3132
+	 *
3133
+	 * @param string $table_alias
3134
+	 * @return EE_Primary_Table | EE_Secondary_Table
3135
+	 */
3136
+	public function get_table_obj_by_alias($table_alias = '')
3137
+	{
3138
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3139
+	}
3140
+
3141
+
3142
+
3143
+	/**
3144
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3145
+	 *
3146
+	 * @return EE_Secondary_Table[]
3147
+	 */
3148
+	protected function _get_other_tables()
3149
+	{
3150
+		$other_tables = array();
3151
+		foreach ($this->_tables as $table_alias => $table) {
3152
+			if ($table instanceof EE_Secondary_Table) {
3153
+				$other_tables[ $table_alias ] = $table;
3154
+			}
3155
+		}
3156
+		return $other_tables;
3157
+	}
3158
+
3159
+
3160
+
3161
+	/**
3162
+	 * Finds all the fields that correspond to the given table
3163
+	 *
3164
+	 * @param string $table_alias , array key in EEM_Base::_tables
3165
+	 * @return EE_Model_Field_Base[]
3166
+	 */
3167
+	public function _get_fields_for_table($table_alias)
3168
+	{
3169
+		return $this->_fields[ $table_alias ];
3170
+	}
3171
+
3172
+
3173
+
3174
+	/**
3175
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3176
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3177
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3178
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3179
+	 * related Registration, Transaction, and Payment models.
3180
+	 *
3181
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3182
+	 * @return EE_Model_Query_Info_Carrier
3183
+	 * @throws EE_Error
3184
+	 */
3185
+	public function _extract_related_models_from_query($query_params)
3186
+	{
3187
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3188
+		if (array_key_exists(0, $query_params)) {
3189
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3190
+		}
3191
+		if (array_key_exists('group_by', $query_params)) {
3192
+			if (is_array($query_params['group_by'])) {
3193
+				$this->_extract_related_models_from_sub_params_array_values(
3194
+					$query_params['group_by'],
3195
+					$query_info_carrier,
3196
+					'group_by'
3197
+				);
3198
+			} elseif (! empty($query_params['group_by'])) {
3199
+				$this->_extract_related_model_info_from_query_param(
3200
+					$query_params['group_by'],
3201
+					$query_info_carrier,
3202
+					'group_by'
3203
+				);
3204
+			}
3205
+		}
3206
+		if (array_key_exists('having', $query_params)) {
3207
+			$this->_extract_related_models_from_sub_params_array_keys(
3208
+				$query_params[0],
3209
+				$query_info_carrier,
3210
+				'having'
3211
+			);
3212
+		}
3213
+		if (array_key_exists('order_by', $query_params)) {
3214
+			if (is_array($query_params['order_by'])) {
3215
+				$this->_extract_related_models_from_sub_params_array_keys(
3216
+					$query_params['order_by'],
3217
+					$query_info_carrier,
3218
+					'order_by'
3219
+				);
3220
+			} elseif (! empty($query_params['order_by'])) {
3221
+				$this->_extract_related_model_info_from_query_param(
3222
+					$query_params['order_by'],
3223
+					$query_info_carrier,
3224
+					'order_by'
3225
+				);
3226
+			}
3227
+		}
3228
+		if (array_key_exists('force_join', $query_params)) {
3229
+			$this->_extract_related_models_from_sub_params_array_values(
3230
+				$query_params['force_join'],
3231
+				$query_info_carrier,
3232
+				'force_join'
3233
+			);
3234
+		}
3235
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3236
+		return $query_info_carrier;
3237
+	}
3238
+
3239
+
3240
+
3241
+	/**
3242
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3243
+	 *
3244
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3245
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3246
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3247
+	 * @throws EE_Error
3248
+	 * @return \EE_Model_Query_Info_Carrier
3249
+	 */
3250
+	private function _extract_related_models_from_sub_params_array_keys(
3251
+		$sub_query_params,
3252
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253
+		$query_param_type
3254
+	) {
3255
+		if (! empty($sub_query_params)) {
3256
+			$sub_query_params = (array) $sub_query_params;
3257
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3259
+				$this->_extract_related_model_info_from_query_param(
3260
+					$param,
3261
+					$model_query_info_carrier,
3262
+					$query_param_type
3263
+				);
3264
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3265
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3266
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3267
+				// of array('Registration.TXN_ID'=>23)
3268
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3269
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3270
+					if (! is_array($possibly_array_of_params)) {
3271
+						throw new EE_Error(sprintf(
3272
+							__(
3273
+								"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'))",
3274
+								"event_espresso"
3275
+							),
3276
+							$param,
3277
+							$possibly_array_of_params
3278
+						));
3279
+					}
3280
+					$this->_extract_related_models_from_sub_params_array_keys(
3281
+						$possibly_array_of_params,
3282
+						$model_query_info_carrier,
3283
+						$query_param_type
3284
+					);
3285
+				} elseif ($query_param_type === 0 // ie WHERE
3286
+						  && is_array($possibly_array_of_params)
3287
+						  && isset($possibly_array_of_params[2])
3288
+						  && $possibly_array_of_params[2] == true
3289
+				) {
3290
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3291
+					// indicating that $possible_array_of_params[1] is actually a field name,
3292
+					// from which we should extract query parameters!
3293
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3294
+						throw new EE_Error(sprintf(__(
3295
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3296
+							"event_espresso"
3297
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3298
+					}
3299
+					$this->_extract_related_model_info_from_query_param(
3300
+						$possibly_array_of_params[1],
3301
+						$model_query_info_carrier,
3302
+						$query_param_type
3303
+					);
3304
+				}
3305
+			}
3306
+		}
3307
+		return $model_query_info_carrier;
3308
+	}
3309
+
3310
+
3311
+
3312
+	/**
3313
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3314
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3315
+	 *
3316
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3317
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3318
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3319
+	 * @throws EE_Error
3320
+	 * @return \EE_Model_Query_Info_Carrier
3321
+	 */
3322
+	private function _extract_related_models_from_sub_params_array_values(
3323
+		$sub_query_params,
3324
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3325
+		$query_param_type
3326
+	) {
3327
+		if (! empty($sub_query_params)) {
3328
+			if (! is_array($sub_query_params)) {
3329
+				throw new EE_Error(sprintf(
3330
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3331
+					$sub_query_params
3332
+				));
3333
+			}
3334
+			foreach ($sub_query_params as $param) {
3335
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3336
+				$this->_extract_related_model_info_from_query_param(
3337
+					$param,
3338
+					$model_query_info_carrier,
3339
+					$query_param_type
3340
+				);
3341
+			}
3342
+		}
3343
+		return $model_query_info_carrier;
3344
+	}
3345
+
3346
+
3347
+	/**
3348
+	 * Extract all the query parts from  model query params
3349
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3350
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3351
+	 * but use them in a different order. Eg, we need to know what models we are querying
3352
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3353
+	 * other models before we can finalize the where clause SQL.
3354
+	 *
3355
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3356
+	 * @throws EE_Error
3357
+	 * @return EE_Model_Query_Info_Carrier
3358
+	 * @throws ModelConfigurationException
3359
+	 */
3360
+	public function _create_model_query_info_carrier($query_params)
3361
+	{
3362
+		if (! is_array($query_params)) {
3363
+			EE_Error::doing_it_wrong(
3364
+				'EEM_Base::_create_model_query_info_carrier',
3365
+				sprintf(
3366
+					__(
3367
+						'$query_params should be an array, you passed a variable of type %s',
3368
+						'event_espresso'
3369
+					),
3370
+					gettype($query_params)
3371
+				),
3372
+				'4.6.0'
3373
+			);
3374
+			$query_params = array();
3375
+		}
3376
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3377
+		// first check if we should alter the query to account for caps or not
3378
+		// because the caps might require us to do extra joins
3379
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3380
+			$query_params[0] = array_replace_recursive(
3381
+				$query_params[0],
3382
+				$this->caps_where_conditions(
3383
+					$query_params['caps']
3384
+				)
3385
+			);
3386
+		}
3387
+
3388
+		// check if we should alter the query to remove data related to protected
3389
+		// custom post types
3390
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3391
+			$where_param_key_for_password = $this->modelChainAndPassword();
3392
+			// only include if related to a cpt where no password has been set
3393
+			$query_params[0]['OR*nopassword'] = array(
3394
+				$where_param_key_for_password => '',
3395
+				$where_param_key_for_password . '*' => array('IS_NULL')
3396
+			);
3397
+		}
3398
+		$query_object = $this->_extract_related_models_from_query($query_params);
3399
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3400
+		foreach ($query_params[0] as $key => $value) {
3401
+			if (is_int($key)) {
3402
+				throw new EE_Error(
3403
+					sprintf(
3404
+						__(
3405
+							"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.",
3406
+							"event_espresso"
3407
+						),
3408
+						$key,
3409
+						var_export($value, true),
3410
+						var_export($query_params, true),
3411
+						get_class($this)
3412
+					)
3413
+				);
3414
+			}
3415
+		}
3416
+		if (array_key_exists('default_where_conditions', $query_params)
3417
+			&& ! empty($query_params['default_where_conditions'])
3418
+		) {
3419
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3420
+		} else {
3421
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3422
+		}
3423
+		$query_params[0] = array_merge(
3424
+			$this->_get_default_where_conditions_for_models_in_query(
3425
+				$query_object,
3426
+				$use_default_where_conditions,
3427
+				$query_params[0]
3428
+			),
3429
+			$query_params[0]
3430
+		);
3431
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3432
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3433
+		// So we need to setup a subquery and use that for the main join.
3434
+		// Note for now this only works on the primary table for the model.
3435
+		// So for instance, you could set the limit array like this:
3436
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3437
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3438
+			$query_object->set_main_model_join_sql(
3439
+				$this->_construct_limit_join_select(
3440
+					$query_params['on_join_limit'][0],
3441
+					$query_params['on_join_limit'][1]
3442
+				)
3443
+			);
3444
+		}
3445
+		// set limit
3446
+		if (array_key_exists('limit', $query_params)) {
3447
+			if (is_array($query_params['limit'])) {
3448
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3449
+					$e = sprintf(
3450
+						__(
3451
+							"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)",
3452
+							"event_espresso"
3453
+						),
3454
+						http_build_query($query_params['limit'])
3455
+					);
3456
+					throw new EE_Error($e . "|" . $e);
3457
+				}
3458
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3459
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3460
+			} elseif (! empty($query_params['limit'])) {
3461
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3462
+			}
3463
+		}
3464
+		// set order by
3465
+		if (array_key_exists('order_by', $query_params)) {
3466
+			if (is_array($query_params['order_by'])) {
3467
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3468
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3469
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3470
+				if (array_key_exists('order', $query_params)) {
3471
+					throw new EE_Error(
3472
+						sprintf(
3473
+							__(
3474
+								"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 ",
3475
+								"event_espresso"
3476
+							),
3477
+							get_class($this),
3478
+							implode(", ", array_keys($query_params['order_by'])),
3479
+							implode(", ", $query_params['order_by']),
3480
+							$query_params['order']
3481
+						)
3482
+					);
3483
+				}
3484
+				$this->_extract_related_models_from_sub_params_array_keys(
3485
+					$query_params['order_by'],
3486
+					$query_object,
3487
+					'order_by'
3488
+				);
3489
+				// assume it's an array of fields to order by
3490
+				$order_array = array();
3491
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3492
+					$order = $this->_extract_order($order);
3493
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3494
+				}
3495
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3496
+			} elseif (! empty($query_params['order_by'])) {
3497
+				$this->_extract_related_model_info_from_query_param(
3498
+					$query_params['order_by'],
3499
+					$query_object,
3500
+					'order',
3501
+					$query_params['order_by']
3502
+				);
3503
+				$order = isset($query_params['order'])
3504
+					? $this->_extract_order($query_params['order'])
3505
+					: 'DESC';
3506
+				$query_object->set_order_by_sql(
3507
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3508
+				);
3509
+			}
3510
+		}
3511
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3512
+		if (! array_key_exists('order_by', $query_params)
3513
+			&& array_key_exists('order', $query_params)
3514
+			&& ! empty($query_params['order'])
3515
+		) {
3516
+			$pk_field = $this->get_primary_key_field();
3517
+			$order = $this->_extract_order($query_params['order']);
3518
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3519
+		}
3520
+		// set group by
3521
+		if (array_key_exists('group_by', $query_params)) {
3522
+			if (is_array($query_params['group_by'])) {
3523
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3524
+				$group_by_array = array();
3525
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3526
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3527
+				}
3528
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3529
+			} elseif (! empty($query_params['group_by'])) {
3530
+				$query_object->set_group_by_sql(
3531
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3532
+				);
3533
+			}
3534
+		}
3535
+		// set having
3536
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3537
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3538
+		}
3539
+		// now, just verify they didn't pass anything wack
3540
+		foreach ($query_params as $query_key => $query_value) {
3541
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3542
+				throw new EE_Error(
3543
+					sprintf(
3544
+						__(
3545
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3546
+							'event_espresso'
3547
+						),
3548
+						$query_key,
3549
+						get_class($this),
3550
+						//                      print_r( $this->_allowed_query_params, TRUE )
3551
+						implode(',', $this->_allowed_query_params)
3552
+					)
3553
+				);
3554
+			}
3555
+		}
3556
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3557
+		if (empty($main_model_join_sql)) {
3558
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3559
+		}
3560
+		return $query_object;
3561
+	}
3562
+
3563
+
3564
+
3565
+	/**
3566
+	 * Gets the where conditions that should be imposed on the query based on the
3567
+	 * context (eg reading frontend, backend, edit or delete).
3568
+	 *
3569
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3570
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3571
+	 * @throws EE_Error
3572
+	 */
3573
+	public function caps_where_conditions($context = self::caps_read)
3574
+	{
3575
+		EEM_Base::verify_is_valid_cap_context($context);
3576
+		$cap_where_conditions = array();
3577
+		$cap_restrictions = $this->caps_missing($context);
3578
+		/**
3579
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3580
+		 */
3581
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3582
+			$cap_where_conditions = array_replace_recursive(
3583
+				$cap_where_conditions,
3584
+				$restriction_if_no_cap->get_default_where_conditions()
3585
+			);
3586
+		}
3587
+		return apply_filters(
3588
+			'FHEE__EEM_Base__caps_where_conditions__return',
3589
+			$cap_where_conditions,
3590
+			$this,
3591
+			$context,
3592
+			$cap_restrictions
3593
+		);
3594
+	}
3595
+
3596
+
3597
+
3598
+	/**
3599
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3600
+	 * otherwise throws an exception
3601
+	 *
3602
+	 * @param string $should_be_order_string
3603
+	 * @return string either ASC, asc, DESC or desc
3604
+	 * @throws EE_Error
3605
+	 */
3606
+	private function _extract_order($should_be_order_string)
3607
+	{
3608
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3609
+			return $should_be_order_string;
3610
+		}
3611
+		throw new EE_Error(
3612
+			sprintf(
3613
+				__(
3614
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3615
+					"event_espresso"
3616
+				),
3617
+				get_class($this),
3618
+				$should_be_order_string
3619
+			)
3620
+		);
3621
+	}
3622
+
3623
+
3624
+
3625
+	/**
3626
+	 * Looks at all the models which are included in this query, and asks each
3627
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3628
+	 * so they can be merged
3629
+	 *
3630
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3631
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3632
+	 *                                                                  'none' means NO default where conditions will
3633
+	 *                                                                  be used AT ALL during this query.
3634
+	 *                                                                  'other_models_only' means default where
3635
+	 *                                                                  conditions from other models will be used, but
3636
+	 *                                                                  not for this primary model. 'all', the default,
3637
+	 *                                                                  means default where conditions will apply as
3638
+	 *                                                                  normal
3639
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3640
+	 * @throws EE_Error
3641
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3642
+	 */
3643
+	private function _get_default_where_conditions_for_models_in_query(
3644
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3645
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3646
+		$where_query_params = array()
3647
+	) {
3648
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3649
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3650
+			throw new EE_Error(sprintf(
3651
+				__(
3652
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3653
+					"event_espresso"
3654
+				),
3655
+				$use_default_where_conditions,
3656
+				implode(", ", $allowed_used_default_where_conditions_values)
3657
+			));
3658
+		}
3659
+		$universal_query_params = array();
3660
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3661
+			$universal_query_params = $this->_get_default_where_conditions();
3662
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3663
+			$universal_query_params = $this->_get_minimum_where_conditions();
3664
+		}
3665
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3666
+			$related_model = $this->get_related_model_obj($model_name);
3667
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3668
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3669
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3670
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3671
+			} else {
3672
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3673
+				continue;
3674
+			}
3675
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3676
+				$related_model_universal_where_params,
3677
+				$where_query_params,
3678
+				$related_model,
3679
+				$model_relation_path
3680
+			);
3681
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3682
+				$universal_query_params,
3683
+				$overrides
3684
+			);
3685
+		}
3686
+		return $universal_query_params;
3687
+	}
3688
+
3689
+
3690
+
3691
+	/**
3692
+	 * Determines whether or not we should use default where conditions for the model in question
3693
+	 * (this model, or other related models).
3694
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3695
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3696
+	 * We should use default where conditions on related models when they requested to use default where conditions
3697
+	 * on all models, or specifically just on other related models
3698
+	 * @param      $default_where_conditions_value
3699
+	 * @param bool $for_this_model false means this is for OTHER related models
3700
+	 * @return bool
3701
+	 */
3702
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3703
+	{
3704
+		return (
3705
+				   $for_this_model
3706
+				   && in_array(
3707
+					   $default_where_conditions_value,
3708
+					   array(
3709
+						   EEM_Base::default_where_conditions_all,
3710
+						   EEM_Base::default_where_conditions_this_only,
3711
+						   EEM_Base::default_where_conditions_minimum_others,
3712
+					   ),
3713
+					   true
3714
+				   )
3715
+			   )
3716
+			   || (
3717
+				   ! $for_this_model
3718
+				   && in_array(
3719
+					   $default_where_conditions_value,
3720
+					   array(
3721
+						   EEM_Base::default_where_conditions_all,
3722
+						   EEM_Base::default_where_conditions_others_only,
3723
+					   ),
3724
+					   true
3725
+				   )
3726
+			   );
3727
+	}
3728
+
3729
+	/**
3730
+	 * Determines whether or not we should use default minimum conditions for the model in question
3731
+	 * (this model, or other related models).
3732
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3733
+	 * where conditions.
3734
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3735
+	 * on this model or others
3736
+	 * @param      $default_where_conditions_value
3737
+	 * @param bool $for_this_model false means this is for OTHER related models
3738
+	 * @return bool
3739
+	 */
3740
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3741
+	{
3742
+		return (
3743
+				   $for_this_model
3744
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3745
+			   )
3746
+			   || (
3747
+				   ! $for_this_model
3748
+				   && in_array(
3749
+					   $default_where_conditions_value,
3750
+					   array(
3751
+						   EEM_Base::default_where_conditions_minimum_others,
3752
+						   EEM_Base::default_where_conditions_minimum_all,
3753
+					   ),
3754
+					   true
3755
+				   )
3756
+			   );
3757
+	}
3758
+
3759
+
3760
+	/**
3761
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3762
+	 * then we also add a special where condition which allows for that model's primary key
3763
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3764
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3765
+	 *
3766
+	 * @param array    $default_where_conditions
3767
+	 * @param array    $provided_where_conditions
3768
+	 * @param EEM_Base $model
3769
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3770
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3771
+	 * @throws EE_Error
3772
+	 */
3773
+	private function _override_defaults_or_make_null_friendly(
3774
+		$default_where_conditions,
3775
+		$provided_where_conditions,
3776
+		$model,
3777
+		$model_relation_path
3778
+	) {
3779
+		$null_friendly_where_conditions = array();
3780
+		$none_overridden = true;
3781
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3782
+		foreach ($default_where_conditions as $key => $val) {
3783
+			if (isset($provided_where_conditions[ $key ])) {
3784
+				$none_overridden = false;
3785
+			} else {
3786
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3787
+			}
3788
+		}
3789
+		if ($none_overridden && $default_where_conditions) {
3790
+			if ($model->has_primary_key_field()) {
3791
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3792
+																				. "."
3793
+																				. $model->primary_key_name() ] = array('IS NULL');
3794
+			}/*else{
3795 3795
                 //@todo NO PK, use other defaults
3796 3796
             }*/
3797
-        }
3798
-        return $null_friendly_where_conditions;
3799
-    }
3800
-
3801
-
3802
-
3803
-    /**
3804
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3805
-     * default where conditions on all get_all, update, and delete queries done by this model.
3806
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3807
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3808
-     *
3809
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3810
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3811
-     */
3812
-    private function _get_default_where_conditions($model_relation_path = null)
3813
-    {
3814
-        if ($this->_ignore_where_strategy) {
3815
-            return array();
3816
-        }
3817
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3818
-    }
3819
-
3820
-
3821
-
3822
-    /**
3823
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3824
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3825
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3826
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3827
-     * Similar to _get_default_where_conditions
3828
-     *
3829
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
-     */
3832
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3833
-    {
3834
-        if ($this->_ignore_where_strategy) {
3835
-            return array();
3836
-        }
3837
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
-    }
3839
-
3840
-
3841
-
3842
-    /**
3843
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3844
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3845
-     *
3846
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3847
-     * @return string
3848
-     * @throws EE_Error
3849
-     */
3850
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3851
-    {
3852
-        $selects = $this->_get_columns_to_select_for_this_model();
3853
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3854
-            $name_of_other_model_included) {
3855
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3856
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3857
-            foreach ($other_model_selects as $key => $value) {
3858
-                $selects[] = $value;
3859
-            }
3860
-        }
3861
-        return implode(", ", $selects);
3862
-    }
3863
-
3864
-
3865
-
3866
-    /**
3867
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3868
-     * So that's going to be the columns for all the fields on the model
3869
-     *
3870
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3871
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3872
-     */
3873
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3874
-    {
3875
-        $fields = $this->field_settings();
3876
-        $selects = array();
3877
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3878
-            $model_relation_chain,
3879
-            $this->get_this_model_name()
3880
-        );
3881
-        foreach ($fields as $field_obj) {
3882
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3883
-                         . $field_obj->get_table_alias()
3884
-                         . "."
3885
-                         . $field_obj->get_table_column()
3886
-                         . " AS '"
3887
-                         . $table_alias_with_model_relation_chain_prefix
3888
-                         . $field_obj->get_table_alias()
3889
-                         . "."
3890
-                         . $field_obj->get_table_column()
3891
-                         . "'";
3892
-        }
3893
-        // make sure we are also getting the PKs of each table
3894
-        $tables = $this->get_tables();
3895
-        if (count($tables) > 1) {
3896
-            foreach ($tables as $table_obj) {
3897
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3898
-                                       . $table_obj->get_fully_qualified_pk_column();
3899
-                if (! in_array($qualified_pk_column, $selects)) {
3900
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3901
-                }
3902
-            }
3903
-        }
3904
-        return $selects;
3905
-    }
3906
-
3907
-
3908
-
3909
-    /**
3910
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3911
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3912
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3913
-     * SQL for joining, and the data types
3914
-     *
3915
-     * @param null|string                 $original_query_param
3916
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3917
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3918
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3919
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3920
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3921
-     *                                                          or 'Registration's
3922
-     * @param string                      $original_query_param what it originally was (eg
3923
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3924
-     *                                                          matches $query_param
3925
-     * @throws EE_Error
3926
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3927
-     */
3928
-    private function _extract_related_model_info_from_query_param(
3929
-        $query_param,
3930
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3931
-        $query_param_type,
3932
-        $original_query_param = null
3933
-    ) {
3934
-        if ($original_query_param === null) {
3935
-            $original_query_param = $query_param;
3936
-        }
3937
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3938
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3939
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3940
-        $allow_fields = in_array(
3941
-            $query_param_type,
3942
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3943
-            true
3944
-        );
3945
-        // check to see if we have a field on this model
3946
-        $this_model_fields = $this->field_settings(true);
3947
-        if (array_key_exists($query_param, $this_model_fields)) {
3948
-            if ($allow_fields) {
3949
-                return;
3950
-            }
3951
-            throw new EE_Error(
3952
-                sprintf(
3953
-                    __(
3954
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3955
-                        "event_espresso"
3956
-                    ),
3957
-                    $query_param,
3958
-                    get_class($this),
3959
-                    $query_param_type,
3960
-                    $original_query_param
3961
-                )
3962
-            );
3963
-        }
3964
-        // check if this is a special logic query param
3965
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3966
-            if ($allow_logic_query_params) {
3967
-                return;
3968
-            }
3969
-            throw new EE_Error(
3970
-                sprintf(
3971
-                    __(
3972
-                        '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',
3973
-                        'event_espresso'
3974
-                    ),
3975
-                    implode('", "', $this->_logic_query_param_keys),
3976
-                    $query_param,
3977
-                    get_class($this),
3978
-                    '<br />',
3979
-                    "\t"
3980
-                    . ' $passed_in_query_info = <pre>'
3981
-                    . print_r($passed_in_query_info, true)
3982
-                    . '</pre>'
3983
-                    . "\n\t"
3984
-                    . ' $query_param_type = '
3985
-                    . $query_param_type
3986
-                    . "\n\t"
3987
-                    . ' $original_query_param = '
3988
-                    . $original_query_param
3989
-                )
3990
-            );
3991
-        }
3992
-        // check if it's a custom selection
3993
-        if ($this->_custom_selections instanceof CustomSelects
3994
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3995
-        ) {
3996
-            return;
3997
-        }
3998
-        // check if has a model name at the beginning
3999
-        // and
4000
-        // check if it's a field on a related model
4001
-        if ($this->extractJoinModelFromQueryParams(
4002
-            $passed_in_query_info,
4003
-            $query_param,
4004
-            $original_query_param,
4005
-            $query_param_type
4006
-        )) {
4007
-            return;
4008
-        }
4009
-
4010
-        // ok so $query_param didn't start with a model name
4011
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4012
-        // it's wack, that's what it is
4013
-        throw new EE_Error(
4014
-            sprintf(
4015
-                esc_html__(
4016
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4017
-                    "event_espresso"
4018
-                ),
4019
-                $query_param,
4020
-                get_class($this),
4021
-                $query_param_type,
4022
-                $original_query_param
4023
-            )
4024
-        );
4025
-    }
4026
-
4027
-
4028
-    /**
4029
-     * Extracts any possible join model information from the provided possible_join_string.
4030
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4031
-     * parts that should be added to the query.
4032
-     *
4033
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4034
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4035
-     * @param null|string                 $original_query_param
4036
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4037
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4038
-     * @return bool  returns true if a join was added and false if not.
4039
-     * @throws EE_Error
4040
-     */
4041
-    private function extractJoinModelFromQueryParams(
4042
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4043
-        $possible_join_string,
4044
-        $original_query_param,
4045
-        $query_parameter_type
4046
-    ) {
4047
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4048
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4049
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4050
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4051
-                if ($possible_join_string === '') {
4052
-                    // nothing left to $query_param
4053
-                    // we should actually end in a field name, not a model like this!
4054
-                    throw new EE_Error(
4055
-                        sprintf(
4056
-                            esc_html__(
4057
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4058
-                                "event_espresso"
4059
-                            ),
4060
-                            $possible_join_string,
4061
-                            $query_parameter_type,
4062
-                            get_class($this),
4063
-                            $valid_related_model_name
4064
-                        )
4065
-                    );
4066
-                }
4067
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4068
-                $related_model_obj->_extract_related_model_info_from_query_param(
4069
-                    $possible_join_string,
4070
-                    $query_info_carrier,
4071
-                    $query_parameter_type,
4072
-                    $original_query_param
4073
-                );
4074
-                return true;
4075
-            }
4076
-            if ($possible_join_string === $valid_related_model_name) {
4077
-                $this->_add_join_to_model(
4078
-                    $valid_related_model_name,
4079
-                    $query_info_carrier,
4080
-                    $original_query_param
4081
-                );
4082
-                return true;
4083
-            }
4084
-        }
4085
-        return false;
4086
-    }
4087
-
4088
-
4089
-    /**
4090
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4091
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4092
-     * @throws EE_Error
4093
-     */
4094
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4095
-    {
4096
-        if ($this->_custom_selections instanceof CustomSelects
4097
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4098
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4099
-            )
4100
-        ) {
4101
-            $original_selects = $this->_custom_selections->originalSelects();
4102
-            foreach ($original_selects as $alias => $select_configuration) {
4103
-                $this->extractJoinModelFromQueryParams(
4104
-                    $query_info_carrier,
4105
-                    $select_configuration[0],
4106
-                    $select_configuration[0],
4107
-                    'custom_selects'
4108
-                );
4109
-            }
4110
-        }
4111
-    }
4112
-
4113
-
4114
-
4115
-    /**
4116
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4117
-     * and store it on $passed_in_query_info
4118
-     *
4119
-     * @param string                      $model_name
4120
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4121
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4122
-     *                                                          model and $model_name. Eg, if we are querying Event,
4123
-     *                                                          and are adding a join to 'Payment' with the original
4124
-     *                                                          query param key
4125
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4126
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4127
-     *                                                          Payment wants to add default query params so that it
4128
-     *                                                          will know what models to prepend onto its default query
4129
-     *                                                          params or in case it wants to rename tables (in case
4130
-     *                                                          there are multiple joins to the same table)
4131
-     * @return void
4132
-     * @throws EE_Error
4133
-     */
4134
-    private function _add_join_to_model(
4135
-        $model_name,
4136
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4137
-        $original_query_param
4138
-    ) {
4139
-        $relation_obj = $this->related_settings_for($model_name);
4140
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4141
-        // check if the relation is HABTM, because then we're essentially doing two joins
4142
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4143
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4144
-            $join_model_obj = $relation_obj->get_join_model();
4145
-            // replace the model specified with the join model for this relation chain, whi
4146
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4147
-                $model_name,
4148
-                $join_model_obj->get_this_model_name(),
4149
-                $model_relation_chain
4150
-            );
4151
-            $passed_in_query_info->merge(
4152
-                new EE_Model_Query_Info_Carrier(
4153
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4154
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4155
-                )
4156
-            );
4157
-        }
4158
-        // now just join to the other table pointed to by the relation object, and add its data types
4159
-        $passed_in_query_info->merge(
4160
-            new EE_Model_Query_Info_Carrier(
4161
-                array($model_relation_chain => $model_name),
4162
-                $relation_obj->get_join_statement($model_relation_chain)
4163
-            )
4164
-        );
4165
-    }
4166
-
4167
-
4168
-
4169
-    /**
4170
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4171
-     *
4172
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4173
-     * @return string of SQL
4174
-     * @throws EE_Error
4175
-     */
4176
-    private function _construct_where_clause($where_params)
4177
-    {
4178
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4179
-        if ($SQL) {
4180
-            return " WHERE " . $SQL;
4181
-        }
4182
-        return '';
4183
-    }
4184
-
4185
-
4186
-
4187
-    /**
4188
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4189
-     * and should be passed HAVING parameters, not WHERE parameters
4190
-     *
4191
-     * @param array $having_params
4192
-     * @return string
4193
-     * @throws EE_Error
4194
-     */
4195
-    private function _construct_having_clause($having_params)
4196
-    {
4197
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4198
-        if ($SQL) {
4199
-            return " HAVING " . $SQL;
4200
-        }
4201
-        return '';
4202
-    }
4203
-
4204
-
4205
-    /**
4206
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4207
-     * Event_Meta.meta_value = 'foo'))"
4208
-     *
4209
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4210
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4211
-     * @throws EE_Error
4212
-     * @return string of SQL
4213
-     */
4214
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4215
-    {
4216
-        $where_clauses = array();
4217
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4218
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4219
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4220
-                switch ($query_param) {
4221
-                    case 'not':
4222
-                    case 'NOT':
4223
-                        $where_clauses[] = "! ("
4224
-                                           . $this->_construct_condition_clause_recursive(
4225
-                                               $op_and_value_or_sub_condition,
4226
-                                               $glue
4227
-                                           )
4228
-                                           . ")";
4229
-                        break;
4230
-                    case 'and':
4231
-                    case 'AND':
4232
-                        $where_clauses[] = " ("
4233
-                                           . $this->_construct_condition_clause_recursive(
4234
-                                               $op_and_value_or_sub_condition,
4235
-                                               ' AND '
4236
-                                           )
4237
-                                           . ")";
4238
-                        break;
4239
-                    case 'or':
4240
-                    case 'OR':
4241
-                        $where_clauses[] = " ("
4242
-                                           . $this->_construct_condition_clause_recursive(
4243
-                                               $op_and_value_or_sub_condition,
4244
-                                               ' OR '
4245
-                                           )
4246
-                                           . ")";
4247
-                        break;
4248
-                }
4249
-            } else {
4250
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4251
-                // if it's not a normal field, maybe it's a custom selection?
4252
-                if (! $field_obj) {
4253
-                    if ($this->_custom_selections instanceof CustomSelects) {
4254
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4255
-                    } else {
4256
-                        throw new EE_Error(sprintf(__(
4257
-                            "%s is neither a valid model field name, nor a custom selection",
4258
-                            "event_espresso"
4259
-                        ), $query_param));
4260
-                    }
4261
-                }
4262
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4263
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4264
-            }
4265
-        }
4266
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4267
-    }
4268
-
4269
-
4270
-
4271
-    /**
4272
-     * Takes the input parameter and extract the table name (alias) and column name
4273
-     *
4274
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4275
-     * @throws EE_Error
4276
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4277
-     */
4278
-    private function _deduce_column_name_from_query_param($query_param)
4279
-    {
4280
-        $field = $this->_deduce_field_from_query_param($query_param);
4281
-        if ($field) {
4282
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4283
-                $field->get_model_name(),
4284
-                $query_param
4285
-            );
4286
-            return $table_alias_prefix . $field->get_qualified_column();
4287
-        }
4288
-        if ($this->_custom_selections instanceof CustomSelects
4289
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4290
-        ) {
4291
-            // maybe it's custom selection item?
4292
-            // if so, just use it as the "column name"
4293
-            return $query_param;
4294
-        }
4295
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4296
-            ? implode(',', $this->_custom_selections->columnAliases())
4297
-            : '';
4298
-        throw new EE_Error(
4299
-            sprintf(
4300
-                __(
4301
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4302
-                    "event_espresso"
4303
-                ),
4304
-                $query_param,
4305
-                $custom_select_aliases
4306
-            )
4307
-        );
4308
-    }
4309
-
4310
-
4311
-
4312
-    /**
4313
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4314
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4315
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4316
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4317
-     *
4318
-     * @param string $condition_query_param_key
4319
-     * @return string
4320
-     */
4321
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4322
-    {
4323
-        $pos_of_star = strpos($condition_query_param_key, '*');
4324
-        if ($pos_of_star === false) {
4325
-            return $condition_query_param_key;
4326
-        }
4327
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4328
-        return $condition_query_param_sans_star;
4329
-    }
4330
-
4331
-
4332
-
4333
-    /**
4334
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4335
-     *
4336
-     * @param                            mixed      array | string    $op_and_value
4337
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4338
-     * @throws EE_Error
4339
-     * @return string
4340
-     */
4341
-    private function _construct_op_and_value($op_and_value, $field_obj)
4342
-    {
4343
-        if (is_array($op_and_value)) {
4344
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4345
-            if (! $operator) {
4346
-                $php_array_like_string = array();
4347
-                foreach ($op_and_value as $key => $value) {
4348
-                    $php_array_like_string[] = "$key=>$value";
4349
-                }
4350
-                throw new EE_Error(
4351
-                    sprintf(
4352
-                        __(
4353
-                            "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))",
4354
-                            "event_espresso"
4355
-                        ),
4356
-                        implode(",", $php_array_like_string)
4357
-                    )
4358
-                );
4359
-            }
4360
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4361
-        } else {
4362
-            $operator = '=';
4363
-            $value = $op_and_value;
4364
-        }
4365
-        // check to see if the value is actually another field
4366
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4367
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4368
-        }
4369
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4370
-            // in this case, the value should be an array, or at least a comma-separated list
4371
-            // it will need to handle a little differently
4372
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4373
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4374
-            return $operator . SP . $cleaned_value;
4375
-        }
4376
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4377
-            // the value should be an array with count of two.
4378
-            if (count($value) !== 2) {
4379
-                throw new EE_Error(
4380
-                    sprintf(
4381
-                        __(
4382
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4383
-                            'event_espresso'
4384
-                        ),
4385
-                        "BETWEEN"
4386
-                    )
4387
-                );
4388
-            }
4389
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4390
-            return $operator . SP . $cleaned_value;
4391
-        }
4392
-        if (in_array($operator, $this->valid_null_style_operators())) {
4393
-            if ($value !== null) {
4394
-                throw new EE_Error(
4395
-                    sprintf(
4396
-                        __(
4397
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4398
-                            "event_espresso"
4399
-                        ),
4400
-                        $value,
4401
-                        $operator
4402
-                    )
4403
-                );
4404
-            }
4405
-            return $operator;
4406
-        }
4407
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4408
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4409
-            // remove other junk. So just treat it as a string.
4410
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4411
-        }
4412
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4413
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4414
-        }
4415
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4416
-            throw new EE_Error(
4417
-                sprintf(
4418
-                    __(
4419
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4420
-                        'event_espresso'
4421
-                    ),
4422
-                    $operator,
4423
-                    $operator
4424
-                )
4425
-            );
4426
-        }
4427
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4428
-            throw new EE_Error(
4429
-                sprintf(
4430
-                    __(
4431
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4432
-                        'event_espresso'
4433
-                    ),
4434
-                    $operator,
4435
-                    $operator
4436
-                )
4437
-            );
4438
-        }
4439
-        throw new EE_Error(
4440
-            sprintf(
4441
-                __(
4442
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4443
-                    "event_espresso"
4444
-                ),
4445
-                http_build_query($op_and_value)
4446
-            )
4447
-        );
4448
-    }
4449
-
4450
-
4451
-
4452
-    /**
4453
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4454
-     *
4455
-     * @param array                      $values
4456
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4457
-     *                                              '%s'
4458
-     * @return string
4459
-     * @throws EE_Error
4460
-     */
4461
-    public function _construct_between_value($values, $field_obj)
4462
-    {
4463
-        $cleaned_values = array();
4464
-        foreach ($values as $value) {
4465
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4466
-        }
4467
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4468
-    }
4469
-
4470
-
4471
-
4472
-    /**
4473
-     * Takes an array or a comma-separated list of $values and cleans them
4474
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4475
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4476
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4477
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4478
-     *
4479
-     * @param mixed                      $values    array or comma-separated string
4480
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4481
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4482
-     * @throws EE_Error
4483
-     */
4484
-    public function _construct_in_value($values, $field_obj)
4485
-    {
4486
-        // check if the value is a CSV list
4487
-        if (is_string($values)) {
4488
-            // in which case, turn it into an array
4489
-            $values = explode(",", $values);
4490
-        }
4491
-        $cleaned_values = array();
4492
-        foreach ($values as $value) {
4493
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4494
-        }
4495
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4496
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4497
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4498
-        if (empty($cleaned_values)) {
4499
-            $all_fields = $this->field_settings();
4500
-            $a_field = array_shift($all_fields);
4501
-            $main_table = $this->_get_main_table();
4502
-            $cleaned_values[] = "SELECT "
4503
-                                . $a_field->get_table_column()
4504
-                                . " FROM "
4505
-                                . $main_table->get_table_name()
4506
-                                . " WHERE FALSE";
4507
-        }
4508
-        return "(" . implode(",", $cleaned_values) . ")";
4509
-    }
4510
-
4511
-
4512
-
4513
-    /**
4514
-     * @param mixed                      $value
4515
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4516
-     * @throws EE_Error
4517
-     * @return false|null|string
4518
-     */
4519
-    private function _wpdb_prepare_using_field($value, $field_obj)
4520
-    {
4521
-        /** @type WPDB $wpdb */
4522
-        global $wpdb;
4523
-        if ($field_obj instanceof EE_Model_Field_Base) {
4524
-            return $wpdb->prepare(
4525
-                $field_obj->get_wpdb_data_type(),
4526
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4527
-            );
4528
-        } //$field_obj should really just be a data type
4529
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4530
-            throw new EE_Error(
4531
-                sprintf(
4532
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4533
-                    $field_obj,
4534
-                    implode(",", $this->_valid_wpdb_data_types)
4535
-                )
4536
-            );
4537
-        }
4538
-        return $wpdb->prepare($field_obj, $value);
4539
-    }
4540
-
4541
-
4542
-
4543
-    /**
4544
-     * Takes the input parameter and finds the model field that it indicates.
4545
-     *
4546
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4547
-     * @throws EE_Error
4548
-     * @return EE_Model_Field_Base
4549
-     */
4550
-    protected function _deduce_field_from_query_param($query_param_name)
4551
-    {
4552
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4553
-        // which will help us find the database table and column
4554
-        $query_param_parts = explode(".", $query_param_name);
4555
-        if (empty($query_param_parts)) {
4556
-            throw new EE_Error(sprintf(__(
4557
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4558
-                'event_espresso'
4559
-            ), $query_param_name));
4560
-        }
4561
-        $number_of_parts = count($query_param_parts);
4562
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4563
-        if ($number_of_parts === 1) {
4564
-            $field_name = $last_query_param_part;
4565
-            $model_obj = $this;
4566
-        } else {// $number_of_parts >= 2
4567
-            // the last part is the column name, and there are only 2parts. therefore...
4568
-            $field_name = $last_query_param_part;
4569
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4570
-        }
4571
-        try {
4572
-            return $model_obj->field_settings_for($field_name);
4573
-        } catch (EE_Error $e) {
4574
-            return null;
4575
-        }
4576
-    }
4577
-
4578
-
4579
-
4580
-    /**
4581
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4582
-     * alias and column which corresponds to it
4583
-     *
4584
-     * @param string $field_name
4585
-     * @throws EE_Error
4586
-     * @return string
4587
-     */
4588
-    public function _get_qualified_column_for_field($field_name)
4589
-    {
4590
-        $all_fields = $this->field_settings();
4591
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4592
-        if ($field) {
4593
-            return $field->get_qualified_column();
4594
-        }
4595
-        throw new EE_Error(
4596
-            sprintf(
4597
-                __(
4598
-                    "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.",
4599
-                    'event_espresso'
4600
-                ),
4601
-                $field_name,
4602
-                get_class($this)
4603
-            )
4604
-        );
4605
-    }
4606
-
4607
-
4608
-
4609
-    /**
4610
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4611
-     * Example usage:
4612
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4613
-     *      array(),
4614
-     *      ARRAY_A,
4615
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4616
-     *  );
4617
-     * is equivalent to
4618
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4619
-     * and
4620
-     *  EEM_Event::instance()->get_all_wpdb_results(
4621
-     *      array(
4622
-     *          array(
4623
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4624
-     *          ),
4625
-     *          ARRAY_A,
4626
-     *          implode(
4627
-     *              ', ',
4628
-     *              array_merge(
4629
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4630
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4631
-     *              )
4632
-     *          )
4633
-     *      )
4634
-     *  );
4635
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4636
-     *
4637
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4638
-     *                                            and the one whose fields you are selecting for example: when querying
4639
-     *                                            tickets model and selecting fields from the tickets model you would
4640
-     *                                            leave this parameter empty, because no models are needed to join
4641
-     *                                            between the queried model and the selected one. Likewise when
4642
-     *                                            querying the datetime model and selecting fields from the tickets
4643
-     *                                            model, it would also be left empty, because there is a direct
4644
-     *                                            relation from datetimes to tickets, so no model is needed to join
4645
-     *                                            them together. However, when querying from the event model and
4646
-     *                                            selecting fields from the ticket model, you should provide the string
4647
-     *                                            'Datetime', indicating that the event model must first join to the
4648
-     *                                            datetime model in order to find its relation to ticket model.
4649
-     *                                            Also, when querying from the venue model and selecting fields from
4650
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4651
-     *                                            indicating you need to join the venue model to the event model,
4652
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4653
-     *                                            This string is used to deduce the prefix that gets added onto the
4654
-     *                                            models' tables qualified columns
4655
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4656
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4657
-     *                                            qualified column names
4658
-     * @return array|string
4659
-     */
4660
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4661
-    {
4662
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4663
-        $qualified_columns = array();
4664
-        foreach ($this->field_settings() as $field_name => $field) {
4665
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4666
-        }
4667
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4668
-    }
4669
-
4670
-
4671
-
4672
-    /**
4673
-     * constructs the select use on special limit joins
4674
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4675
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4676
-     * (as that is typically where the limits would be set).
4677
-     *
4678
-     * @param  string       $table_alias The table the select is being built for
4679
-     * @param  mixed|string $limit       The limit for this select
4680
-     * @return string                The final select join element for the query.
4681
-     */
4682
-    public function _construct_limit_join_select($table_alias, $limit)
4683
-    {
4684
-        $SQL = '';
4685
-        foreach ($this->_tables as $table_obj) {
4686
-            if ($table_obj instanceof EE_Primary_Table) {
4687
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4688
-                    ? $table_obj->get_select_join_limit($limit)
4689
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4690
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4691
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4692
-                    ? $table_obj->get_select_join_limit_join($limit)
4693
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4694
-            }
4695
-        }
4696
-        return $SQL;
4697
-    }
4698
-
4699
-
4700
-
4701
-    /**
4702
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4703
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4704
-     *
4705
-     * @return string SQL
4706
-     * @throws EE_Error
4707
-     */
4708
-    public function _construct_internal_join()
4709
-    {
4710
-        $SQL = $this->_get_main_table()->get_table_sql();
4711
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4712
-        return $SQL;
4713
-    }
4714
-
4715
-
4716
-
4717
-    /**
4718
-     * Constructs the SQL for joining all the tables on this model.
4719
-     * Normally $alias should be the primary table's alias, but in cases where
4720
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4721
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4722
-     * alias, this will construct SQL like:
4723
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4724
-     * With $alias being a secondary table's alias, this will construct SQL like:
4725
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4726
-     *
4727
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4728
-     * @return string
4729
-     */
4730
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4731
-    {
4732
-        $SQL = '';
4733
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4734
-        foreach ($this->_tables as $table_obj) {
4735
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4736
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4737
-                    // so we're joining to this table, meaning the table is already in
4738
-                    // the FROM statement, BUT the primary table isn't. So we want
4739
-                    // to add the inverse join sql
4740
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4741
-                } else {
4742
-                    // just add a regular JOIN to this table from the primary table
4743
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4744
-                }
4745
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4746
-        }
4747
-        return $SQL;
4748
-    }
4749
-
4750
-
4751
-
4752
-    /**
4753
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4754
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4755
-     * their data type (eg, '%s', '%d', etc)
4756
-     *
4757
-     * @return array
4758
-     */
4759
-    public function _get_data_types()
4760
-    {
4761
-        $data_types = array();
4762
-        foreach ($this->field_settings() as $field_obj) {
4763
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4764
-            /** @var $field_obj EE_Model_Field_Base */
4765
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4766
-        }
4767
-        return $data_types;
4768
-    }
4769
-
4770
-
4771
-
4772
-    /**
4773
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4774
-     *
4775
-     * @param string $model_name
4776
-     * @throws EE_Error
4777
-     * @return EEM_Base
4778
-     */
4779
-    public function get_related_model_obj($model_name)
4780
-    {
4781
-        $model_classname = "EEM_" . $model_name;
4782
-        if (! class_exists($model_classname)) {
4783
-            throw new EE_Error(sprintf(__(
4784
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4785
-                'event_espresso'
4786
-            ), $model_name, $model_classname));
4787
-        }
4788
-        return call_user_func($model_classname . "::instance");
4789
-    }
4790
-
4791
-
4792
-
4793
-    /**
4794
-     * Returns the array of EE_ModelRelations for this model.
4795
-     *
4796
-     * @return EE_Model_Relation_Base[]
4797
-     */
4798
-    public function relation_settings()
4799
-    {
4800
-        return $this->_model_relations;
4801
-    }
4802
-
4803
-
4804
-
4805
-    /**
4806
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4807
-     * because without THOSE models, this model probably doesn't have much purpose.
4808
-     * (Eg, without an event, datetimes have little purpose.)
4809
-     *
4810
-     * @return EE_Belongs_To_Relation[]
4811
-     */
4812
-    public function belongs_to_relations()
4813
-    {
4814
-        $belongs_to_relations = array();
4815
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4816
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4817
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4818
-            }
4819
-        }
4820
-        return $belongs_to_relations;
4821
-    }
4822
-
4823
-
4824
-
4825
-    /**
4826
-     * Returns the specified EE_Model_Relation, or throws an exception
4827
-     *
4828
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4829
-     * @throws EE_Error
4830
-     * @return EE_Model_Relation_Base
4831
-     */
4832
-    public function related_settings_for($relation_name)
4833
-    {
4834
-        $relatedModels = $this->relation_settings();
4835
-        if (! array_key_exists($relation_name, $relatedModels)) {
4836
-            throw new EE_Error(
4837
-                sprintf(
4838
-                    __(
4839
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4840
-                        'event_espresso'
4841
-                    ),
4842
-                    $relation_name,
4843
-                    $this->_get_class_name(),
4844
-                    implode(', ', array_keys($relatedModels))
4845
-                )
4846
-            );
4847
-        }
4848
-        return $relatedModels[ $relation_name ];
4849
-    }
4850
-
4851
-
4852
-
4853
-    /**
4854
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4855
-     * fields
4856
-     *
4857
-     * @param string $fieldName
4858
-     * @param boolean $include_db_only_fields
4859
-     * @throws EE_Error
4860
-     * @return EE_Model_Field_Base
4861
-     */
4862
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4863
-    {
4864
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4865
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4866
-            throw new EE_Error(sprintf(
4867
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4868
-                $fieldName,
4869
-                get_class($this)
4870
-            ));
4871
-        }
4872
-        return $fieldSettings[ $fieldName ];
4873
-    }
4874
-
4875
-
4876
-
4877
-    /**
4878
-     * Checks if this field exists on this model
4879
-     *
4880
-     * @param string $fieldName a key in the model's _field_settings array
4881
-     * @return boolean
4882
-     */
4883
-    public function has_field($fieldName)
4884
-    {
4885
-        $fieldSettings = $this->field_settings(true);
4886
-        if (isset($fieldSettings[ $fieldName ])) {
4887
-            return true;
4888
-        }
4889
-        return false;
4890
-    }
4891
-
4892
-
4893
-
4894
-    /**
4895
-     * Returns whether or not this model has a relation to the specified model
4896
-     *
4897
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4898
-     * @return boolean
4899
-     */
4900
-    public function has_relation($relation_name)
4901
-    {
4902
-        $relations = $this->relation_settings();
4903
-        if (isset($relations[ $relation_name ])) {
4904
-            return true;
4905
-        }
4906
-        return false;
4907
-    }
4908
-
4909
-
4910
-
4911
-    /**
4912
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4913
-     * Eg, on EE_Answer that would be ANS_ID field object
4914
-     *
4915
-     * @param $field_obj
4916
-     * @return boolean
4917
-     */
4918
-    public function is_primary_key_field($field_obj)
4919
-    {
4920
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4921
-    }
4922
-
4923
-
4924
-
4925
-    /**
4926
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4927
-     * Eg, on EE_Answer that would be ANS_ID field object
4928
-     *
4929
-     * @return EE_Model_Field_Base
4930
-     * @throws EE_Error
4931
-     */
4932
-    public function get_primary_key_field()
4933
-    {
4934
-        if ($this->_primary_key_field === null) {
4935
-            foreach ($this->field_settings(true) as $field_obj) {
4936
-                if ($this->is_primary_key_field($field_obj)) {
4937
-                    $this->_primary_key_field = $field_obj;
4938
-                    break;
4939
-                }
4940
-            }
4941
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4942
-                throw new EE_Error(sprintf(
4943
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4944
-                    get_class($this)
4945
-                ));
4946
-            }
4947
-        }
4948
-        return $this->_primary_key_field;
4949
-    }
4950
-
4951
-
4952
-
4953
-    /**
4954
-     * Returns whether or not not there is a primary key on this model.
4955
-     * Internally does some caching.
4956
-     *
4957
-     * @return boolean
4958
-     */
4959
-    public function has_primary_key_field()
4960
-    {
4961
-        if ($this->_has_primary_key_field === null) {
4962
-            try {
4963
-                $this->get_primary_key_field();
4964
-                $this->_has_primary_key_field = true;
4965
-            } catch (EE_Error $e) {
4966
-                $this->_has_primary_key_field = false;
4967
-            }
4968
-        }
4969
-        return $this->_has_primary_key_field;
4970
-    }
4971
-
4972
-
4973
-
4974
-    /**
4975
-     * Finds the first field of type $field_class_name.
4976
-     *
4977
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4978
-     *                                 EE_Foreign_Key_Field, etc
4979
-     * @return EE_Model_Field_Base or null if none is found
4980
-     */
4981
-    public function get_a_field_of_type($field_class_name)
4982
-    {
4983
-        foreach ($this->field_settings() as $field) {
4984
-            if ($field instanceof $field_class_name) {
4985
-                return $field;
4986
-            }
4987
-        }
4988
-        return null;
4989
-    }
4990
-
4991
-
4992
-
4993
-    /**
4994
-     * Gets a foreign key field pointing to model.
4995
-     *
4996
-     * @param string $model_name eg Event, Registration, not EEM_Event
4997
-     * @return EE_Foreign_Key_Field_Base
4998
-     * @throws EE_Error
4999
-     */
5000
-    public function get_foreign_key_to($model_name)
5001
-    {
5002
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5003
-            foreach ($this->field_settings() as $field) {
5004
-                if ($field instanceof EE_Foreign_Key_Field_Base
5005
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5006
-                ) {
5007
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5008
-                    break;
5009
-                }
5010
-            }
5011
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5012
-                throw new EE_Error(sprintf(__(
5013
-                    "There is no foreign key field pointing to model %s on model %s",
5014
-                    'event_espresso'
5015
-                ), $model_name, get_class($this)));
5016
-            }
5017
-        }
5018
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5019
-    }
5020
-
5021
-
5022
-
5023
-    /**
5024
-     * Gets the table name (including $wpdb->prefix) for the table alias
5025
-     *
5026
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5027
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5028
-     *                            Either one works
5029
-     * @return string
5030
-     */
5031
-    public function get_table_for_alias($table_alias)
5032
-    {
5033
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5034
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5035
-    }
5036
-
5037
-
5038
-
5039
-    /**
5040
-     * Returns a flat array of all field son this model, instead of organizing them
5041
-     * by table_alias as they are in the constructor.
5042
-     *
5043
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5044
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5045
-     */
5046
-    public function field_settings($include_db_only_fields = false)
5047
-    {
5048
-        if ($include_db_only_fields) {
5049
-            if ($this->_cached_fields === null) {
5050
-                $this->_cached_fields = array();
5051
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5052
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5053
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5054
-                    }
5055
-                }
5056
-            }
5057
-            return $this->_cached_fields;
5058
-        }
5059
-        if ($this->_cached_fields_non_db_only === null) {
5060
-            $this->_cached_fields_non_db_only = array();
5061
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5062
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5063
-                    /** @var $field_obj EE_Model_Field_Base */
5064
-                    if (! $field_obj->is_db_only_field()) {
5065
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5066
-                    }
5067
-                }
5068
-            }
5069
-        }
5070
-        return $this->_cached_fields_non_db_only;
5071
-    }
5072
-
5073
-
5074
-
5075
-    /**
5076
-     *        cycle though array of attendees and create objects out of each item
5077
-     *
5078
-     * @access        private
5079
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5080
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5081
-     *                           numerically indexed)
5082
-     * @throws EE_Error
5083
-     */
5084
-    protected function _create_objects($rows = array())
5085
-    {
5086
-        $array_of_objects = array();
5087
-        if (empty($rows)) {
5088
-            return array();
5089
-        }
5090
-        $count_if_model_has_no_primary_key = 0;
5091
-        $has_primary_key = $this->has_primary_key_field();
5092
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5093
-        foreach ((array) $rows as $row) {
5094
-            if (empty($row)) {
5095
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5096
-                return array();
5097
-            }
5098
-            // check if we've already set this object in the results array,
5099
-            // in which case there's no need to process it further (again)
5100
-            if ($has_primary_key) {
5101
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5102
-                    $row,
5103
-                    $primary_key_field->get_qualified_column(),
5104
-                    $primary_key_field->get_table_column()
5105
-                );
5106
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5107
-                    continue;
5108
-                }
5109
-            }
5110
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5111
-            if (! $classInstance) {
5112
-                throw new EE_Error(
5113
-                    sprintf(
5114
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5115
-                        $this->get_this_model_name(),
5116
-                        http_build_query($row)
5117
-                    )
5118
-                );
5119
-            }
5120
-            // set the timezone on the instantiated objects
5121
-            $classInstance->set_timezone($this->_timezone);
5122
-            // make sure if there is any timezone setting present that we set the timezone for the object
5123
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5124
-            $array_of_objects[ $key ] = $classInstance;
5125
-            // also, for all the relations of type BelongsTo, see if we can cache
5126
-            // those related models
5127
-            // (we could do this for other relations too, but if there are conditions
5128
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5129
-            // so it requires a little more thought than just caching them immediately...)
5130
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5131
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5132
-                    // check if this model's INFO is present. If so, cache it on the model
5133
-                    $other_model = $relation_obj->get_other_model();
5134
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5135
-                    // if we managed to make a model object from the results, cache it on the main model object
5136
-                    if ($other_model_obj_maybe) {
5137
-                        // set timezone on these other model objects if they are present
5138
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5139
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5140
-                    }
5141
-                }
5142
-            }
5143
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5144
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5145
-            // the field in the CustomSelects object
5146
-            if ($this->_custom_selections instanceof CustomSelects) {
5147
-                $classInstance->setCustomSelectsValues(
5148
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5149
-                );
5150
-            }
5151
-        }
5152
-        return $array_of_objects;
5153
-    }
5154
-
5155
-
5156
-    /**
5157
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5158
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5159
-     *
5160
-     * @param array $db_results_row
5161
-     * @return array
5162
-     */
5163
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5164
-    {
5165
-        $results = array();
5166
-        if ($this->_custom_selections instanceof CustomSelects) {
5167
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5168
-                if (isset($db_results_row[ $alias ])) {
5169
-                    $results[ $alias ] = $this->convertValueToDataType(
5170
-                        $db_results_row[ $alias ],
5171
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5172
-                    );
5173
-                }
5174
-            }
5175
-        }
5176
-        return $results;
5177
-    }
5178
-
5179
-
5180
-    /**
5181
-     * This will set the value for the given alias
5182
-     * @param string $value
5183
-     * @param string $datatype (one of %d, %s, %f)
5184
-     * @return int|string|float (int for %d, string for %s, float for %f)
5185
-     */
5186
-    protected function convertValueToDataType($value, $datatype)
5187
-    {
5188
-        switch ($datatype) {
5189
-            case '%f':
5190
-                return (float) $value;
5191
-            case '%d':
5192
-                return (int) $value;
5193
-            default:
5194
-                return (string) $value;
5195
-        }
5196
-    }
5197
-
5198
-
5199
-    /**
5200
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5201
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5202
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5203
-     * object (as set in the model_field!).
5204
-     *
5205
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5206
-     */
5207
-    public function create_default_object()
5208
-    {
5209
-        $this_model_fields_and_values = array();
5210
-        // setup the row using default values;
5211
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5212
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5213
-        }
5214
-        $className = $this->_get_class_name();
5215
-        $classInstance = EE_Registry::instance()
5216
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5217
-        return $classInstance;
5218
-    }
5219
-
5220
-
5221
-
5222
-    /**
5223
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5224
-     *                             or an stdClass where each property is the name of a column,
5225
-     * @return EE_Base_Class
5226
-     * @throws EE_Error
5227
-     */
5228
-    public function instantiate_class_from_array_or_object($cols_n_values)
5229
-    {
5230
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5231
-            $cols_n_values = get_object_vars($cols_n_values);
5232
-        }
5233
-        $primary_key = null;
5234
-        // make sure the array only has keys that are fields/columns on this model
5235
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5236
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5237
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5238
-        }
5239
-        $className = $this->_get_class_name();
5240
-        // check we actually found results that we can use to build our model object
5241
-        // if not, return null
5242
-        if ($this->has_primary_key_field()) {
5243
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
-                return null;
5245
-            }
5246
-        } elseif ($this->unique_indexes()) {
5247
-            $first_column = reset($this_model_fields_n_values);
5248
-            if (empty($first_column)) {
5249
-                return null;
5250
-            }
5251
-        }
5252
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5253
-        if ($primary_key) {
5254
-            $classInstance = $this->get_from_entity_map($primary_key);
5255
-            if (! $classInstance) {
5256
-                $classInstance = EE_Registry::instance()
5257
-                                            ->load_class(
5258
-                                                $className,
5259
-                                                array($this_model_fields_n_values, $this->_timezone),
5260
-                                                true,
5261
-                                                false
5262
-                                            );
5263
-                // add this new object to the entity map
5264
-                $classInstance = $this->add_to_entity_map($classInstance);
5265
-            }
5266
-        } else {
5267
-            $classInstance = EE_Registry::instance()
5268
-                                        ->load_class(
5269
-                                            $className,
5270
-                                            array($this_model_fields_n_values, $this->_timezone),
5271
-                                            true,
5272
-                                            false
5273
-                                        );
5274
-        }
5275
-        return $classInstance;
5276
-    }
5277
-
5278
-
5279
-
5280
-    /**
5281
-     * Gets the model object from the  entity map if it exists
5282
-     *
5283
-     * @param int|string $id the ID of the model object
5284
-     * @return EE_Base_Class
5285
-     */
5286
-    public function get_from_entity_map($id)
5287
-    {
5288
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5289
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5290
-    }
5291
-
5292
-
5293
-
5294
-    /**
5295
-     * add_to_entity_map
5296
-     * Adds the object to the model's entity mappings
5297
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5298
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5299
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5300
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5301
-     *        then this method should be called immediately after the update query
5302
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5303
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5304
-     *
5305
-     * @param    EE_Base_Class $object
5306
-     * @throws EE_Error
5307
-     * @return \EE_Base_Class
5308
-     */
5309
-    public function add_to_entity_map(EE_Base_Class $object)
5310
-    {
5311
-        $className = $this->_get_class_name();
5312
-        if (! $object instanceof $className) {
5313
-            throw new EE_Error(sprintf(
5314
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5315
-                is_object($object) ? get_class($object) : $object,
5316
-                $className
5317
-            ));
5318
-        }
5319
-        /** @var $object EE_Base_Class */
5320
-        if (! $object->ID()) {
5321
-            throw new EE_Error(sprintf(__(
5322
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5323
-                "event_espresso"
5324
-            ), get_class($this)));
5325
-        }
5326
-        // double check it's not already there
5327
-        $classInstance = $this->get_from_entity_map($object->ID());
5328
-        if ($classInstance) {
5329
-            return $classInstance;
5330
-        }
5331
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5332
-        return $object;
5333
-    }
5334
-
5335
-
5336
-
5337
-    /**
5338
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5339
-     * if no identifier is provided, then the entire entity map is emptied
5340
-     *
5341
-     * @param int|string $id the ID of the model object
5342
-     * @return boolean
5343
-     */
5344
-    public function clear_entity_map($id = null)
5345
-    {
5346
-        if (empty($id)) {
5347
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5348
-            return true;
5349
-        }
5350
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5351
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5352
-            return true;
5353
-        }
5354
-        return false;
5355
-    }
5356
-
5357
-
5358
-
5359
-    /**
5360
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5361
-     * Given an array where keys are column (or column alias) names and values,
5362
-     * returns an array of their corresponding field names and database values
5363
-     *
5364
-     * @param array $cols_n_values
5365
-     * @return array
5366
-     */
5367
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5368
-    {
5369
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5370
-    }
5371
-
5372
-
5373
-
5374
-    /**
5375
-     * _deduce_fields_n_values_from_cols_n_values
5376
-     * Given an array where keys are column (or column alias) names and values,
5377
-     * returns an array of their corresponding field names and database values
5378
-     *
5379
-     * @param string $cols_n_values
5380
-     * @return array
5381
-     */
5382
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5383
-    {
5384
-        $this_model_fields_n_values = array();
5385
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5386
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5387
-                $cols_n_values,
5388
-                $table_obj->get_fully_qualified_pk_column(),
5389
-                $table_obj->get_pk_column()
5390
-            );
5391
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5392
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5393
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5394
-                    if (! $field_obj->is_db_only_field()) {
5395
-                        // prepare field as if its coming from db
5396
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5397
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5398
-                    }
5399
-                }
5400
-            } else {
5401
-                // the table's rows existed. Use their values
5402
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5403
-                    if (! $field_obj->is_db_only_field()) {
5404
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5405
-                            $cols_n_values,
5406
-                            $field_obj->get_qualified_column(),
5407
-                            $field_obj->get_table_column()
5408
-                        );
5409
-                    }
5410
-                }
5411
-            }
5412
-        }
5413
-        return $this_model_fields_n_values;
5414
-    }
5415
-
5416
-
5417
-
5418
-    /**
5419
-     * @param $cols_n_values
5420
-     * @param $qualified_column
5421
-     * @param $regular_column
5422
-     * @return null
5423
-     */
5424
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5425
-    {
5426
-        $value = null;
5427
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5428
-        // does the field on the model relate to this column retrieved from the db?
5429
-        // or is it a db-only field? (not relating to the model)
5430
-        if (isset($cols_n_values[ $qualified_column ])) {
5431
-            $value = $cols_n_values[ $qualified_column ];
5432
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5433
-            $value = $cols_n_values[ $regular_column ];
5434
-        } elseif (! empty($this->foreign_key_aliases)) {
5435
-            // no PK?  ok check if there is a foreign key alias set for this table
5436
-            // then check if that alias exists in the incoming data
5437
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5438
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5439
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5440
-                    $value = $cols_n_values[ $FK_alias ];
5441
-                    break;
5442
-                }
5443
-            }
5444
-        }
5445
-        return $value;
5446
-    }
5447
-
5448
-
5449
-
5450
-    /**
5451
-     * refresh_entity_map_from_db
5452
-     * Makes sure the model object in the entity map at $id assumes the values
5453
-     * of the database (opposite of EE_base_Class::save())
5454
-     *
5455
-     * @param int|string $id
5456
-     * @return EE_Base_Class
5457
-     * @throws EE_Error
5458
-     */
5459
-    public function refresh_entity_map_from_db($id)
5460
-    {
5461
-        $obj_in_map = $this->get_from_entity_map($id);
5462
-        if ($obj_in_map) {
5463
-            $wpdb_results = $this->_get_all_wpdb_results(
5464
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5465
-            );
5466
-            if ($wpdb_results && is_array($wpdb_results)) {
5467
-                $one_row = reset($wpdb_results);
5468
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5469
-                    $obj_in_map->set_from_db($field_name, $db_value);
5470
-                }
5471
-                // clear the cache of related model objects
5472
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5473
-                    $obj_in_map->clear_cache($relation_name, null, true);
5474
-                }
5475
-            }
5476
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5477
-            return $obj_in_map;
5478
-        }
5479
-        return $this->get_one_by_ID($id);
5480
-    }
5481
-
5482
-
5483
-
5484
-    /**
5485
-     * refresh_entity_map_with
5486
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5487
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5488
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5489
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5490
-     *
5491
-     * @param int|string    $id
5492
-     * @param EE_Base_Class $replacing_model_obj
5493
-     * @return \EE_Base_Class
5494
-     * @throws EE_Error
5495
-     */
5496
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5497
-    {
5498
-        $obj_in_map = $this->get_from_entity_map($id);
5499
-        if ($obj_in_map) {
5500
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5501
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5502
-                    $obj_in_map->set($field_name, $value);
5503
-                }
5504
-                // make the model object in the entity map's cache match the $replacing_model_obj
5505
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
-                    $obj_in_map->clear_cache($relation_name, null, true);
5507
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5508
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5509
-                    }
5510
-                }
5511
-            }
5512
-            return $obj_in_map;
5513
-        }
5514
-        $this->add_to_entity_map($replacing_model_obj);
5515
-        return $replacing_model_obj;
5516
-    }
5517
-
5518
-
5519
-
5520
-    /**
5521
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5522
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5523
-     * require_once($this->_getClassName().".class.php");
5524
-     *
5525
-     * @return string
5526
-     */
5527
-    private function _get_class_name()
5528
-    {
5529
-        return "EE_" . $this->get_this_model_name();
5530
-    }
5531
-
5532
-
5533
-
5534
-    /**
5535
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5536
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5537
-     * it would be 'Events'.
5538
-     *
5539
-     * @param int $quantity
5540
-     * @return string
5541
-     */
5542
-    public function item_name($quantity = 1)
5543
-    {
5544
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5545
-    }
5546
-
5547
-
5548
-
5549
-    /**
5550
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5551
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5552
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5553
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5554
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5555
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5556
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5557
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5558
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5559
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5560
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5561
-     *        return $previousReturnValue.$returnString;
5562
-     * }
5563
-     * require('EEM_Answer.model.php');
5564
-     * $answer=EEM_Answer::instance();
5565
-     * echo $answer->my_callback('monkeys',100);
5566
-     * //will output "you called my_callback! and passed args:monkeys,100"
5567
-     *
5568
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5569
-     * @param array  $args       array of original arguments passed to the function
5570
-     * @throws EE_Error
5571
-     * @return mixed whatever the plugin which calls add_filter decides
5572
-     */
5573
-    public function __call($methodName, $args)
5574
-    {
5575
-        $className = get_class($this);
5576
-        $tagName = "FHEE__{$className}__{$methodName}";
5577
-        if (! has_filter($tagName)) {
5578
-            throw new EE_Error(
5579
-                sprintf(
5580
-                    __(
5581
-                        '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 );',
5582
-                        'event_espresso'
5583
-                    ),
5584
-                    $methodName,
5585
-                    $className,
5586
-                    $tagName,
5587
-                    '<br />'
5588
-                )
5589
-            );
5590
-        }
5591
-        return apply_filters($tagName, null, $this, $args);
5592
-    }
5593
-
5594
-
5595
-
5596
-    /**
5597
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5598
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5599
-     *
5600
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5601
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5602
-     *                                                       the object's class name
5603
-     *                                                       or object's ID
5604
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5605
-     *                                                       exists in the database. If it does not, we add it
5606
-     * @throws EE_Error
5607
-     * @return EE_Base_Class
5608
-     */
5609
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5610
-    {
5611
-        $className = $this->_get_class_name();
5612
-        if ($base_class_obj_or_id instanceof $className) {
5613
-            $model_object = $base_class_obj_or_id;
5614
-        } else {
5615
-            $primary_key_field = $this->get_primary_key_field();
5616
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5617
-                && (
5618
-                    is_int($base_class_obj_or_id)
5619
-                    || is_string($base_class_obj_or_id)
5620
-                )
5621
-            ) {
5622
-                // assume it's an ID.
5623
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5624
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5625
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5626
-                && is_string($base_class_obj_or_id)
5627
-            ) {
5628
-                // assume its a string representation of the object
5629
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5630
-            } else {
5631
-                throw new EE_Error(
5632
-                    sprintf(
5633
-                        __(
5634
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5635
-                            'event_espresso'
5636
-                        ),
5637
-                        $base_class_obj_or_id,
5638
-                        $this->_get_class_name(),
5639
-                        print_r($base_class_obj_or_id, true)
5640
-                    )
5641
-                );
5642
-            }
5643
-        }
5644
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5645
-            $model_object->save();
5646
-        }
5647
-        return $model_object;
5648
-    }
5649
-
5650
-
5651
-
5652
-    /**
5653
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5654
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5655
-     * returns it ID.
5656
-     *
5657
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5658
-     * @return int|string depending on the type of this model object's ID
5659
-     * @throws EE_Error
5660
-     */
5661
-    public function ensure_is_ID($base_class_obj_or_id)
5662
-    {
5663
-        $className = $this->_get_class_name();
5664
-        if ($base_class_obj_or_id instanceof $className) {
5665
-            /** @var $base_class_obj_or_id EE_Base_Class */
5666
-            $id = $base_class_obj_or_id->ID();
5667
-        } elseif (is_int($base_class_obj_or_id)) {
5668
-            // assume it's an ID
5669
-            $id = $base_class_obj_or_id;
5670
-        } elseif (is_string($base_class_obj_or_id)) {
5671
-            // assume its a string representation of the object
5672
-            $id = $base_class_obj_or_id;
5673
-        } else {
5674
-            throw new EE_Error(sprintf(
5675
-                __(
5676
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5677
-                    'event_espresso'
5678
-                ),
5679
-                $base_class_obj_or_id,
5680
-                $this->_get_class_name(),
5681
-                print_r($base_class_obj_or_id, true)
5682
-            ));
5683
-        }
5684
-        return $id;
5685
-    }
5686
-
5687
-
5688
-
5689
-    /**
5690
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5691
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5692
-     * been sanitized and converted into the appropriate domain.
5693
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5694
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5695
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5696
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5697
-     * $EVT = EEM_Event::instance(); $old_setting =
5698
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5699
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5700
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5701
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5702
-     *
5703
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5704
-     * @return void
5705
-     */
5706
-    public function assume_values_already_prepared_by_model_object(
5707
-        $values_already_prepared = self::not_prepared_by_model_object
5708
-    ) {
5709
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5710
-    }
5711
-
5712
-
5713
-
5714
-    /**
5715
-     * Read comments for assume_values_already_prepared_by_model_object()
5716
-     *
5717
-     * @return int
5718
-     */
5719
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5720
-    {
5721
-        return $this->_values_already_prepared_by_model_object;
5722
-    }
5723
-
5724
-
5725
-
5726
-    /**
5727
-     * Gets all the indexes on this model
5728
-     *
5729
-     * @return EE_Index[]
5730
-     */
5731
-    public function indexes()
5732
-    {
5733
-        return $this->_indexes;
5734
-    }
5735
-
5736
-
5737
-
5738
-    /**
5739
-     * Gets all the Unique Indexes on this model
5740
-     *
5741
-     * @return EE_Unique_Index[]
5742
-     */
5743
-    public function unique_indexes()
5744
-    {
5745
-        $unique_indexes = array();
5746
-        foreach ($this->_indexes as $name => $index) {
5747
-            if ($index instanceof EE_Unique_Index) {
5748
-                $unique_indexes [ $name ] = $index;
5749
-            }
5750
-        }
5751
-        return $unique_indexes;
5752
-    }
5753
-
5754
-
5755
-
5756
-    /**
5757
-     * Gets all the fields which, when combined, make the primary key.
5758
-     * This is usually just an array with 1 element (the primary key), but in cases
5759
-     * where there is no primary key, it's a combination of fields as defined
5760
-     * on a primary index
5761
-     *
5762
-     * @return EE_Model_Field_Base[] indexed by the field's name
5763
-     * @throws EE_Error
5764
-     */
5765
-    public function get_combined_primary_key_fields()
5766
-    {
5767
-        foreach ($this->indexes() as $index) {
5768
-            if ($index instanceof EE_Primary_Key_Index) {
5769
-                return $index->fields();
5770
-            }
5771
-        }
5772
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5773
-    }
5774
-
5775
-
5776
-
5777
-    /**
5778
-     * Used to build a primary key string (when the model has no primary key),
5779
-     * which can be used a unique string to identify this model object.
5780
-     *
5781
-     * @param array $fields_n_values keys are field names, values are their values.
5782
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5783
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5784
-     *                               before passing it to this function (that will convert it from columns-n-values
5785
-     *                               to field-names-n-values).
5786
-     * @return string
5787
-     * @throws EE_Error
5788
-     */
5789
-    public function get_index_primary_key_string($fields_n_values)
5790
-    {
5791
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5792
-            $fields_n_values,
5793
-            $this->get_combined_primary_key_fields()
5794
-        );
5795
-        return http_build_query($cols_n_values_for_primary_key_index);
5796
-    }
5797
-
5798
-
5799
-
5800
-    /**
5801
-     * Gets the field values from the primary key string
5802
-     *
5803
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5804
-     * @param string $index_primary_key_string
5805
-     * @return null|array
5806
-     * @throws EE_Error
5807
-     */
5808
-    public function parse_index_primary_key_string($index_primary_key_string)
5809
-    {
5810
-        $key_fields = $this->get_combined_primary_key_fields();
5811
-        // check all of them are in the $id
5812
-        $key_vals_in_combined_pk = array();
5813
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5814
-        foreach ($key_fields as $key_field_name => $field_obj) {
5815
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5816
-                return null;
5817
-            }
5818
-        }
5819
-        return $key_vals_in_combined_pk;
5820
-    }
5821
-
5822
-
5823
-
5824
-    /**
5825
-     * verifies that an array of key-value pairs for model fields has a key
5826
-     * for each field comprising the primary key index
5827
-     *
5828
-     * @param array $key_vals
5829
-     * @return boolean
5830
-     * @throws EE_Error
5831
-     */
5832
-    public function has_all_combined_primary_key_fields($key_vals)
5833
-    {
5834
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5835
-        foreach ($keys_it_should_have as $key) {
5836
-            if (! isset($key_vals[ $key ])) {
5837
-                return false;
5838
-            }
5839
-        }
5840
-        return true;
5841
-    }
5842
-
5843
-
5844
-
5845
-    /**
5846
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5847
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5848
-     *
5849
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5850
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5851
-     * @throws EE_Error
5852
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5853
-     *                                                              indexed)
5854
-     */
5855
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5856
-    {
5857
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5858
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5859
-        } elseif (is_array($model_object_or_attributes_array)) {
5860
-            $attributes_array = $model_object_or_attributes_array;
5861
-        } else {
5862
-            throw new EE_Error(sprintf(__(
5863
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5864
-                "event_espresso"
5865
-            ), $model_object_or_attributes_array));
5866
-        }
5867
-        // even copies obviously won't have the same ID, so remove the primary key
5868
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5869
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5870
-            unset($attributes_array[ $this->primary_key_name() ]);
5871
-        }
5872
-        if (isset($query_params[0])) {
5873
-            $query_params[0] = array_merge($attributes_array, $query_params);
5874
-        } else {
5875
-            $query_params[0] = $attributes_array;
5876
-        }
5877
-        return $this->get_all($query_params);
5878
-    }
5879
-
5880
-
5881
-
5882
-    /**
5883
-     * Gets the first copy we find. See get_all_copies for more details
5884
-     *
5885
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5886
-     * @param array $query_params
5887
-     * @return EE_Base_Class
5888
-     * @throws EE_Error
5889
-     */
5890
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5891
-    {
5892
-        if (! is_array($query_params)) {
5893
-            EE_Error::doing_it_wrong(
5894
-                'EEM_Base::get_one_copy',
5895
-                sprintf(
5896
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5897
-                    gettype($query_params)
5898
-                ),
5899
-                '4.6.0'
5900
-            );
5901
-            $query_params = array();
5902
-        }
5903
-        $query_params['limit'] = 1;
5904
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5905
-        if (is_array($copies)) {
5906
-            return array_shift($copies);
5907
-        }
5908
-        return null;
5909
-    }
5910
-
5911
-
5912
-
5913
-    /**
5914
-     * Updates the item with the specified id. Ignores default query parameters because
5915
-     * we have specified the ID, and its assumed we KNOW what we're doing
5916
-     *
5917
-     * @param array      $fields_n_values keys are field names, values are their new values
5918
-     * @param int|string $id              the value of the primary key to update
5919
-     * @return int number of rows updated
5920
-     * @throws EE_Error
5921
-     */
5922
-    public function update_by_ID($fields_n_values, $id)
5923
-    {
5924
-        $query_params = array(
5925
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5926
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5927
-        );
5928
-        return $this->update($fields_n_values, $query_params);
5929
-    }
5930
-
5931
-
5932
-
5933
-    /**
5934
-     * Changes an operator which was supplied to the models into one usable in SQL
5935
-     *
5936
-     * @param string $operator_supplied
5937
-     * @return string an operator which can be used in SQL
5938
-     * @throws EE_Error
5939
-     */
5940
-    private function _prepare_operator_for_sql($operator_supplied)
5941
-    {
5942
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5943
-            : null;
5944
-        if ($sql_operator) {
5945
-            return $sql_operator;
5946
-        }
5947
-        throw new EE_Error(
5948
-            sprintf(
5949
-                __(
5950
-                    "The operator '%s' is not in the list of valid operators: %s",
5951
-                    "event_espresso"
5952
-                ),
5953
-                $operator_supplied,
5954
-                implode(",", array_keys($this->_valid_operators))
5955
-            )
5956
-        );
5957
-    }
5958
-
5959
-
5960
-
5961
-    /**
5962
-     * Gets the valid operators
5963
-     * @return array keys are accepted strings, values are the SQL they are converted to
5964
-     */
5965
-    public function valid_operators()
5966
-    {
5967
-        return $this->_valid_operators;
5968
-    }
5969
-
5970
-
5971
-
5972
-    /**
5973
-     * Gets the between-style operators (take 2 arguments).
5974
-     * @return array keys are accepted strings, values are the SQL they are converted to
5975
-     */
5976
-    public function valid_between_style_operators()
5977
-    {
5978
-        return array_intersect(
5979
-            $this->valid_operators(),
5980
-            $this->_between_style_operators
5981
-        );
5982
-    }
5983
-
5984
-    /**
5985
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5986
-     * @return array keys are accepted strings, values are the SQL they are converted to
5987
-     */
5988
-    public function valid_like_style_operators()
5989
-    {
5990
-        return array_intersect(
5991
-            $this->valid_operators(),
5992
-            $this->_like_style_operators
5993
-        );
5994
-    }
5995
-
5996
-    /**
5997
-     * Gets the "in"-style operators
5998
-     * @return array keys are accepted strings, values are the SQL they are converted to
5999
-     */
6000
-    public function valid_in_style_operators()
6001
-    {
6002
-        return array_intersect(
6003
-            $this->valid_operators(),
6004
-            $this->_in_style_operators
6005
-        );
6006
-    }
6007
-
6008
-    /**
6009
-     * Gets the "null"-style operators (accept no arguments)
6010
-     * @return array keys are accepted strings, values are the SQL they are converted to
6011
-     */
6012
-    public function valid_null_style_operators()
6013
-    {
6014
-        return array_intersect(
6015
-            $this->valid_operators(),
6016
-            $this->_null_style_operators
6017
-        );
6018
-    }
6019
-
6020
-    /**
6021
-     * Gets an array where keys are the primary keys and values are their 'names'
6022
-     * (as determined by the model object's name() function, which is often overridden)
6023
-     *
6024
-     * @param array $query_params like get_all's
6025
-     * @return string[]
6026
-     * @throws EE_Error
6027
-     */
6028
-    public function get_all_names($query_params = array())
6029
-    {
6030
-        $objs = $this->get_all($query_params);
6031
-        $names = array();
6032
-        foreach ($objs as $obj) {
6033
-            $names[ $obj->ID() ] = $obj->name();
6034
-        }
6035
-        return $names;
6036
-    }
6037
-
6038
-
6039
-
6040
-    /**
6041
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6042
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6043
-     * this is duplicated effort and reduces efficiency) you would be better to use
6044
-     * array_keys() on $model_objects.
6045
-     *
6046
-     * @param \EE_Base_Class[] $model_objects
6047
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6048
-     *                                               in the returned array
6049
-     * @return array
6050
-     * @throws EE_Error
6051
-     */
6052
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6053
-    {
6054
-        if (! $this->has_primary_key_field()) {
6055
-            if (WP_DEBUG) {
6056
-                EE_Error::add_error(
6057
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6058
-                    __FILE__,
6059
-                    __FUNCTION__,
6060
-                    __LINE__
6061
-                );
6062
-            }
6063
-        }
6064
-        $IDs = array();
6065
-        foreach ($model_objects as $model_object) {
6066
-            $id = $model_object->ID();
6067
-            if (! $id) {
6068
-                if ($filter_out_empty_ids) {
6069
-                    continue;
6070
-                }
6071
-                if (WP_DEBUG) {
6072
-                    EE_Error::add_error(
6073
-                        __(
6074
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6075
-                            'event_espresso'
6076
-                        ),
6077
-                        __FILE__,
6078
-                        __FUNCTION__,
6079
-                        __LINE__
6080
-                    );
6081
-                }
6082
-            }
6083
-            $IDs[] = $id;
6084
-        }
6085
-        return $IDs;
6086
-    }
6087
-
6088
-
6089
-
6090
-    /**
6091
-     * Returns the string used in capabilities relating to this model. If there
6092
-     * are no capabilities that relate to this model returns false
6093
-     *
6094
-     * @return string|false
6095
-     */
6096
-    public function cap_slug()
6097
-    {
6098
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6099
-    }
6100
-
6101
-
6102
-
6103
-    /**
6104
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6105
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6106
-     * only returns the cap restrictions array in that context (ie, the array
6107
-     * at that key)
6108
-     *
6109
-     * @param string $context
6110
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6111
-     * @throws EE_Error
6112
-     */
6113
-    public function cap_restrictions($context = EEM_Base::caps_read)
6114
-    {
6115
-        EEM_Base::verify_is_valid_cap_context($context);
6116
-        // check if we ought to run the restriction generator first
6117
-        if (isset($this->_cap_restriction_generators[ $context ])
6118
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6119
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6120
-        ) {
6121
-            $this->_cap_restrictions[ $context ] = array_merge(
6122
-                $this->_cap_restrictions[ $context ],
6123
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6124
-            );
6125
-        }
6126
-        // and make sure we've finalized the construction of each restriction
6127
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6128
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6129
-                $where_conditions_obj->_finalize_construct($this);
6130
-            }
6131
-        }
6132
-        return $this->_cap_restrictions[ $context ];
6133
-    }
6134
-
6135
-
6136
-
6137
-    /**
6138
-     * Indicating whether or not this model thinks its a wp core model
6139
-     *
6140
-     * @return boolean
6141
-     */
6142
-    public function is_wp_core_model()
6143
-    {
6144
-        return $this->_wp_core_model;
6145
-    }
6146
-
6147
-
6148
-
6149
-    /**
6150
-     * Gets all the caps that are missing which impose a restriction on
6151
-     * queries made in this context
6152
-     *
6153
-     * @param string $context one of EEM_Base::caps_ constants
6154
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6155
-     * @throws EE_Error
6156
-     */
6157
-    public function caps_missing($context = EEM_Base::caps_read)
6158
-    {
6159
-        $missing_caps = array();
6160
-        $cap_restrictions = $this->cap_restrictions($context);
6161
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6162
-            if (! EE_Capabilities::instance()
6163
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6164
-            ) {
6165
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6166
-            }
6167
-        }
6168
-        return $missing_caps;
6169
-    }
6170
-
6171
-
6172
-
6173
-    /**
6174
-     * Gets the mapping from capability contexts to action strings used in capability names
6175
-     *
6176
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6177
-     * one of 'read', 'edit', or 'delete'
6178
-     */
6179
-    public function cap_contexts_to_cap_action_map()
6180
-    {
6181
-        return apply_filters(
6182
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6183
-            $this->_cap_contexts_to_cap_action_map,
6184
-            $this
6185
-        );
6186
-    }
6187
-
6188
-
6189
-
6190
-    /**
6191
-     * Gets the action string for the specified capability context
6192
-     *
6193
-     * @param string $context
6194
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6195
-     * @throws EE_Error
6196
-     */
6197
-    public function cap_action_for_context($context)
6198
-    {
6199
-        $mapping = $this->cap_contexts_to_cap_action_map();
6200
-        if (isset($mapping[ $context ])) {
6201
-            return $mapping[ $context ];
6202
-        }
6203
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6204
-            return $action;
6205
-        }
6206
-        throw new EE_Error(
6207
-            sprintf(
6208
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6209
-                $context,
6210
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6211
-            )
6212
-        );
6213
-    }
6214
-
6215
-
6216
-
6217
-    /**
6218
-     * Returns all the capability contexts which are valid when querying models
6219
-     *
6220
-     * @return array
6221
-     */
6222
-    public static function valid_cap_contexts()
6223
-    {
6224
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6225
-            self::caps_read,
6226
-            self::caps_read_admin,
6227
-            self::caps_edit,
6228
-            self::caps_delete,
6229
-        ));
6230
-    }
6231
-
6232
-
6233
-
6234
-    /**
6235
-     * Returns all valid options for 'default_where_conditions'
6236
-     *
6237
-     * @return array
6238
-     */
6239
-    public static function valid_default_where_conditions()
6240
-    {
6241
-        return array(
6242
-            EEM_Base::default_where_conditions_all,
6243
-            EEM_Base::default_where_conditions_this_only,
6244
-            EEM_Base::default_where_conditions_others_only,
6245
-            EEM_Base::default_where_conditions_minimum_all,
6246
-            EEM_Base::default_where_conditions_minimum_others,
6247
-            EEM_Base::default_where_conditions_none
6248
-        );
6249
-    }
6250
-
6251
-    // public static function default_where_conditions_full
6252
-    /**
6253
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6254
-     *
6255
-     * @param string $context
6256
-     * @return bool
6257
-     * @throws EE_Error
6258
-     */
6259
-    public static function verify_is_valid_cap_context($context)
6260
-    {
6261
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6262
-        if (in_array($context, $valid_cap_contexts)) {
6263
-            return true;
6264
-        }
6265
-        throw new EE_Error(
6266
-            sprintf(
6267
-                __(
6268
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6269
-                    'event_espresso'
6270
-                ),
6271
-                $context,
6272
-                'EEM_Base',
6273
-                implode(',', $valid_cap_contexts)
6274
-            )
6275
-        );
6276
-    }
6277
-
6278
-
6279
-
6280
-    /**
6281
-     * Clears all the models field caches. This is only useful when a sub-class
6282
-     * might have added a field or something and these caches might be invalidated
6283
-     */
6284
-    protected function _invalidate_field_caches()
6285
-    {
6286
-        $this->_cache_foreign_key_to_fields = array();
6287
-        $this->_cached_fields = null;
6288
-        $this->_cached_fields_non_db_only = null;
6289
-    }
6290
-
6291
-
6292
-
6293
-    /**
6294
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6295
-     * (eg "and", "or", "not").
6296
-     *
6297
-     * @return array
6298
-     */
6299
-    public function logic_query_param_keys()
6300
-    {
6301
-        return $this->_logic_query_param_keys;
6302
-    }
6303
-
6304
-
6305
-
6306
-    /**
6307
-     * Determines whether or not the where query param array key is for a logic query param.
6308
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6309
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6310
-     *
6311
-     * @param $query_param_key
6312
-     * @return bool
6313
-     */
6314
-    public function is_logic_query_param_key($query_param_key)
6315
-    {
6316
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6317
-            if ($query_param_key === $logic_query_param_key
6318
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6319
-            ) {
6320
-                return true;
6321
-            }
6322
-        }
6323
-        return false;
6324
-    }
6325
-
6326
-    /**
6327
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6328
-     * @since 4.9.74.p
6329
-     * @return boolean
6330
-     */
6331
-    public function hasPassword()
6332
-    {
6333
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6334
-        if ($this->has_password_field === null) {
6335
-            $password_field = $this->getPasswordField();
6336
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6337
-        }
6338
-        return $this->has_password_field;
6339
-    }
6340
-
6341
-    /**
6342
-     * Returns the password field on this model, if there is one
6343
-     * @since 4.9.74.p
6344
-     * @return EE_Password_Field|null
6345
-     */
6346
-    public function getPasswordField()
6347
-    {
6348
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6349
-        // there's no need to search for it. If we don't know yet, then find out
6350
-        if ($this->has_password_field === null && $this->password_field === null) {
6351
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6352
-        }
6353
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6354
-        return $this->password_field;
6355
-    }
6356
-
6357
-
6358
-    /**
6359
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6360
-     * @since 4.9.74.p
6361
-     * @return EE_Model_Field_Base[]
6362
-     * @throws EE_Error
6363
-     */
6364
-    public function getPasswordProtectedFields()
6365
-    {
6366
-        $password_field = $this->getPasswordField();
6367
-        $fields = array();
6368
-        if ($password_field instanceof EE_Password_Field) {
6369
-            $field_names = $password_field->protectedFields();
6370
-            foreach ($field_names as $field_name) {
6371
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6372
-            }
6373
-        }
6374
-        return $fields;
6375
-    }
6376
-
6377
-
6378
-    /**
6379
-     * Checks if the current user can perform the requested action on this model
6380
-     * @since 4.9.74.p
6381
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6382
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6383
-     * @return bool
6384
-     * @throws EE_Error
6385
-     * @throws InvalidArgumentException
6386
-     * @throws InvalidDataTypeException
6387
-     * @throws InvalidInterfaceException
6388
-     * @throws ReflectionException
6389
-     * @throws UnexpectedEntityException
6390
-     */
6391
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6392
-    {
6393
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6394
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6395
-        }
6396
-        if (!is_array($model_obj_or_fields_n_values)) {
6397
-            throw new UnexpectedEntityException(
6398
-                $model_obj_or_fields_n_values,
6399
-                'EE_Base_Class',
6400
-                sprintf(
6401
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6402
-                    __FUNCTION__
6403
-                )
6404
-            );
6405
-        }
6406
-        return $this->exists(
6407
-            $this->alter_query_params_to_restrict_by_ID(
6408
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6409
-                array(
6410
-                    'default_where_conditions' => 'none',
6411
-                    'caps'                     => $cap_to_check,
6412
-                )
6413
-            )
6414
-        );
6415
-    }
6416
-
6417
-    /**
6418
-     * Returns the query param where conditions key to the password affecting this model.
6419
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6420
-     * @since 4.9.74.p
6421
-     * @return null|string
6422
-     * @throws EE_Error
6423
-     * @throws InvalidArgumentException
6424
-     * @throws InvalidDataTypeException
6425
-     * @throws InvalidInterfaceException
6426
-     * @throws ModelConfigurationException
6427
-     * @throws ReflectionException
6428
-     */
6429
-    public function modelChainAndPassword()
6430
-    {
6431
-        if ($this->model_chain_to_password === null) {
6432
-            throw new ModelConfigurationException(
6433
-                $this,
6434
-                esc_html_x(
6435
-                // @codingStandardsIgnoreStart
6436
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6437
-                    // @codingStandardsIgnoreEnd
6438
-                    '1: model name',
6439
-                    'event_espresso'
6440
-                )
6441
-            );
6442
-        }
6443
-        if ($this->model_chain_to_password === '') {
6444
-            $model_with_password = $this;
6445
-        } else {
6446
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6447
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6448
-            } else {
6449
-                $last_model_in_chain = $this->model_chain_to_password;
6450
-            }
6451
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6452
-        }
6453
-
6454
-        $password_field = $model_with_password->getPasswordField();
6455
-        if ($password_field instanceof EE_Password_Field) {
6456
-            $password_field_name = $password_field->get_name();
6457
-        } else {
6458
-            throw new ModelConfigurationException(
6459
-                $this,
6460
-                sprintf(
6461
-                    esc_html_x(
6462
-                        '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"',
6463
-                        '1: model name, 2: special string',
6464
-                        'event_espresso'
6465
-                    ),
6466
-                    $model_with_password->get_this_model_name(),
6467
-                    $this->model_chain_to_password
6468
-                )
6469
-            );
6470
-        }
6471
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6472
-    }
6473
-
6474
-    /**
6475
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6476
-     * or if this model itself has a password affecting access to some of its other fields.
6477
-     * @since 4.9.74.p
6478
-     * @return boolean
6479
-     */
6480
-    public function restrictedByRelatedModelPassword()
6481
-    {
6482
-        return $this->model_chain_to_password !== null;
6483
-    }
3797
+		}
3798
+		return $null_friendly_where_conditions;
3799
+	}
3800
+
3801
+
3802
+
3803
+	/**
3804
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3805
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3806
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3807
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3808
+	 *
3809
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3810
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3811
+	 */
3812
+	private function _get_default_where_conditions($model_relation_path = null)
3813
+	{
3814
+		if ($this->_ignore_where_strategy) {
3815
+			return array();
3816
+		}
3817
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3818
+	}
3819
+
3820
+
3821
+
3822
+	/**
3823
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3824
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3825
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3826
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3827
+	 * Similar to _get_default_where_conditions
3828
+	 *
3829
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
+	 */
3832
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3833
+	{
3834
+		if ($this->_ignore_where_strategy) {
3835
+			return array();
3836
+		}
3837
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
+	}
3839
+
3840
+
3841
+
3842
+	/**
3843
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3844
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3845
+	 *
3846
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3847
+	 * @return string
3848
+	 * @throws EE_Error
3849
+	 */
3850
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3851
+	{
3852
+		$selects = $this->_get_columns_to_select_for_this_model();
3853
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3854
+			$name_of_other_model_included) {
3855
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3856
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3857
+			foreach ($other_model_selects as $key => $value) {
3858
+				$selects[] = $value;
3859
+			}
3860
+		}
3861
+		return implode(", ", $selects);
3862
+	}
3863
+
3864
+
3865
+
3866
+	/**
3867
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3868
+	 * So that's going to be the columns for all the fields on the model
3869
+	 *
3870
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3871
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3872
+	 */
3873
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3874
+	{
3875
+		$fields = $this->field_settings();
3876
+		$selects = array();
3877
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3878
+			$model_relation_chain,
3879
+			$this->get_this_model_name()
3880
+		);
3881
+		foreach ($fields as $field_obj) {
3882
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3883
+						 . $field_obj->get_table_alias()
3884
+						 . "."
3885
+						 . $field_obj->get_table_column()
3886
+						 . " AS '"
3887
+						 . $table_alias_with_model_relation_chain_prefix
3888
+						 . $field_obj->get_table_alias()
3889
+						 . "."
3890
+						 . $field_obj->get_table_column()
3891
+						 . "'";
3892
+		}
3893
+		// make sure we are also getting the PKs of each table
3894
+		$tables = $this->get_tables();
3895
+		if (count($tables) > 1) {
3896
+			foreach ($tables as $table_obj) {
3897
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3898
+									   . $table_obj->get_fully_qualified_pk_column();
3899
+				if (! in_array($qualified_pk_column, $selects)) {
3900
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3901
+				}
3902
+			}
3903
+		}
3904
+		return $selects;
3905
+	}
3906
+
3907
+
3908
+
3909
+	/**
3910
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3911
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3912
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3913
+	 * SQL for joining, and the data types
3914
+	 *
3915
+	 * @param null|string                 $original_query_param
3916
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3917
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3918
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3919
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3920
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3921
+	 *                                                          or 'Registration's
3922
+	 * @param string                      $original_query_param what it originally was (eg
3923
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3924
+	 *                                                          matches $query_param
3925
+	 * @throws EE_Error
3926
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3927
+	 */
3928
+	private function _extract_related_model_info_from_query_param(
3929
+		$query_param,
3930
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3931
+		$query_param_type,
3932
+		$original_query_param = null
3933
+	) {
3934
+		if ($original_query_param === null) {
3935
+			$original_query_param = $query_param;
3936
+		}
3937
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3938
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3939
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3940
+		$allow_fields = in_array(
3941
+			$query_param_type,
3942
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3943
+			true
3944
+		);
3945
+		// check to see if we have a field on this model
3946
+		$this_model_fields = $this->field_settings(true);
3947
+		if (array_key_exists($query_param, $this_model_fields)) {
3948
+			if ($allow_fields) {
3949
+				return;
3950
+			}
3951
+			throw new EE_Error(
3952
+				sprintf(
3953
+					__(
3954
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3955
+						"event_espresso"
3956
+					),
3957
+					$query_param,
3958
+					get_class($this),
3959
+					$query_param_type,
3960
+					$original_query_param
3961
+				)
3962
+			);
3963
+		}
3964
+		// check if this is a special logic query param
3965
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3966
+			if ($allow_logic_query_params) {
3967
+				return;
3968
+			}
3969
+			throw new EE_Error(
3970
+				sprintf(
3971
+					__(
3972
+						'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',
3973
+						'event_espresso'
3974
+					),
3975
+					implode('", "', $this->_logic_query_param_keys),
3976
+					$query_param,
3977
+					get_class($this),
3978
+					'<br />',
3979
+					"\t"
3980
+					. ' $passed_in_query_info = <pre>'
3981
+					. print_r($passed_in_query_info, true)
3982
+					. '</pre>'
3983
+					. "\n\t"
3984
+					. ' $query_param_type = '
3985
+					. $query_param_type
3986
+					. "\n\t"
3987
+					. ' $original_query_param = '
3988
+					. $original_query_param
3989
+				)
3990
+			);
3991
+		}
3992
+		// check if it's a custom selection
3993
+		if ($this->_custom_selections instanceof CustomSelects
3994
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3995
+		) {
3996
+			return;
3997
+		}
3998
+		// check if has a model name at the beginning
3999
+		// and
4000
+		// check if it's a field on a related model
4001
+		if ($this->extractJoinModelFromQueryParams(
4002
+			$passed_in_query_info,
4003
+			$query_param,
4004
+			$original_query_param,
4005
+			$query_param_type
4006
+		)) {
4007
+			return;
4008
+		}
4009
+
4010
+		// ok so $query_param didn't start with a model name
4011
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4012
+		// it's wack, that's what it is
4013
+		throw new EE_Error(
4014
+			sprintf(
4015
+				esc_html__(
4016
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4017
+					"event_espresso"
4018
+				),
4019
+				$query_param,
4020
+				get_class($this),
4021
+				$query_param_type,
4022
+				$original_query_param
4023
+			)
4024
+		);
4025
+	}
4026
+
4027
+
4028
+	/**
4029
+	 * Extracts any possible join model information from the provided possible_join_string.
4030
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4031
+	 * parts that should be added to the query.
4032
+	 *
4033
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4034
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4035
+	 * @param null|string                 $original_query_param
4036
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4037
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4038
+	 * @return bool  returns true if a join was added and false if not.
4039
+	 * @throws EE_Error
4040
+	 */
4041
+	private function extractJoinModelFromQueryParams(
4042
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4043
+		$possible_join_string,
4044
+		$original_query_param,
4045
+		$query_parameter_type
4046
+	) {
4047
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4048
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4049
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4050
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4051
+				if ($possible_join_string === '') {
4052
+					// nothing left to $query_param
4053
+					// we should actually end in a field name, not a model like this!
4054
+					throw new EE_Error(
4055
+						sprintf(
4056
+							esc_html__(
4057
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4058
+								"event_espresso"
4059
+							),
4060
+							$possible_join_string,
4061
+							$query_parameter_type,
4062
+							get_class($this),
4063
+							$valid_related_model_name
4064
+						)
4065
+					);
4066
+				}
4067
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4068
+				$related_model_obj->_extract_related_model_info_from_query_param(
4069
+					$possible_join_string,
4070
+					$query_info_carrier,
4071
+					$query_parameter_type,
4072
+					$original_query_param
4073
+				);
4074
+				return true;
4075
+			}
4076
+			if ($possible_join_string === $valid_related_model_name) {
4077
+				$this->_add_join_to_model(
4078
+					$valid_related_model_name,
4079
+					$query_info_carrier,
4080
+					$original_query_param
4081
+				);
4082
+				return true;
4083
+			}
4084
+		}
4085
+		return false;
4086
+	}
4087
+
4088
+
4089
+	/**
4090
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4091
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4092
+	 * @throws EE_Error
4093
+	 */
4094
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4095
+	{
4096
+		if ($this->_custom_selections instanceof CustomSelects
4097
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4098
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4099
+			)
4100
+		) {
4101
+			$original_selects = $this->_custom_selections->originalSelects();
4102
+			foreach ($original_selects as $alias => $select_configuration) {
4103
+				$this->extractJoinModelFromQueryParams(
4104
+					$query_info_carrier,
4105
+					$select_configuration[0],
4106
+					$select_configuration[0],
4107
+					'custom_selects'
4108
+				);
4109
+			}
4110
+		}
4111
+	}
4112
+
4113
+
4114
+
4115
+	/**
4116
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4117
+	 * and store it on $passed_in_query_info
4118
+	 *
4119
+	 * @param string                      $model_name
4120
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4121
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4122
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4123
+	 *                                                          and are adding a join to 'Payment' with the original
4124
+	 *                                                          query param key
4125
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4126
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4127
+	 *                                                          Payment wants to add default query params so that it
4128
+	 *                                                          will know what models to prepend onto its default query
4129
+	 *                                                          params or in case it wants to rename tables (in case
4130
+	 *                                                          there are multiple joins to the same table)
4131
+	 * @return void
4132
+	 * @throws EE_Error
4133
+	 */
4134
+	private function _add_join_to_model(
4135
+		$model_name,
4136
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4137
+		$original_query_param
4138
+	) {
4139
+		$relation_obj = $this->related_settings_for($model_name);
4140
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4141
+		// check if the relation is HABTM, because then we're essentially doing two joins
4142
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4143
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4144
+			$join_model_obj = $relation_obj->get_join_model();
4145
+			// replace the model specified with the join model for this relation chain, whi
4146
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4147
+				$model_name,
4148
+				$join_model_obj->get_this_model_name(),
4149
+				$model_relation_chain
4150
+			);
4151
+			$passed_in_query_info->merge(
4152
+				new EE_Model_Query_Info_Carrier(
4153
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4154
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4155
+				)
4156
+			);
4157
+		}
4158
+		// now just join to the other table pointed to by the relation object, and add its data types
4159
+		$passed_in_query_info->merge(
4160
+			new EE_Model_Query_Info_Carrier(
4161
+				array($model_relation_chain => $model_name),
4162
+				$relation_obj->get_join_statement($model_relation_chain)
4163
+			)
4164
+		);
4165
+	}
4166
+
4167
+
4168
+
4169
+	/**
4170
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4171
+	 *
4172
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4173
+	 * @return string of SQL
4174
+	 * @throws EE_Error
4175
+	 */
4176
+	private function _construct_where_clause($where_params)
4177
+	{
4178
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4179
+		if ($SQL) {
4180
+			return " WHERE " . $SQL;
4181
+		}
4182
+		return '';
4183
+	}
4184
+
4185
+
4186
+
4187
+	/**
4188
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4189
+	 * and should be passed HAVING parameters, not WHERE parameters
4190
+	 *
4191
+	 * @param array $having_params
4192
+	 * @return string
4193
+	 * @throws EE_Error
4194
+	 */
4195
+	private function _construct_having_clause($having_params)
4196
+	{
4197
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4198
+		if ($SQL) {
4199
+			return " HAVING " . $SQL;
4200
+		}
4201
+		return '';
4202
+	}
4203
+
4204
+
4205
+	/**
4206
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4207
+	 * Event_Meta.meta_value = 'foo'))"
4208
+	 *
4209
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4210
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4211
+	 * @throws EE_Error
4212
+	 * @return string of SQL
4213
+	 */
4214
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4215
+	{
4216
+		$where_clauses = array();
4217
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4218
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4219
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4220
+				switch ($query_param) {
4221
+					case 'not':
4222
+					case 'NOT':
4223
+						$where_clauses[] = "! ("
4224
+										   . $this->_construct_condition_clause_recursive(
4225
+											   $op_and_value_or_sub_condition,
4226
+											   $glue
4227
+										   )
4228
+										   . ")";
4229
+						break;
4230
+					case 'and':
4231
+					case 'AND':
4232
+						$where_clauses[] = " ("
4233
+										   . $this->_construct_condition_clause_recursive(
4234
+											   $op_and_value_or_sub_condition,
4235
+											   ' AND '
4236
+										   )
4237
+										   . ")";
4238
+						break;
4239
+					case 'or':
4240
+					case 'OR':
4241
+						$where_clauses[] = " ("
4242
+										   . $this->_construct_condition_clause_recursive(
4243
+											   $op_and_value_or_sub_condition,
4244
+											   ' OR '
4245
+										   )
4246
+										   . ")";
4247
+						break;
4248
+				}
4249
+			} else {
4250
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4251
+				// if it's not a normal field, maybe it's a custom selection?
4252
+				if (! $field_obj) {
4253
+					if ($this->_custom_selections instanceof CustomSelects) {
4254
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4255
+					} else {
4256
+						throw new EE_Error(sprintf(__(
4257
+							"%s is neither a valid model field name, nor a custom selection",
4258
+							"event_espresso"
4259
+						), $query_param));
4260
+					}
4261
+				}
4262
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4263
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4264
+			}
4265
+		}
4266
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4267
+	}
4268
+
4269
+
4270
+
4271
+	/**
4272
+	 * Takes the input parameter and extract the table name (alias) and column name
4273
+	 *
4274
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4275
+	 * @throws EE_Error
4276
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4277
+	 */
4278
+	private function _deduce_column_name_from_query_param($query_param)
4279
+	{
4280
+		$field = $this->_deduce_field_from_query_param($query_param);
4281
+		if ($field) {
4282
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4283
+				$field->get_model_name(),
4284
+				$query_param
4285
+			);
4286
+			return $table_alias_prefix . $field->get_qualified_column();
4287
+		}
4288
+		if ($this->_custom_selections instanceof CustomSelects
4289
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4290
+		) {
4291
+			// maybe it's custom selection item?
4292
+			// if so, just use it as the "column name"
4293
+			return $query_param;
4294
+		}
4295
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4296
+			? implode(',', $this->_custom_selections->columnAliases())
4297
+			: '';
4298
+		throw new EE_Error(
4299
+			sprintf(
4300
+				__(
4301
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4302
+					"event_espresso"
4303
+				),
4304
+				$query_param,
4305
+				$custom_select_aliases
4306
+			)
4307
+		);
4308
+	}
4309
+
4310
+
4311
+
4312
+	/**
4313
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4314
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4315
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4316
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4317
+	 *
4318
+	 * @param string $condition_query_param_key
4319
+	 * @return string
4320
+	 */
4321
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4322
+	{
4323
+		$pos_of_star = strpos($condition_query_param_key, '*');
4324
+		if ($pos_of_star === false) {
4325
+			return $condition_query_param_key;
4326
+		}
4327
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4328
+		return $condition_query_param_sans_star;
4329
+	}
4330
+
4331
+
4332
+
4333
+	/**
4334
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4335
+	 *
4336
+	 * @param                            mixed      array | string    $op_and_value
4337
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4338
+	 * @throws EE_Error
4339
+	 * @return string
4340
+	 */
4341
+	private function _construct_op_and_value($op_and_value, $field_obj)
4342
+	{
4343
+		if (is_array($op_and_value)) {
4344
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4345
+			if (! $operator) {
4346
+				$php_array_like_string = array();
4347
+				foreach ($op_and_value as $key => $value) {
4348
+					$php_array_like_string[] = "$key=>$value";
4349
+				}
4350
+				throw new EE_Error(
4351
+					sprintf(
4352
+						__(
4353
+							"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))",
4354
+							"event_espresso"
4355
+						),
4356
+						implode(",", $php_array_like_string)
4357
+					)
4358
+				);
4359
+			}
4360
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4361
+		} else {
4362
+			$operator = '=';
4363
+			$value = $op_and_value;
4364
+		}
4365
+		// check to see if the value is actually another field
4366
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4367
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4368
+		}
4369
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4370
+			// in this case, the value should be an array, or at least a comma-separated list
4371
+			// it will need to handle a little differently
4372
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4373
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4374
+			return $operator . SP . $cleaned_value;
4375
+		}
4376
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4377
+			// the value should be an array with count of two.
4378
+			if (count($value) !== 2) {
4379
+				throw new EE_Error(
4380
+					sprintf(
4381
+						__(
4382
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4383
+							'event_espresso'
4384
+						),
4385
+						"BETWEEN"
4386
+					)
4387
+				);
4388
+			}
4389
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4390
+			return $operator . SP . $cleaned_value;
4391
+		}
4392
+		if (in_array($operator, $this->valid_null_style_operators())) {
4393
+			if ($value !== null) {
4394
+				throw new EE_Error(
4395
+					sprintf(
4396
+						__(
4397
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4398
+							"event_espresso"
4399
+						),
4400
+						$value,
4401
+						$operator
4402
+					)
4403
+				);
4404
+			}
4405
+			return $operator;
4406
+		}
4407
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4408
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4409
+			// remove other junk. So just treat it as a string.
4410
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4411
+		}
4412
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4413
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4414
+		}
4415
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4416
+			throw new EE_Error(
4417
+				sprintf(
4418
+					__(
4419
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4420
+						'event_espresso'
4421
+					),
4422
+					$operator,
4423
+					$operator
4424
+				)
4425
+			);
4426
+		}
4427
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4428
+			throw new EE_Error(
4429
+				sprintf(
4430
+					__(
4431
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4432
+						'event_espresso'
4433
+					),
4434
+					$operator,
4435
+					$operator
4436
+				)
4437
+			);
4438
+		}
4439
+		throw new EE_Error(
4440
+			sprintf(
4441
+				__(
4442
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4443
+					"event_espresso"
4444
+				),
4445
+				http_build_query($op_and_value)
4446
+			)
4447
+		);
4448
+	}
4449
+
4450
+
4451
+
4452
+	/**
4453
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4454
+	 *
4455
+	 * @param array                      $values
4456
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4457
+	 *                                              '%s'
4458
+	 * @return string
4459
+	 * @throws EE_Error
4460
+	 */
4461
+	public function _construct_between_value($values, $field_obj)
4462
+	{
4463
+		$cleaned_values = array();
4464
+		foreach ($values as $value) {
4465
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4466
+		}
4467
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4468
+	}
4469
+
4470
+
4471
+
4472
+	/**
4473
+	 * Takes an array or a comma-separated list of $values and cleans them
4474
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4475
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4476
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4477
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4478
+	 *
4479
+	 * @param mixed                      $values    array or comma-separated string
4480
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4481
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4482
+	 * @throws EE_Error
4483
+	 */
4484
+	public function _construct_in_value($values, $field_obj)
4485
+	{
4486
+		// check if the value is a CSV list
4487
+		if (is_string($values)) {
4488
+			// in which case, turn it into an array
4489
+			$values = explode(",", $values);
4490
+		}
4491
+		$cleaned_values = array();
4492
+		foreach ($values as $value) {
4493
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4494
+		}
4495
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4496
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4497
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4498
+		if (empty($cleaned_values)) {
4499
+			$all_fields = $this->field_settings();
4500
+			$a_field = array_shift($all_fields);
4501
+			$main_table = $this->_get_main_table();
4502
+			$cleaned_values[] = "SELECT "
4503
+								. $a_field->get_table_column()
4504
+								. " FROM "
4505
+								. $main_table->get_table_name()
4506
+								. " WHERE FALSE";
4507
+		}
4508
+		return "(" . implode(",", $cleaned_values) . ")";
4509
+	}
4510
+
4511
+
4512
+
4513
+	/**
4514
+	 * @param mixed                      $value
4515
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4516
+	 * @throws EE_Error
4517
+	 * @return false|null|string
4518
+	 */
4519
+	private function _wpdb_prepare_using_field($value, $field_obj)
4520
+	{
4521
+		/** @type WPDB $wpdb */
4522
+		global $wpdb;
4523
+		if ($field_obj instanceof EE_Model_Field_Base) {
4524
+			return $wpdb->prepare(
4525
+				$field_obj->get_wpdb_data_type(),
4526
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4527
+			);
4528
+		} //$field_obj should really just be a data type
4529
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4530
+			throw new EE_Error(
4531
+				sprintf(
4532
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4533
+					$field_obj,
4534
+					implode(",", $this->_valid_wpdb_data_types)
4535
+				)
4536
+			);
4537
+		}
4538
+		return $wpdb->prepare($field_obj, $value);
4539
+	}
4540
+
4541
+
4542
+
4543
+	/**
4544
+	 * Takes the input parameter and finds the model field that it indicates.
4545
+	 *
4546
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4547
+	 * @throws EE_Error
4548
+	 * @return EE_Model_Field_Base
4549
+	 */
4550
+	protected function _deduce_field_from_query_param($query_param_name)
4551
+	{
4552
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4553
+		// which will help us find the database table and column
4554
+		$query_param_parts = explode(".", $query_param_name);
4555
+		if (empty($query_param_parts)) {
4556
+			throw new EE_Error(sprintf(__(
4557
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4558
+				'event_espresso'
4559
+			), $query_param_name));
4560
+		}
4561
+		$number_of_parts = count($query_param_parts);
4562
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4563
+		if ($number_of_parts === 1) {
4564
+			$field_name = $last_query_param_part;
4565
+			$model_obj = $this;
4566
+		} else {// $number_of_parts >= 2
4567
+			// the last part is the column name, and there are only 2parts. therefore...
4568
+			$field_name = $last_query_param_part;
4569
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4570
+		}
4571
+		try {
4572
+			return $model_obj->field_settings_for($field_name);
4573
+		} catch (EE_Error $e) {
4574
+			return null;
4575
+		}
4576
+	}
4577
+
4578
+
4579
+
4580
+	/**
4581
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4582
+	 * alias and column which corresponds to it
4583
+	 *
4584
+	 * @param string $field_name
4585
+	 * @throws EE_Error
4586
+	 * @return string
4587
+	 */
4588
+	public function _get_qualified_column_for_field($field_name)
4589
+	{
4590
+		$all_fields = $this->field_settings();
4591
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4592
+		if ($field) {
4593
+			return $field->get_qualified_column();
4594
+		}
4595
+		throw new EE_Error(
4596
+			sprintf(
4597
+				__(
4598
+					"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.",
4599
+					'event_espresso'
4600
+				),
4601
+				$field_name,
4602
+				get_class($this)
4603
+			)
4604
+		);
4605
+	}
4606
+
4607
+
4608
+
4609
+	/**
4610
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4611
+	 * Example usage:
4612
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4613
+	 *      array(),
4614
+	 *      ARRAY_A,
4615
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4616
+	 *  );
4617
+	 * is equivalent to
4618
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4619
+	 * and
4620
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4621
+	 *      array(
4622
+	 *          array(
4623
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4624
+	 *          ),
4625
+	 *          ARRAY_A,
4626
+	 *          implode(
4627
+	 *              ', ',
4628
+	 *              array_merge(
4629
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4630
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4631
+	 *              )
4632
+	 *          )
4633
+	 *      )
4634
+	 *  );
4635
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4636
+	 *
4637
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4638
+	 *                                            and the one whose fields you are selecting for example: when querying
4639
+	 *                                            tickets model and selecting fields from the tickets model you would
4640
+	 *                                            leave this parameter empty, because no models are needed to join
4641
+	 *                                            between the queried model and the selected one. Likewise when
4642
+	 *                                            querying the datetime model and selecting fields from the tickets
4643
+	 *                                            model, it would also be left empty, because there is a direct
4644
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4645
+	 *                                            them together. However, when querying from the event model and
4646
+	 *                                            selecting fields from the ticket model, you should provide the string
4647
+	 *                                            'Datetime', indicating that the event model must first join to the
4648
+	 *                                            datetime model in order to find its relation to ticket model.
4649
+	 *                                            Also, when querying from the venue model and selecting fields from
4650
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4651
+	 *                                            indicating you need to join the venue model to the event model,
4652
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4653
+	 *                                            This string is used to deduce the prefix that gets added onto the
4654
+	 *                                            models' tables qualified columns
4655
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4656
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4657
+	 *                                            qualified column names
4658
+	 * @return array|string
4659
+	 */
4660
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4661
+	{
4662
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4663
+		$qualified_columns = array();
4664
+		foreach ($this->field_settings() as $field_name => $field) {
4665
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4666
+		}
4667
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4668
+	}
4669
+
4670
+
4671
+
4672
+	/**
4673
+	 * constructs the select use on special limit joins
4674
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4675
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4676
+	 * (as that is typically where the limits would be set).
4677
+	 *
4678
+	 * @param  string       $table_alias The table the select is being built for
4679
+	 * @param  mixed|string $limit       The limit for this select
4680
+	 * @return string                The final select join element for the query.
4681
+	 */
4682
+	public function _construct_limit_join_select($table_alias, $limit)
4683
+	{
4684
+		$SQL = '';
4685
+		foreach ($this->_tables as $table_obj) {
4686
+			if ($table_obj instanceof EE_Primary_Table) {
4687
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4688
+					? $table_obj->get_select_join_limit($limit)
4689
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4690
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4691
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4692
+					? $table_obj->get_select_join_limit_join($limit)
4693
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4694
+			}
4695
+		}
4696
+		return $SQL;
4697
+	}
4698
+
4699
+
4700
+
4701
+	/**
4702
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4703
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4704
+	 *
4705
+	 * @return string SQL
4706
+	 * @throws EE_Error
4707
+	 */
4708
+	public function _construct_internal_join()
4709
+	{
4710
+		$SQL = $this->_get_main_table()->get_table_sql();
4711
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4712
+		return $SQL;
4713
+	}
4714
+
4715
+
4716
+
4717
+	/**
4718
+	 * Constructs the SQL for joining all the tables on this model.
4719
+	 * Normally $alias should be the primary table's alias, but in cases where
4720
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4721
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4722
+	 * alias, this will construct SQL like:
4723
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4724
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4725
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4726
+	 *
4727
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4728
+	 * @return string
4729
+	 */
4730
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4731
+	{
4732
+		$SQL = '';
4733
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4734
+		foreach ($this->_tables as $table_obj) {
4735
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4736
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4737
+					// so we're joining to this table, meaning the table is already in
4738
+					// the FROM statement, BUT the primary table isn't. So we want
4739
+					// to add the inverse join sql
4740
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4741
+				} else {
4742
+					// just add a regular JOIN to this table from the primary table
4743
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4744
+				}
4745
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4746
+		}
4747
+		return $SQL;
4748
+	}
4749
+
4750
+
4751
+
4752
+	/**
4753
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4754
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4755
+	 * their data type (eg, '%s', '%d', etc)
4756
+	 *
4757
+	 * @return array
4758
+	 */
4759
+	public function _get_data_types()
4760
+	{
4761
+		$data_types = array();
4762
+		foreach ($this->field_settings() as $field_obj) {
4763
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4764
+			/** @var $field_obj EE_Model_Field_Base */
4765
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4766
+		}
4767
+		return $data_types;
4768
+	}
4769
+
4770
+
4771
+
4772
+	/**
4773
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4774
+	 *
4775
+	 * @param string $model_name
4776
+	 * @throws EE_Error
4777
+	 * @return EEM_Base
4778
+	 */
4779
+	public function get_related_model_obj($model_name)
4780
+	{
4781
+		$model_classname = "EEM_" . $model_name;
4782
+		if (! class_exists($model_classname)) {
4783
+			throw new EE_Error(sprintf(__(
4784
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4785
+				'event_espresso'
4786
+			), $model_name, $model_classname));
4787
+		}
4788
+		return call_user_func($model_classname . "::instance");
4789
+	}
4790
+
4791
+
4792
+
4793
+	/**
4794
+	 * Returns the array of EE_ModelRelations for this model.
4795
+	 *
4796
+	 * @return EE_Model_Relation_Base[]
4797
+	 */
4798
+	public function relation_settings()
4799
+	{
4800
+		return $this->_model_relations;
4801
+	}
4802
+
4803
+
4804
+
4805
+	/**
4806
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4807
+	 * because without THOSE models, this model probably doesn't have much purpose.
4808
+	 * (Eg, without an event, datetimes have little purpose.)
4809
+	 *
4810
+	 * @return EE_Belongs_To_Relation[]
4811
+	 */
4812
+	public function belongs_to_relations()
4813
+	{
4814
+		$belongs_to_relations = array();
4815
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4816
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4817
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4818
+			}
4819
+		}
4820
+		return $belongs_to_relations;
4821
+	}
4822
+
4823
+
4824
+
4825
+	/**
4826
+	 * Returns the specified EE_Model_Relation, or throws an exception
4827
+	 *
4828
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4829
+	 * @throws EE_Error
4830
+	 * @return EE_Model_Relation_Base
4831
+	 */
4832
+	public function related_settings_for($relation_name)
4833
+	{
4834
+		$relatedModels = $this->relation_settings();
4835
+		if (! array_key_exists($relation_name, $relatedModels)) {
4836
+			throw new EE_Error(
4837
+				sprintf(
4838
+					__(
4839
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4840
+						'event_espresso'
4841
+					),
4842
+					$relation_name,
4843
+					$this->_get_class_name(),
4844
+					implode(', ', array_keys($relatedModels))
4845
+				)
4846
+			);
4847
+		}
4848
+		return $relatedModels[ $relation_name ];
4849
+	}
4850
+
4851
+
4852
+
4853
+	/**
4854
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4855
+	 * fields
4856
+	 *
4857
+	 * @param string $fieldName
4858
+	 * @param boolean $include_db_only_fields
4859
+	 * @throws EE_Error
4860
+	 * @return EE_Model_Field_Base
4861
+	 */
4862
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4863
+	{
4864
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4865
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4866
+			throw new EE_Error(sprintf(
4867
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4868
+				$fieldName,
4869
+				get_class($this)
4870
+			));
4871
+		}
4872
+		return $fieldSettings[ $fieldName ];
4873
+	}
4874
+
4875
+
4876
+
4877
+	/**
4878
+	 * Checks if this field exists on this model
4879
+	 *
4880
+	 * @param string $fieldName a key in the model's _field_settings array
4881
+	 * @return boolean
4882
+	 */
4883
+	public function has_field($fieldName)
4884
+	{
4885
+		$fieldSettings = $this->field_settings(true);
4886
+		if (isset($fieldSettings[ $fieldName ])) {
4887
+			return true;
4888
+		}
4889
+		return false;
4890
+	}
4891
+
4892
+
4893
+
4894
+	/**
4895
+	 * Returns whether or not this model has a relation to the specified model
4896
+	 *
4897
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4898
+	 * @return boolean
4899
+	 */
4900
+	public function has_relation($relation_name)
4901
+	{
4902
+		$relations = $this->relation_settings();
4903
+		if (isset($relations[ $relation_name ])) {
4904
+			return true;
4905
+		}
4906
+		return false;
4907
+	}
4908
+
4909
+
4910
+
4911
+	/**
4912
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4913
+	 * Eg, on EE_Answer that would be ANS_ID field object
4914
+	 *
4915
+	 * @param $field_obj
4916
+	 * @return boolean
4917
+	 */
4918
+	public function is_primary_key_field($field_obj)
4919
+	{
4920
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4921
+	}
4922
+
4923
+
4924
+
4925
+	/**
4926
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4927
+	 * Eg, on EE_Answer that would be ANS_ID field object
4928
+	 *
4929
+	 * @return EE_Model_Field_Base
4930
+	 * @throws EE_Error
4931
+	 */
4932
+	public function get_primary_key_field()
4933
+	{
4934
+		if ($this->_primary_key_field === null) {
4935
+			foreach ($this->field_settings(true) as $field_obj) {
4936
+				if ($this->is_primary_key_field($field_obj)) {
4937
+					$this->_primary_key_field = $field_obj;
4938
+					break;
4939
+				}
4940
+			}
4941
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4942
+				throw new EE_Error(sprintf(
4943
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4944
+					get_class($this)
4945
+				));
4946
+			}
4947
+		}
4948
+		return $this->_primary_key_field;
4949
+	}
4950
+
4951
+
4952
+
4953
+	/**
4954
+	 * Returns whether or not not there is a primary key on this model.
4955
+	 * Internally does some caching.
4956
+	 *
4957
+	 * @return boolean
4958
+	 */
4959
+	public function has_primary_key_field()
4960
+	{
4961
+		if ($this->_has_primary_key_field === null) {
4962
+			try {
4963
+				$this->get_primary_key_field();
4964
+				$this->_has_primary_key_field = true;
4965
+			} catch (EE_Error $e) {
4966
+				$this->_has_primary_key_field = false;
4967
+			}
4968
+		}
4969
+		return $this->_has_primary_key_field;
4970
+	}
4971
+
4972
+
4973
+
4974
+	/**
4975
+	 * Finds the first field of type $field_class_name.
4976
+	 *
4977
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4978
+	 *                                 EE_Foreign_Key_Field, etc
4979
+	 * @return EE_Model_Field_Base or null if none is found
4980
+	 */
4981
+	public function get_a_field_of_type($field_class_name)
4982
+	{
4983
+		foreach ($this->field_settings() as $field) {
4984
+			if ($field instanceof $field_class_name) {
4985
+				return $field;
4986
+			}
4987
+		}
4988
+		return null;
4989
+	}
4990
+
4991
+
4992
+
4993
+	/**
4994
+	 * Gets a foreign key field pointing to model.
4995
+	 *
4996
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4997
+	 * @return EE_Foreign_Key_Field_Base
4998
+	 * @throws EE_Error
4999
+	 */
5000
+	public function get_foreign_key_to($model_name)
5001
+	{
5002
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5003
+			foreach ($this->field_settings() as $field) {
5004
+				if ($field instanceof EE_Foreign_Key_Field_Base
5005
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5006
+				) {
5007
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5008
+					break;
5009
+				}
5010
+			}
5011
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5012
+				throw new EE_Error(sprintf(__(
5013
+					"There is no foreign key field pointing to model %s on model %s",
5014
+					'event_espresso'
5015
+				), $model_name, get_class($this)));
5016
+			}
5017
+		}
5018
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5019
+	}
5020
+
5021
+
5022
+
5023
+	/**
5024
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5025
+	 *
5026
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5027
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5028
+	 *                            Either one works
5029
+	 * @return string
5030
+	 */
5031
+	public function get_table_for_alias($table_alias)
5032
+	{
5033
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5034
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5035
+	}
5036
+
5037
+
5038
+
5039
+	/**
5040
+	 * Returns a flat array of all field son this model, instead of organizing them
5041
+	 * by table_alias as they are in the constructor.
5042
+	 *
5043
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5044
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5045
+	 */
5046
+	public function field_settings($include_db_only_fields = false)
5047
+	{
5048
+		if ($include_db_only_fields) {
5049
+			if ($this->_cached_fields === null) {
5050
+				$this->_cached_fields = array();
5051
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5052
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5053
+						$this->_cached_fields[ $field_name ] = $field_obj;
5054
+					}
5055
+				}
5056
+			}
5057
+			return $this->_cached_fields;
5058
+		}
5059
+		if ($this->_cached_fields_non_db_only === null) {
5060
+			$this->_cached_fields_non_db_only = array();
5061
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5062
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5063
+					/** @var $field_obj EE_Model_Field_Base */
5064
+					if (! $field_obj->is_db_only_field()) {
5065
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5066
+					}
5067
+				}
5068
+			}
5069
+		}
5070
+		return $this->_cached_fields_non_db_only;
5071
+	}
5072
+
5073
+
5074
+
5075
+	/**
5076
+	 *        cycle though array of attendees and create objects out of each item
5077
+	 *
5078
+	 * @access        private
5079
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5080
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5081
+	 *                           numerically indexed)
5082
+	 * @throws EE_Error
5083
+	 */
5084
+	protected function _create_objects($rows = array())
5085
+	{
5086
+		$array_of_objects = array();
5087
+		if (empty($rows)) {
5088
+			return array();
5089
+		}
5090
+		$count_if_model_has_no_primary_key = 0;
5091
+		$has_primary_key = $this->has_primary_key_field();
5092
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5093
+		foreach ((array) $rows as $row) {
5094
+			if (empty($row)) {
5095
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5096
+				return array();
5097
+			}
5098
+			// check if we've already set this object in the results array,
5099
+			// in which case there's no need to process it further (again)
5100
+			if ($has_primary_key) {
5101
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5102
+					$row,
5103
+					$primary_key_field->get_qualified_column(),
5104
+					$primary_key_field->get_table_column()
5105
+				);
5106
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5107
+					continue;
5108
+				}
5109
+			}
5110
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5111
+			if (! $classInstance) {
5112
+				throw new EE_Error(
5113
+					sprintf(
5114
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5115
+						$this->get_this_model_name(),
5116
+						http_build_query($row)
5117
+					)
5118
+				);
5119
+			}
5120
+			// set the timezone on the instantiated objects
5121
+			$classInstance->set_timezone($this->_timezone);
5122
+			// make sure if there is any timezone setting present that we set the timezone for the object
5123
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5124
+			$array_of_objects[ $key ] = $classInstance;
5125
+			// also, for all the relations of type BelongsTo, see if we can cache
5126
+			// those related models
5127
+			// (we could do this for other relations too, but if there are conditions
5128
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5129
+			// so it requires a little more thought than just caching them immediately...)
5130
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5131
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5132
+					// check if this model's INFO is present. If so, cache it on the model
5133
+					$other_model = $relation_obj->get_other_model();
5134
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5135
+					// if we managed to make a model object from the results, cache it on the main model object
5136
+					if ($other_model_obj_maybe) {
5137
+						// set timezone on these other model objects if they are present
5138
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5139
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5140
+					}
5141
+				}
5142
+			}
5143
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5144
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5145
+			// the field in the CustomSelects object
5146
+			if ($this->_custom_selections instanceof CustomSelects) {
5147
+				$classInstance->setCustomSelectsValues(
5148
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5149
+				);
5150
+			}
5151
+		}
5152
+		return $array_of_objects;
5153
+	}
5154
+
5155
+
5156
+	/**
5157
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5158
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5159
+	 *
5160
+	 * @param array $db_results_row
5161
+	 * @return array
5162
+	 */
5163
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5164
+	{
5165
+		$results = array();
5166
+		if ($this->_custom_selections instanceof CustomSelects) {
5167
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5168
+				if (isset($db_results_row[ $alias ])) {
5169
+					$results[ $alias ] = $this->convertValueToDataType(
5170
+						$db_results_row[ $alias ],
5171
+						$this->_custom_selections->getDataTypeForAlias($alias)
5172
+					);
5173
+				}
5174
+			}
5175
+		}
5176
+		return $results;
5177
+	}
5178
+
5179
+
5180
+	/**
5181
+	 * This will set the value for the given alias
5182
+	 * @param string $value
5183
+	 * @param string $datatype (one of %d, %s, %f)
5184
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5185
+	 */
5186
+	protected function convertValueToDataType($value, $datatype)
5187
+	{
5188
+		switch ($datatype) {
5189
+			case '%f':
5190
+				return (float) $value;
5191
+			case '%d':
5192
+				return (int) $value;
5193
+			default:
5194
+				return (string) $value;
5195
+		}
5196
+	}
5197
+
5198
+
5199
+	/**
5200
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5201
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5202
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5203
+	 * object (as set in the model_field!).
5204
+	 *
5205
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5206
+	 */
5207
+	public function create_default_object()
5208
+	{
5209
+		$this_model_fields_and_values = array();
5210
+		// setup the row using default values;
5211
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5212
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5213
+		}
5214
+		$className = $this->_get_class_name();
5215
+		$classInstance = EE_Registry::instance()
5216
+									->load_class($className, array($this_model_fields_and_values), false, false);
5217
+		return $classInstance;
5218
+	}
5219
+
5220
+
5221
+
5222
+	/**
5223
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5224
+	 *                             or an stdClass where each property is the name of a column,
5225
+	 * @return EE_Base_Class
5226
+	 * @throws EE_Error
5227
+	 */
5228
+	public function instantiate_class_from_array_or_object($cols_n_values)
5229
+	{
5230
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5231
+			$cols_n_values = get_object_vars($cols_n_values);
5232
+		}
5233
+		$primary_key = null;
5234
+		// make sure the array only has keys that are fields/columns on this model
5235
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5236
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5237
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5238
+		}
5239
+		$className = $this->_get_class_name();
5240
+		// check we actually found results that we can use to build our model object
5241
+		// if not, return null
5242
+		if ($this->has_primary_key_field()) {
5243
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
+				return null;
5245
+			}
5246
+		} elseif ($this->unique_indexes()) {
5247
+			$first_column = reset($this_model_fields_n_values);
5248
+			if (empty($first_column)) {
5249
+				return null;
5250
+			}
5251
+		}
5252
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5253
+		if ($primary_key) {
5254
+			$classInstance = $this->get_from_entity_map($primary_key);
5255
+			if (! $classInstance) {
5256
+				$classInstance = EE_Registry::instance()
5257
+											->load_class(
5258
+												$className,
5259
+												array($this_model_fields_n_values, $this->_timezone),
5260
+												true,
5261
+												false
5262
+											);
5263
+				// add this new object to the entity map
5264
+				$classInstance = $this->add_to_entity_map($classInstance);
5265
+			}
5266
+		} else {
5267
+			$classInstance = EE_Registry::instance()
5268
+										->load_class(
5269
+											$className,
5270
+											array($this_model_fields_n_values, $this->_timezone),
5271
+											true,
5272
+											false
5273
+										);
5274
+		}
5275
+		return $classInstance;
5276
+	}
5277
+
5278
+
5279
+
5280
+	/**
5281
+	 * Gets the model object from the  entity map if it exists
5282
+	 *
5283
+	 * @param int|string $id the ID of the model object
5284
+	 * @return EE_Base_Class
5285
+	 */
5286
+	public function get_from_entity_map($id)
5287
+	{
5288
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5289
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5290
+	}
5291
+
5292
+
5293
+
5294
+	/**
5295
+	 * add_to_entity_map
5296
+	 * Adds the object to the model's entity mappings
5297
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5298
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5299
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5300
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5301
+	 *        then this method should be called immediately after the update query
5302
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5303
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5304
+	 *
5305
+	 * @param    EE_Base_Class $object
5306
+	 * @throws EE_Error
5307
+	 * @return \EE_Base_Class
5308
+	 */
5309
+	public function add_to_entity_map(EE_Base_Class $object)
5310
+	{
5311
+		$className = $this->_get_class_name();
5312
+		if (! $object instanceof $className) {
5313
+			throw new EE_Error(sprintf(
5314
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5315
+				is_object($object) ? get_class($object) : $object,
5316
+				$className
5317
+			));
5318
+		}
5319
+		/** @var $object EE_Base_Class */
5320
+		if (! $object->ID()) {
5321
+			throw new EE_Error(sprintf(__(
5322
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5323
+				"event_espresso"
5324
+			), get_class($this)));
5325
+		}
5326
+		// double check it's not already there
5327
+		$classInstance = $this->get_from_entity_map($object->ID());
5328
+		if ($classInstance) {
5329
+			return $classInstance;
5330
+		}
5331
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5332
+		return $object;
5333
+	}
5334
+
5335
+
5336
+
5337
+	/**
5338
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5339
+	 * if no identifier is provided, then the entire entity map is emptied
5340
+	 *
5341
+	 * @param int|string $id the ID of the model object
5342
+	 * @return boolean
5343
+	 */
5344
+	public function clear_entity_map($id = null)
5345
+	{
5346
+		if (empty($id)) {
5347
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5348
+			return true;
5349
+		}
5350
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5351
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5352
+			return true;
5353
+		}
5354
+		return false;
5355
+	}
5356
+
5357
+
5358
+
5359
+	/**
5360
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5361
+	 * Given an array where keys are column (or column alias) names and values,
5362
+	 * returns an array of their corresponding field names and database values
5363
+	 *
5364
+	 * @param array $cols_n_values
5365
+	 * @return array
5366
+	 */
5367
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5368
+	{
5369
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5370
+	}
5371
+
5372
+
5373
+
5374
+	/**
5375
+	 * _deduce_fields_n_values_from_cols_n_values
5376
+	 * Given an array where keys are column (or column alias) names and values,
5377
+	 * returns an array of their corresponding field names and database values
5378
+	 *
5379
+	 * @param string $cols_n_values
5380
+	 * @return array
5381
+	 */
5382
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5383
+	{
5384
+		$this_model_fields_n_values = array();
5385
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5386
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5387
+				$cols_n_values,
5388
+				$table_obj->get_fully_qualified_pk_column(),
5389
+				$table_obj->get_pk_column()
5390
+			);
5391
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5392
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5393
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5394
+					if (! $field_obj->is_db_only_field()) {
5395
+						// prepare field as if its coming from db
5396
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5397
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5398
+					}
5399
+				}
5400
+			} else {
5401
+				// the table's rows existed. Use their values
5402
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5403
+					if (! $field_obj->is_db_only_field()) {
5404
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5405
+							$cols_n_values,
5406
+							$field_obj->get_qualified_column(),
5407
+							$field_obj->get_table_column()
5408
+						);
5409
+					}
5410
+				}
5411
+			}
5412
+		}
5413
+		return $this_model_fields_n_values;
5414
+	}
5415
+
5416
+
5417
+
5418
+	/**
5419
+	 * @param $cols_n_values
5420
+	 * @param $qualified_column
5421
+	 * @param $regular_column
5422
+	 * @return null
5423
+	 */
5424
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5425
+	{
5426
+		$value = null;
5427
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5428
+		// does the field on the model relate to this column retrieved from the db?
5429
+		// or is it a db-only field? (not relating to the model)
5430
+		if (isset($cols_n_values[ $qualified_column ])) {
5431
+			$value = $cols_n_values[ $qualified_column ];
5432
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5433
+			$value = $cols_n_values[ $regular_column ];
5434
+		} elseif (! empty($this->foreign_key_aliases)) {
5435
+			// no PK?  ok check if there is a foreign key alias set for this table
5436
+			// then check if that alias exists in the incoming data
5437
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5438
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5439
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5440
+					$value = $cols_n_values[ $FK_alias ];
5441
+					break;
5442
+				}
5443
+			}
5444
+		}
5445
+		return $value;
5446
+	}
5447
+
5448
+
5449
+
5450
+	/**
5451
+	 * refresh_entity_map_from_db
5452
+	 * Makes sure the model object in the entity map at $id assumes the values
5453
+	 * of the database (opposite of EE_base_Class::save())
5454
+	 *
5455
+	 * @param int|string $id
5456
+	 * @return EE_Base_Class
5457
+	 * @throws EE_Error
5458
+	 */
5459
+	public function refresh_entity_map_from_db($id)
5460
+	{
5461
+		$obj_in_map = $this->get_from_entity_map($id);
5462
+		if ($obj_in_map) {
5463
+			$wpdb_results = $this->_get_all_wpdb_results(
5464
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5465
+			);
5466
+			if ($wpdb_results && is_array($wpdb_results)) {
5467
+				$one_row = reset($wpdb_results);
5468
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5469
+					$obj_in_map->set_from_db($field_name, $db_value);
5470
+				}
5471
+				// clear the cache of related model objects
5472
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5473
+					$obj_in_map->clear_cache($relation_name, null, true);
5474
+				}
5475
+			}
5476
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5477
+			return $obj_in_map;
5478
+		}
5479
+		return $this->get_one_by_ID($id);
5480
+	}
5481
+
5482
+
5483
+
5484
+	/**
5485
+	 * refresh_entity_map_with
5486
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5487
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5488
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5489
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5490
+	 *
5491
+	 * @param int|string    $id
5492
+	 * @param EE_Base_Class $replacing_model_obj
5493
+	 * @return \EE_Base_Class
5494
+	 * @throws EE_Error
5495
+	 */
5496
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5497
+	{
5498
+		$obj_in_map = $this->get_from_entity_map($id);
5499
+		if ($obj_in_map) {
5500
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5501
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5502
+					$obj_in_map->set($field_name, $value);
5503
+				}
5504
+				// make the model object in the entity map's cache match the $replacing_model_obj
5505
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
+					$obj_in_map->clear_cache($relation_name, null, true);
5507
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5508
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5509
+					}
5510
+				}
5511
+			}
5512
+			return $obj_in_map;
5513
+		}
5514
+		$this->add_to_entity_map($replacing_model_obj);
5515
+		return $replacing_model_obj;
5516
+	}
5517
+
5518
+
5519
+
5520
+	/**
5521
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5522
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5523
+	 * require_once($this->_getClassName().".class.php");
5524
+	 *
5525
+	 * @return string
5526
+	 */
5527
+	private function _get_class_name()
5528
+	{
5529
+		return "EE_" . $this->get_this_model_name();
5530
+	}
5531
+
5532
+
5533
+
5534
+	/**
5535
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5536
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5537
+	 * it would be 'Events'.
5538
+	 *
5539
+	 * @param int $quantity
5540
+	 * @return string
5541
+	 */
5542
+	public function item_name($quantity = 1)
5543
+	{
5544
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5545
+	}
5546
+
5547
+
5548
+
5549
+	/**
5550
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5551
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5552
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5553
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5554
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5555
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5556
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5557
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5558
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5559
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5560
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5561
+	 *        return $previousReturnValue.$returnString;
5562
+	 * }
5563
+	 * require('EEM_Answer.model.php');
5564
+	 * $answer=EEM_Answer::instance();
5565
+	 * echo $answer->my_callback('monkeys',100);
5566
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5567
+	 *
5568
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5569
+	 * @param array  $args       array of original arguments passed to the function
5570
+	 * @throws EE_Error
5571
+	 * @return mixed whatever the plugin which calls add_filter decides
5572
+	 */
5573
+	public function __call($methodName, $args)
5574
+	{
5575
+		$className = get_class($this);
5576
+		$tagName = "FHEE__{$className}__{$methodName}";
5577
+		if (! has_filter($tagName)) {
5578
+			throw new EE_Error(
5579
+				sprintf(
5580
+					__(
5581
+						'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 );',
5582
+						'event_espresso'
5583
+					),
5584
+					$methodName,
5585
+					$className,
5586
+					$tagName,
5587
+					'<br />'
5588
+				)
5589
+			);
5590
+		}
5591
+		return apply_filters($tagName, null, $this, $args);
5592
+	}
5593
+
5594
+
5595
+
5596
+	/**
5597
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5598
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5599
+	 *
5600
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5601
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5602
+	 *                                                       the object's class name
5603
+	 *                                                       or object's ID
5604
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5605
+	 *                                                       exists in the database. If it does not, we add it
5606
+	 * @throws EE_Error
5607
+	 * @return EE_Base_Class
5608
+	 */
5609
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5610
+	{
5611
+		$className = $this->_get_class_name();
5612
+		if ($base_class_obj_or_id instanceof $className) {
5613
+			$model_object = $base_class_obj_or_id;
5614
+		} else {
5615
+			$primary_key_field = $this->get_primary_key_field();
5616
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5617
+				&& (
5618
+					is_int($base_class_obj_or_id)
5619
+					|| is_string($base_class_obj_or_id)
5620
+				)
5621
+			) {
5622
+				// assume it's an ID.
5623
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5624
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5625
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5626
+				&& is_string($base_class_obj_or_id)
5627
+			) {
5628
+				// assume its a string representation of the object
5629
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5630
+			} else {
5631
+				throw new EE_Error(
5632
+					sprintf(
5633
+						__(
5634
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5635
+							'event_espresso'
5636
+						),
5637
+						$base_class_obj_or_id,
5638
+						$this->_get_class_name(),
5639
+						print_r($base_class_obj_or_id, true)
5640
+					)
5641
+				);
5642
+			}
5643
+		}
5644
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5645
+			$model_object->save();
5646
+		}
5647
+		return $model_object;
5648
+	}
5649
+
5650
+
5651
+
5652
+	/**
5653
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5654
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5655
+	 * returns it ID.
5656
+	 *
5657
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5658
+	 * @return int|string depending on the type of this model object's ID
5659
+	 * @throws EE_Error
5660
+	 */
5661
+	public function ensure_is_ID($base_class_obj_or_id)
5662
+	{
5663
+		$className = $this->_get_class_name();
5664
+		if ($base_class_obj_or_id instanceof $className) {
5665
+			/** @var $base_class_obj_or_id EE_Base_Class */
5666
+			$id = $base_class_obj_or_id->ID();
5667
+		} elseif (is_int($base_class_obj_or_id)) {
5668
+			// assume it's an ID
5669
+			$id = $base_class_obj_or_id;
5670
+		} elseif (is_string($base_class_obj_or_id)) {
5671
+			// assume its a string representation of the object
5672
+			$id = $base_class_obj_or_id;
5673
+		} else {
5674
+			throw new EE_Error(sprintf(
5675
+				__(
5676
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5677
+					'event_espresso'
5678
+				),
5679
+				$base_class_obj_or_id,
5680
+				$this->_get_class_name(),
5681
+				print_r($base_class_obj_or_id, true)
5682
+			));
5683
+		}
5684
+		return $id;
5685
+	}
5686
+
5687
+
5688
+
5689
+	/**
5690
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5691
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5692
+	 * been sanitized and converted into the appropriate domain.
5693
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5694
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5695
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5696
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5697
+	 * $EVT = EEM_Event::instance(); $old_setting =
5698
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5699
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5700
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5701
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5702
+	 *
5703
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5704
+	 * @return void
5705
+	 */
5706
+	public function assume_values_already_prepared_by_model_object(
5707
+		$values_already_prepared = self::not_prepared_by_model_object
5708
+	) {
5709
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5710
+	}
5711
+
5712
+
5713
+
5714
+	/**
5715
+	 * Read comments for assume_values_already_prepared_by_model_object()
5716
+	 *
5717
+	 * @return int
5718
+	 */
5719
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5720
+	{
5721
+		return $this->_values_already_prepared_by_model_object;
5722
+	}
5723
+
5724
+
5725
+
5726
+	/**
5727
+	 * Gets all the indexes on this model
5728
+	 *
5729
+	 * @return EE_Index[]
5730
+	 */
5731
+	public function indexes()
5732
+	{
5733
+		return $this->_indexes;
5734
+	}
5735
+
5736
+
5737
+
5738
+	/**
5739
+	 * Gets all the Unique Indexes on this model
5740
+	 *
5741
+	 * @return EE_Unique_Index[]
5742
+	 */
5743
+	public function unique_indexes()
5744
+	{
5745
+		$unique_indexes = array();
5746
+		foreach ($this->_indexes as $name => $index) {
5747
+			if ($index instanceof EE_Unique_Index) {
5748
+				$unique_indexes [ $name ] = $index;
5749
+			}
5750
+		}
5751
+		return $unique_indexes;
5752
+	}
5753
+
5754
+
5755
+
5756
+	/**
5757
+	 * Gets all the fields which, when combined, make the primary key.
5758
+	 * This is usually just an array with 1 element (the primary key), but in cases
5759
+	 * where there is no primary key, it's a combination of fields as defined
5760
+	 * on a primary index
5761
+	 *
5762
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5763
+	 * @throws EE_Error
5764
+	 */
5765
+	public function get_combined_primary_key_fields()
5766
+	{
5767
+		foreach ($this->indexes() as $index) {
5768
+			if ($index instanceof EE_Primary_Key_Index) {
5769
+				return $index->fields();
5770
+			}
5771
+		}
5772
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5773
+	}
5774
+
5775
+
5776
+
5777
+	/**
5778
+	 * Used to build a primary key string (when the model has no primary key),
5779
+	 * which can be used a unique string to identify this model object.
5780
+	 *
5781
+	 * @param array $fields_n_values keys are field names, values are their values.
5782
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5783
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5784
+	 *                               before passing it to this function (that will convert it from columns-n-values
5785
+	 *                               to field-names-n-values).
5786
+	 * @return string
5787
+	 * @throws EE_Error
5788
+	 */
5789
+	public function get_index_primary_key_string($fields_n_values)
5790
+	{
5791
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5792
+			$fields_n_values,
5793
+			$this->get_combined_primary_key_fields()
5794
+		);
5795
+		return http_build_query($cols_n_values_for_primary_key_index);
5796
+	}
5797
+
5798
+
5799
+
5800
+	/**
5801
+	 * Gets the field values from the primary key string
5802
+	 *
5803
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5804
+	 * @param string $index_primary_key_string
5805
+	 * @return null|array
5806
+	 * @throws EE_Error
5807
+	 */
5808
+	public function parse_index_primary_key_string($index_primary_key_string)
5809
+	{
5810
+		$key_fields = $this->get_combined_primary_key_fields();
5811
+		// check all of them are in the $id
5812
+		$key_vals_in_combined_pk = array();
5813
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5814
+		foreach ($key_fields as $key_field_name => $field_obj) {
5815
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5816
+				return null;
5817
+			}
5818
+		}
5819
+		return $key_vals_in_combined_pk;
5820
+	}
5821
+
5822
+
5823
+
5824
+	/**
5825
+	 * verifies that an array of key-value pairs for model fields has a key
5826
+	 * for each field comprising the primary key index
5827
+	 *
5828
+	 * @param array $key_vals
5829
+	 * @return boolean
5830
+	 * @throws EE_Error
5831
+	 */
5832
+	public function has_all_combined_primary_key_fields($key_vals)
5833
+	{
5834
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5835
+		foreach ($keys_it_should_have as $key) {
5836
+			if (! isset($key_vals[ $key ])) {
5837
+				return false;
5838
+			}
5839
+		}
5840
+		return true;
5841
+	}
5842
+
5843
+
5844
+
5845
+	/**
5846
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5847
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5848
+	 *
5849
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5850
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5851
+	 * @throws EE_Error
5852
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5853
+	 *                                                              indexed)
5854
+	 */
5855
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5856
+	{
5857
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5858
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5859
+		} elseif (is_array($model_object_or_attributes_array)) {
5860
+			$attributes_array = $model_object_or_attributes_array;
5861
+		} else {
5862
+			throw new EE_Error(sprintf(__(
5863
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5864
+				"event_espresso"
5865
+			), $model_object_or_attributes_array));
5866
+		}
5867
+		// even copies obviously won't have the same ID, so remove the primary key
5868
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5869
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5870
+			unset($attributes_array[ $this->primary_key_name() ]);
5871
+		}
5872
+		if (isset($query_params[0])) {
5873
+			$query_params[0] = array_merge($attributes_array, $query_params);
5874
+		} else {
5875
+			$query_params[0] = $attributes_array;
5876
+		}
5877
+		return $this->get_all($query_params);
5878
+	}
5879
+
5880
+
5881
+
5882
+	/**
5883
+	 * Gets the first copy we find. See get_all_copies for more details
5884
+	 *
5885
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5886
+	 * @param array $query_params
5887
+	 * @return EE_Base_Class
5888
+	 * @throws EE_Error
5889
+	 */
5890
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5891
+	{
5892
+		if (! is_array($query_params)) {
5893
+			EE_Error::doing_it_wrong(
5894
+				'EEM_Base::get_one_copy',
5895
+				sprintf(
5896
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5897
+					gettype($query_params)
5898
+				),
5899
+				'4.6.0'
5900
+			);
5901
+			$query_params = array();
5902
+		}
5903
+		$query_params['limit'] = 1;
5904
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5905
+		if (is_array($copies)) {
5906
+			return array_shift($copies);
5907
+		}
5908
+		return null;
5909
+	}
5910
+
5911
+
5912
+
5913
+	/**
5914
+	 * Updates the item with the specified id. Ignores default query parameters because
5915
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5916
+	 *
5917
+	 * @param array      $fields_n_values keys are field names, values are their new values
5918
+	 * @param int|string $id              the value of the primary key to update
5919
+	 * @return int number of rows updated
5920
+	 * @throws EE_Error
5921
+	 */
5922
+	public function update_by_ID($fields_n_values, $id)
5923
+	{
5924
+		$query_params = array(
5925
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5926
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5927
+		);
5928
+		return $this->update($fields_n_values, $query_params);
5929
+	}
5930
+
5931
+
5932
+
5933
+	/**
5934
+	 * Changes an operator which was supplied to the models into one usable in SQL
5935
+	 *
5936
+	 * @param string $operator_supplied
5937
+	 * @return string an operator which can be used in SQL
5938
+	 * @throws EE_Error
5939
+	 */
5940
+	private function _prepare_operator_for_sql($operator_supplied)
5941
+	{
5942
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5943
+			: null;
5944
+		if ($sql_operator) {
5945
+			return $sql_operator;
5946
+		}
5947
+		throw new EE_Error(
5948
+			sprintf(
5949
+				__(
5950
+					"The operator '%s' is not in the list of valid operators: %s",
5951
+					"event_espresso"
5952
+				),
5953
+				$operator_supplied,
5954
+				implode(",", array_keys($this->_valid_operators))
5955
+			)
5956
+		);
5957
+	}
5958
+
5959
+
5960
+
5961
+	/**
5962
+	 * Gets the valid operators
5963
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5964
+	 */
5965
+	public function valid_operators()
5966
+	{
5967
+		return $this->_valid_operators;
5968
+	}
5969
+
5970
+
5971
+
5972
+	/**
5973
+	 * Gets the between-style operators (take 2 arguments).
5974
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5975
+	 */
5976
+	public function valid_between_style_operators()
5977
+	{
5978
+		return array_intersect(
5979
+			$this->valid_operators(),
5980
+			$this->_between_style_operators
5981
+		);
5982
+	}
5983
+
5984
+	/**
5985
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5986
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5987
+	 */
5988
+	public function valid_like_style_operators()
5989
+	{
5990
+		return array_intersect(
5991
+			$this->valid_operators(),
5992
+			$this->_like_style_operators
5993
+		);
5994
+	}
5995
+
5996
+	/**
5997
+	 * Gets the "in"-style operators
5998
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5999
+	 */
6000
+	public function valid_in_style_operators()
6001
+	{
6002
+		return array_intersect(
6003
+			$this->valid_operators(),
6004
+			$this->_in_style_operators
6005
+		);
6006
+	}
6007
+
6008
+	/**
6009
+	 * Gets the "null"-style operators (accept no arguments)
6010
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6011
+	 */
6012
+	public function valid_null_style_operators()
6013
+	{
6014
+		return array_intersect(
6015
+			$this->valid_operators(),
6016
+			$this->_null_style_operators
6017
+		);
6018
+	}
6019
+
6020
+	/**
6021
+	 * Gets an array where keys are the primary keys and values are their 'names'
6022
+	 * (as determined by the model object's name() function, which is often overridden)
6023
+	 *
6024
+	 * @param array $query_params like get_all's
6025
+	 * @return string[]
6026
+	 * @throws EE_Error
6027
+	 */
6028
+	public function get_all_names($query_params = array())
6029
+	{
6030
+		$objs = $this->get_all($query_params);
6031
+		$names = array();
6032
+		foreach ($objs as $obj) {
6033
+			$names[ $obj->ID() ] = $obj->name();
6034
+		}
6035
+		return $names;
6036
+	}
6037
+
6038
+
6039
+
6040
+	/**
6041
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6042
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6043
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6044
+	 * array_keys() on $model_objects.
6045
+	 *
6046
+	 * @param \EE_Base_Class[] $model_objects
6047
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6048
+	 *                                               in the returned array
6049
+	 * @return array
6050
+	 * @throws EE_Error
6051
+	 */
6052
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6053
+	{
6054
+		if (! $this->has_primary_key_field()) {
6055
+			if (WP_DEBUG) {
6056
+				EE_Error::add_error(
6057
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6058
+					__FILE__,
6059
+					__FUNCTION__,
6060
+					__LINE__
6061
+				);
6062
+			}
6063
+		}
6064
+		$IDs = array();
6065
+		foreach ($model_objects as $model_object) {
6066
+			$id = $model_object->ID();
6067
+			if (! $id) {
6068
+				if ($filter_out_empty_ids) {
6069
+					continue;
6070
+				}
6071
+				if (WP_DEBUG) {
6072
+					EE_Error::add_error(
6073
+						__(
6074
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6075
+							'event_espresso'
6076
+						),
6077
+						__FILE__,
6078
+						__FUNCTION__,
6079
+						__LINE__
6080
+					);
6081
+				}
6082
+			}
6083
+			$IDs[] = $id;
6084
+		}
6085
+		return $IDs;
6086
+	}
6087
+
6088
+
6089
+
6090
+	/**
6091
+	 * Returns the string used in capabilities relating to this model. If there
6092
+	 * are no capabilities that relate to this model returns false
6093
+	 *
6094
+	 * @return string|false
6095
+	 */
6096
+	public function cap_slug()
6097
+	{
6098
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6099
+	}
6100
+
6101
+
6102
+
6103
+	/**
6104
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6105
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6106
+	 * only returns the cap restrictions array in that context (ie, the array
6107
+	 * at that key)
6108
+	 *
6109
+	 * @param string $context
6110
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6111
+	 * @throws EE_Error
6112
+	 */
6113
+	public function cap_restrictions($context = EEM_Base::caps_read)
6114
+	{
6115
+		EEM_Base::verify_is_valid_cap_context($context);
6116
+		// check if we ought to run the restriction generator first
6117
+		if (isset($this->_cap_restriction_generators[ $context ])
6118
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6119
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6120
+		) {
6121
+			$this->_cap_restrictions[ $context ] = array_merge(
6122
+				$this->_cap_restrictions[ $context ],
6123
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6124
+			);
6125
+		}
6126
+		// and make sure we've finalized the construction of each restriction
6127
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6128
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6129
+				$where_conditions_obj->_finalize_construct($this);
6130
+			}
6131
+		}
6132
+		return $this->_cap_restrictions[ $context ];
6133
+	}
6134
+
6135
+
6136
+
6137
+	/**
6138
+	 * Indicating whether or not this model thinks its a wp core model
6139
+	 *
6140
+	 * @return boolean
6141
+	 */
6142
+	public function is_wp_core_model()
6143
+	{
6144
+		return $this->_wp_core_model;
6145
+	}
6146
+
6147
+
6148
+
6149
+	/**
6150
+	 * Gets all the caps that are missing which impose a restriction on
6151
+	 * queries made in this context
6152
+	 *
6153
+	 * @param string $context one of EEM_Base::caps_ constants
6154
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6155
+	 * @throws EE_Error
6156
+	 */
6157
+	public function caps_missing($context = EEM_Base::caps_read)
6158
+	{
6159
+		$missing_caps = array();
6160
+		$cap_restrictions = $this->cap_restrictions($context);
6161
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6162
+			if (! EE_Capabilities::instance()
6163
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6164
+			) {
6165
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6166
+			}
6167
+		}
6168
+		return $missing_caps;
6169
+	}
6170
+
6171
+
6172
+
6173
+	/**
6174
+	 * Gets the mapping from capability contexts to action strings used in capability names
6175
+	 *
6176
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6177
+	 * one of 'read', 'edit', or 'delete'
6178
+	 */
6179
+	public function cap_contexts_to_cap_action_map()
6180
+	{
6181
+		return apply_filters(
6182
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6183
+			$this->_cap_contexts_to_cap_action_map,
6184
+			$this
6185
+		);
6186
+	}
6187
+
6188
+
6189
+
6190
+	/**
6191
+	 * Gets the action string for the specified capability context
6192
+	 *
6193
+	 * @param string $context
6194
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6195
+	 * @throws EE_Error
6196
+	 */
6197
+	public function cap_action_for_context($context)
6198
+	{
6199
+		$mapping = $this->cap_contexts_to_cap_action_map();
6200
+		if (isset($mapping[ $context ])) {
6201
+			return $mapping[ $context ];
6202
+		}
6203
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6204
+			return $action;
6205
+		}
6206
+		throw new EE_Error(
6207
+			sprintf(
6208
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6209
+				$context,
6210
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6211
+			)
6212
+		);
6213
+	}
6214
+
6215
+
6216
+
6217
+	/**
6218
+	 * Returns all the capability contexts which are valid when querying models
6219
+	 *
6220
+	 * @return array
6221
+	 */
6222
+	public static function valid_cap_contexts()
6223
+	{
6224
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6225
+			self::caps_read,
6226
+			self::caps_read_admin,
6227
+			self::caps_edit,
6228
+			self::caps_delete,
6229
+		));
6230
+	}
6231
+
6232
+
6233
+
6234
+	/**
6235
+	 * Returns all valid options for 'default_where_conditions'
6236
+	 *
6237
+	 * @return array
6238
+	 */
6239
+	public static function valid_default_where_conditions()
6240
+	{
6241
+		return array(
6242
+			EEM_Base::default_where_conditions_all,
6243
+			EEM_Base::default_where_conditions_this_only,
6244
+			EEM_Base::default_where_conditions_others_only,
6245
+			EEM_Base::default_where_conditions_minimum_all,
6246
+			EEM_Base::default_where_conditions_minimum_others,
6247
+			EEM_Base::default_where_conditions_none
6248
+		);
6249
+	}
6250
+
6251
+	// public static function default_where_conditions_full
6252
+	/**
6253
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6254
+	 *
6255
+	 * @param string $context
6256
+	 * @return bool
6257
+	 * @throws EE_Error
6258
+	 */
6259
+	public static function verify_is_valid_cap_context($context)
6260
+	{
6261
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6262
+		if (in_array($context, $valid_cap_contexts)) {
6263
+			return true;
6264
+		}
6265
+		throw new EE_Error(
6266
+			sprintf(
6267
+				__(
6268
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6269
+					'event_espresso'
6270
+				),
6271
+				$context,
6272
+				'EEM_Base',
6273
+				implode(',', $valid_cap_contexts)
6274
+			)
6275
+		);
6276
+	}
6277
+
6278
+
6279
+
6280
+	/**
6281
+	 * Clears all the models field caches. This is only useful when a sub-class
6282
+	 * might have added a field or something and these caches might be invalidated
6283
+	 */
6284
+	protected function _invalidate_field_caches()
6285
+	{
6286
+		$this->_cache_foreign_key_to_fields = array();
6287
+		$this->_cached_fields = null;
6288
+		$this->_cached_fields_non_db_only = null;
6289
+	}
6290
+
6291
+
6292
+
6293
+	/**
6294
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6295
+	 * (eg "and", "or", "not").
6296
+	 *
6297
+	 * @return array
6298
+	 */
6299
+	public function logic_query_param_keys()
6300
+	{
6301
+		return $this->_logic_query_param_keys;
6302
+	}
6303
+
6304
+
6305
+
6306
+	/**
6307
+	 * Determines whether or not the where query param array key is for a logic query param.
6308
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6309
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6310
+	 *
6311
+	 * @param $query_param_key
6312
+	 * @return bool
6313
+	 */
6314
+	public function is_logic_query_param_key($query_param_key)
6315
+	{
6316
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6317
+			if ($query_param_key === $logic_query_param_key
6318
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6319
+			) {
6320
+				return true;
6321
+			}
6322
+		}
6323
+		return false;
6324
+	}
6325
+
6326
+	/**
6327
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6328
+	 * @since 4.9.74.p
6329
+	 * @return boolean
6330
+	 */
6331
+	public function hasPassword()
6332
+	{
6333
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6334
+		if ($this->has_password_field === null) {
6335
+			$password_field = $this->getPasswordField();
6336
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6337
+		}
6338
+		return $this->has_password_field;
6339
+	}
6340
+
6341
+	/**
6342
+	 * Returns the password field on this model, if there is one
6343
+	 * @since 4.9.74.p
6344
+	 * @return EE_Password_Field|null
6345
+	 */
6346
+	public function getPasswordField()
6347
+	{
6348
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6349
+		// there's no need to search for it. If we don't know yet, then find out
6350
+		if ($this->has_password_field === null && $this->password_field === null) {
6351
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6352
+		}
6353
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6354
+		return $this->password_field;
6355
+	}
6356
+
6357
+
6358
+	/**
6359
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6360
+	 * @since 4.9.74.p
6361
+	 * @return EE_Model_Field_Base[]
6362
+	 * @throws EE_Error
6363
+	 */
6364
+	public function getPasswordProtectedFields()
6365
+	{
6366
+		$password_field = $this->getPasswordField();
6367
+		$fields = array();
6368
+		if ($password_field instanceof EE_Password_Field) {
6369
+			$field_names = $password_field->protectedFields();
6370
+			foreach ($field_names as $field_name) {
6371
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6372
+			}
6373
+		}
6374
+		return $fields;
6375
+	}
6376
+
6377
+
6378
+	/**
6379
+	 * Checks if the current user can perform the requested action on this model
6380
+	 * @since 4.9.74.p
6381
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6382
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6383
+	 * @return bool
6384
+	 * @throws EE_Error
6385
+	 * @throws InvalidArgumentException
6386
+	 * @throws InvalidDataTypeException
6387
+	 * @throws InvalidInterfaceException
6388
+	 * @throws ReflectionException
6389
+	 * @throws UnexpectedEntityException
6390
+	 */
6391
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6392
+	{
6393
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6394
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6395
+		}
6396
+		if (!is_array($model_obj_or_fields_n_values)) {
6397
+			throw new UnexpectedEntityException(
6398
+				$model_obj_or_fields_n_values,
6399
+				'EE_Base_Class',
6400
+				sprintf(
6401
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6402
+					__FUNCTION__
6403
+				)
6404
+			);
6405
+		}
6406
+		return $this->exists(
6407
+			$this->alter_query_params_to_restrict_by_ID(
6408
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6409
+				array(
6410
+					'default_where_conditions' => 'none',
6411
+					'caps'                     => $cap_to_check,
6412
+				)
6413
+			)
6414
+		);
6415
+	}
6416
+
6417
+	/**
6418
+	 * Returns the query param where conditions key to the password affecting this model.
6419
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6420
+	 * @since 4.9.74.p
6421
+	 * @return null|string
6422
+	 * @throws EE_Error
6423
+	 * @throws InvalidArgumentException
6424
+	 * @throws InvalidDataTypeException
6425
+	 * @throws InvalidInterfaceException
6426
+	 * @throws ModelConfigurationException
6427
+	 * @throws ReflectionException
6428
+	 */
6429
+	public function modelChainAndPassword()
6430
+	{
6431
+		if ($this->model_chain_to_password === null) {
6432
+			throw new ModelConfigurationException(
6433
+				$this,
6434
+				esc_html_x(
6435
+				// @codingStandardsIgnoreStart
6436
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6437
+					// @codingStandardsIgnoreEnd
6438
+					'1: model name',
6439
+					'event_espresso'
6440
+				)
6441
+			);
6442
+		}
6443
+		if ($this->model_chain_to_password === '') {
6444
+			$model_with_password = $this;
6445
+		} else {
6446
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6447
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6448
+			} else {
6449
+				$last_model_in_chain = $this->model_chain_to_password;
6450
+			}
6451
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6452
+		}
6453
+
6454
+		$password_field = $model_with_password->getPasswordField();
6455
+		if ($password_field instanceof EE_Password_Field) {
6456
+			$password_field_name = $password_field->get_name();
6457
+		} else {
6458
+			throw new ModelConfigurationException(
6459
+				$this,
6460
+				sprintf(
6461
+					esc_html_x(
6462
+						'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"',
6463
+						'1: model name, 2: special string',
6464
+						'event_espresso'
6465
+					),
6466
+					$model_with_password->get_this_model_name(),
6467
+					$this->model_chain_to_password
6468
+				)
6469
+			);
6470
+		}
6471
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6472
+	}
6473
+
6474
+	/**
6475
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6476
+	 * or if this model itself has a password affecting access to some of its other fields.
6477
+	 * @since 4.9.74.p
6478
+	 * @return boolean
6479
+	 */
6480
+	public function restrictedByRelatedModelPassword()
6481
+	{
6482
+		return $this->model_chain_to_password !== null;
6483
+	}
6484 6484
 }
Please login to merge, or discard this patch.
Spacing   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     protected function __construct($timezone = null)
555 555
     {
556 556
         // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
557
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
558 558
             throw new EE_Error(
559 559
                 sprintf(
560 560
                     __(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @var EE_Table_Base[] $_tables
579 579
          */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
580
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
581 581
         foreach ($this->_tables as $table_alias => $table_obj) {
582 582
             /** @var $table_obj EE_Table_Base */
583 583
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
          *
593 593
          * @param EE_Model_Field_Base[] $_fields
594 594
          */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
595
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
596 596
         $this->_invalidate_field_caches();
597 597
         foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
598
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
599 599
                 throw new EE_Error(sprintf(__(
600 600
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601 601
                     'event_espresso'
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
          * @param EE_Model_Relation_Base[] $_model_relations
627 627
          */
628 628
         $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
629
+            'FHEE__'.get_class($this).'__construct__model_relations',
630 630
             $this->_model_relations
631 631
         );
632 632
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
         }
640 640
         $this->set_timezone($timezone);
641 641
         // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
642
+        if ( ! $this->_default_where_conditions_strategy) {
643 643
             // nothing was set during child constructor, so set default
644 644
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645 645
         }
646 646
         $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
647
+        if ( ! $this->_minimum_where_conditions_strategy) {
648 648
             // nothing was set during child constructor, so set default
649 649
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650 650
         }
@@ -657,8 +657,8 @@  discard block
 block discarded – undo
657 657
         // initialize the standard cap restriction generators if none were specified by the child constructor
658 658
         if ($this->_cap_restriction_generators !== false) {
659 659
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
660
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
661
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
662 662
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663 663
                         new EE_Restriction_Generator_Protected(),
664 664
                         $cap_context,
@@ -670,10 +670,10 @@  discard block
 block discarded – undo
670 670
         // if there are cap restriction generators, use them to make the default cap restrictions
671 671
         if ($this->_cap_restriction_generators !== false) {
672 672
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
673
+                if ( ! $generator_object) {
674 674
                     continue;
675 675
                 }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
676
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
677 677
                     throw new EE_Error(
678 678
                         sprintf(
679 679
                             __(
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
                     );
687 687
                 }
688 688
                 $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
689
+                if ( ! $generator_object->construction_finalized()) {
690 690
                     $generator_object->_construct_finalize($this, $action);
691 691
                 }
692 692
             }
693 693
         }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
694
+        do_action('AHEE__'.get_class($this).'__construct__end');
695 695
     }
696 696
 
697 697
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     public static function instance($timezone = null)
739 739
     {
740 740
         // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
741
+        if ( ! static::$_instance instanceof static) {
742 742
             // instantiate Espresso_model
743 743
             static::$_instance = new static(
744 744
                 $timezone,
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach ($r->getDefaultProperties() as $property => $value) {
778 778
                 // don't set instance to null like it was originally,
779 779
                 // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
780
+                if ( ! isset($static_properties[$property])) {
781 781
                     static::$_instance->{$property} = $value;
782 782
                 }
783 783
             }
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
      */
802 802
     private static function getLoader()
803 803
     {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
804
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
805 805
             EEM_Base::$loader = LoaderFactory::getLoader();
806 806
         }
807 807
         return EEM_Base::$loader;
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
      */
822 822
     public function status_array($translated = false)
823 823
     {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
824
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
825 825
             return array();
826 826
         }
827 827
         $model_name = $this->get_this_model_name();
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830 830
         $status_array = array();
831 831
         foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
832
+            $status_array[$status->ID()] = $status->get('STS_code');
833 833
         }
834 834
         return $translated
835 835
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
     {
890 890
         $wp_user_field_name = $this->wp_user_field_name();
891 891
         if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
892
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
893 893
         }
894 894
         return $query_params;
895 895
     }
@@ -907,17 +907,17 @@  discard block
 block discarded – undo
907 907
     public function wp_user_field_name()
908 908
     {
909 909
         try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
910
+            if ( ! empty($this->_model_chain_to_wp_user)) {
911 911
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912 912
                 $last_model_name = end($models_to_follow_to_wp_users);
913 913
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
914
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
915 915
             } else {
916 916
                 $model_with_fk_to_wp_users = $this;
917 917
                 $model_chain_to_wp_user = '';
918 918
             }
919 919
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
920
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
921 921
         } catch (EE_Error $e) {
922 922
             return false;
923 923
         }
@@ -994,11 +994,11 @@  discard block
 block discarded – undo
994 994
         if ($this->_custom_selections instanceof CustomSelects) {
995 995
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996 996
             $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
997
+                ? ', '.$custom_expressions
998 998
                 : $custom_expressions;
999 999
         }
1000 1000
 
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1001
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1002 1002
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003 1003
     }
1004 1004
 
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
      */
1016 1016
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017 1017
     {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1018
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019 1019
             return null;
1020 1020
         }
1021 1021
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
         if (is_array($columns_to_select)) {
1065 1065
             $select_sql_array = array();
1066 1066
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1067
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068 1068
                     throw new EE_Error(
1069 1069
                         sprintf(
1070 1070
                             __(
@@ -1076,7 +1076,7 @@  discard block
 block discarded – undo
1076 1076
                         )
1077 1077
                     );
1078 1078
                 }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1079
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080 1080
                     throw new EE_Error(
1081 1081
                         sprintf(
1082 1082
                             esc_html__(
@@ -1148,12 +1148,12 @@  discard block
 block discarded – undo
1148 1148
      */
1149 1149
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1150 1150
     {
1151
-        if (! isset($query_params[0])) {
1151
+        if ( ! isset($query_params[0])) {
1152 1152
             $query_params[0] = array();
1153 1153
         }
1154 1154
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1155 1155
         if ($conditions_from_id === null) {
1156
-            $query_params[0][ $this->primary_key_name() ] = $id;
1156
+            $query_params[0][$this->primary_key_name()] = $id;
1157 1157
         } else {
1158 1158
             // no primary key, so the $id must be from the get_index_primary_key_string()
1159 1159
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
      */
1174 1174
     public function get_one($query_params = array())
1175 1175
     {
1176
-        if (! is_array($query_params)) {
1176
+        if ( ! is_array($query_params)) {
1177 1177
             EE_Error::doing_it_wrong(
1178 1178
                 'EEM_Base::get_one',
1179 1179
                 sprintf(
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
                 return array();
1372 1372
             }
1373 1373
         }
1374
-        if (! is_array($query_params)) {
1374
+        if ( ! is_array($query_params)) {
1375 1375
             EE_Error::doing_it_wrong(
1376 1376
                 'EEM_Base::_get_consecutive',
1377 1377
                 sprintf(
@@ -1383,7 +1383,7 @@  discard block
 block discarded – undo
1383 1383
             $query_params = array();
1384 1384
         }
1385 1385
         // let's add the where query param for consecutive look up.
1386
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1386
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387 1387
         $query_params['limit'] = $limit;
1388 1388
         // set direction
1389 1389
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1464,7 +1464,7 @@  discard block
 block discarded – undo
1464 1464
     {
1465 1465
         $field_settings = $this->field_settings_for($field_name);
1466 1466
         // if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1467
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1468 1468
             throw new EE_Error(sprintf(__(
1469 1469
                 '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.',
1470 1470
                 'event_espresso'
@@ -1613,7 +1613,7 @@  discard block
 block discarded – undo
1613 1613
      */
1614 1614
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1615 1615
     {
1616
-        if (! is_array($query_params)) {
1616
+        if ( ! is_array($query_params)) {
1617 1617
             EE_Error::doing_it_wrong(
1618 1618
                 'EEM_Base::update',
1619 1619
                 sprintf(
@@ -1661,7 +1661,7 @@  discard block
 block discarded – undo
1661 1661
             $wpdb_result = (array) $wpdb_result;
1662 1662
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1663 1663
             if ($this->has_primary_key_field()) {
1664
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1664
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1665 1665
             } else {
1666 1666
                 // 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)
1667 1667
                 $main_table_pk_value = null;
@@ -1675,8 +1675,8 @@  discard block
 block discarded – undo
1675 1675
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1676 1676
                     // if there is no private key for this table on the results, it means there's no entry
1677 1677
                     // in this table, right? so insert a row in the current table, using any fields available
1678
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1679
-                           && $wpdb_result[ $this_table_pk_column ])
1678
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1679
+                           && $wpdb_result[$this_table_pk_column])
1680 1680
                     ) {
1681 1681
                         $success = $this->_insert_into_specific_table(
1682 1682
                             $table_obj,
@@ -1684,7 +1684,7 @@  discard block
 block discarded – undo
1684 1684
                             $main_table_pk_value
1685 1685
                         );
1686 1686
                         // if we died here, report the error
1687
-                        if (! $success) {
1687
+                        if ( ! $success) {
1688 1688
                             return false;
1689 1689
                         }
1690 1690
                     }
@@ -1712,10 +1712,10 @@  discard block
 block discarded – undo
1712 1712
                 $model_objs_affected_ids = array();
1713 1713
                 foreach ($models_affected_key_columns as $row) {
1714 1714
                     $combined_index_key = $this->get_index_primary_key_string($row);
1715
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1715
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1716 1716
                 }
1717 1717
             }
1718
-            if (! $model_objs_affected_ids) {
1718
+            if ( ! $model_objs_affected_ids) {
1719 1719
                 // wait wait wait- if nothing was affected let's stop here
1720 1720
                 return 0;
1721 1721
             }
@@ -1742,7 +1742,7 @@  discard block
 block discarded – undo
1742 1742
                . $model_query_info->get_full_join_sql()
1743 1743
                . " SET "
1744 1744
                . $this->_construct_update_sql($fields_n_values)
1745
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1745
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1746 1746
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1747 1747
         /**
1748 1748
          * Action called after a model update call has been made.
@@ -1753,7 +1753,7 @@  discard block
 block discarded – undo
1753 1753
          * @param int      $rows_affected
1754 1754
          */
1755 1755
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1756
-        return $rows_affected;// how many supposedly got updated
1756
+        return $rows_affected; // how many supposedly got updated
1757 1757
     }
1758 1758
 
1759 1759
 
@@ -1781,7 +1781,7 @@  discard block
 block discarded – undo
1781 1781
         }
1782 1782
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1783 1783
         $select_expressions = $field->get_qualified_column();
1784
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1784
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1785 1785
         return $this->_do_wpdb_query('get_col', array($SQL));
1786 1786
     }
1787 1787
 
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
     {
1800 1800
         $query_params['limit'] = 1;
1801 1801
         $col = $this->get_col($query_params, $field_to_select);
1802
-        if (! empty($col)) {
1802
+        if ( ! empty($col)) {
1803 1803
             return reset($col);
1804 1804
         }
1805 1805
         return null;
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1831 1831
             $value_sql = $prepared_value === null ? 'NULL'
1832 1832
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1833
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1833
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1834 1834
         }
1835 1835
         return implode(",", $cols_n_values);
1836 1836
     }
@@ -1973,12 +1973,12 @@  discard block
 block discarded – undo
1973 1973
         // there was no error with the delete query.
1974 1974
         if ($this->has_primary_key_field()
1975 1975
             && $rows_deleted !== false
1976
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1976
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1977 1977
         ) {
1978
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1978
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1979 1979
             foreach ($ids_for_removal as $id) {
1980
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1981
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1980
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1981
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1982 1982
                 }
1983 1983
             }
1984 1984
 
@@ -2013,7 +2013,7 @@  discard block
 block discarded – undo
2013 2013
          * @param int      $rows_deleted
2014 2014
          */
2015 2015
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2016
-        return $rows_deleted;// how many supposedly got deleted
2016
+        return $rows_deleted; // how many supposedly got deleted
2017 2017
     }
2018 2018
 
2019 2019
 
@@ -2106,15 +2106,15 @@  discard block
 block discarded – undo
2106 2106
                 // make sure there's no related entities blocking its deletion (if we're checking)
2107 2107
                 if ($allow_blocking
2108 2108
                     && $this->delete_is_blocked_by_related_models(
2109
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2109
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2110 2110
                     )
2111 2111
                 ) {
2112 2112
                     continue;
2113 2113
                 }
2114 2114
                 // primary table deletes
2115
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2116
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2117
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2115
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2116
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2117
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2118 2118
                 }
2119 2119
             }
2120 2120
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2123,8 +2123,8 @@  discard block
 block discarded – undo
2123 2123
                 $ids_to_delete_indexed_by_column_for_row = array();
2124 2124
                 foreach ($fields as $cpk_field) {
2125 2125
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2126
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2127
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2126
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2127
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2128 2128
                     }
2129 2129
                 }
2130 2130
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2164,7 +2164,7 @@  discard block
 block discarded – undo
2164 2164
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2165 2165
                 // make sure we have unique $ids
2166 2166
                 $ids = array_unique($ids);
2167
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2167
+                $query[] = $column.' IN('.implode(',', $ids).')';
2168 2168
             }
2169 2169
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2170 2170
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2172,7 +2172,7 @@  discard block
 block discarded – undo
2172 2172
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2173 2173
                 $values_for_each_combined_primary_key_for_a_row = array();
2174 2174
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2175
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2175
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2176 2176
                 }
2177 2177
                 $ways_to_identify_a_row[] = '('
2178 2178
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2244,8 +2244,8 @@  discard block
 block discarded – undo
2244 2244
                 $column_to_count = '*';
2245 2245
             }
2246 2246
         }
2247
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2248
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2247
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2248
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2249 2249
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2250 2250
     }
2251 2251
 
@@ -2268,7 +2268,7 @@  discard block
 block discarded – undo
2268 2268
             $field_obj = $this->get_primary_key_field();
2269 2269
         }
2270 2270
         $column_to_count = $field_obj->get_qualified_column();
2271
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2271
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2272 2272
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2273 2273
         $data_type = $field_obj->get_wpdb_data_type();
2274 2274
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2295,7 +2295,7 @@  discard block
 block discarded – undo
2295 2295
         // if we're in maintenance mode level 2, DON'T run any queries
2296 2296
         // because level 2 indicates the database needs updating and
2297 2297
         // is probably out of sync with the code
2298
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2298
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2299 2299
             throw new EE_Error(sprintf(__(
2300 2300
                 "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.",
2301 2301
                 "event_espresso"
@@ -2303,7 +2303,7 @@  discard block
 block discarded – undo
2303 2303
         }
2304 2304
         /** @type WPDB $wpdb */
2305 2305
         global $wpdb;
2306
-        if (! method_exists($wpdb, $wpdb_method)) {
2306
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2307 2307
             throw new EE_Error(sprintf(__(
2308 2308
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2309 2309
                 'event_espresso'
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2318 2318
         if (WP_DEBUG) {
2319 2319
             $wpdb->show_errors($old_show_errors_value);
2320
-            if (! empty($wpdb->last_error)) {
2320
+            if ( ! empty($wpdb->last_error)) {
2321 2321
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2322 2322
             }
2323 2323
             if ($result === false) {
@@ -2382,7 +2382,7 @@  discard block
 block discarded – undo
2382 2382
                     return $result;
2383 2383
                     break;
2384 2384
             }
2385
-            if (! empty($error_message)) {
2385
+            if ( ! empty($error_message)) {
2386 2386
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2387 2387
                 trigger_error($error_message);
2388 2388
             }
@@ -2462,11 +2462,11 @@  discard block
 block discarded – undo
2462 2462
      */
2463 2463
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2464 2464
     {
2465
-        return " FROM " . $model_query_info->get_full_join_sql() .
2466
-               $model_query_info->get_where_sql() .
2467
-               $model_query_info->get_group_by_sql() .
2468
-               $model_query_info->get_having_sql() .
2469
-               $model_query_info->get_order_by_sql() .
2465
+        return " FROM ".$model_query_info->get_full_join_sql().
2466
+               $model_query_info->get_where_sql().
2467
+               $model_query_info->get_group_by_sql().
2468
+               $model_query_info->get_having_sql().
2469
+               $model_query_info->get_order_by_sql().
2470 2470
                $model_query_info->get_limit_sql();
2471 2471
     }
2472 2472
 
@@ -2662,12 +2662,12 @@  discard block
 block discarded – undo
2662 2662
         $related_model = $this->get_related_model_obj($model_name);
2663 2663
         // we're just going to use the query params on the related model's normal get_all query,
2664 2664
         // except add a condition to say to match the current mod
2665
-        if (! isset($query_params['default_where_conditions'])) {
2665
+        if ( ! isset($query_params['default_where_conditions'])) {
2666 2666
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2667 2667
         }
2668 2668
         $this_model_name = $this->get_this_model_name();
2669 2669
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2670
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2670
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2671 2671
         return $related_model->count($query_params, $field_to_count, $distinct);
2672 2672
     }
2673 2673
 
@@ -2687,7 +2687,7 @@  discard block
 block discarded – undo
2687 2687
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2688 2688
     {
2689 2689
         $related_model = $this->get_related_model_obj($model_name);
2690
-        if (! is_array($query_params)) {
2690
+        if ( ! is_array($query_params)) {
2691 2691
             EE_Error::doing_it_wrong(
2692 2692
                 'EEM_Base::sum_related',
2693 2693
                 sprintf(
@@ -2700,12 +2700,12 @@  discard block
 block discarded – undo
2700 2700
         }
2701 2701
         // we're just going to use the query params on the related model's normal get_all query,
2702 2702
         // except add a condition to say to match the current mod
2703
-        if (! isset($query_params['default_where_conditions'])) {
2703
+        if ( ! isset($query_params['default_where_conditions'])) {
2704 2704
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2705 2705
         }
2706 2706
         $this_model_name = $this->get_this_model_name();
2707 2707
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2708
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2708
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2709 2709
         return $related_model->sum($query_params, $field_to_sum);
2710 2710
     }
2711 2711
 
@@ -2758,7 +2758,7 @@  discard block
 block discarded – undo
2758 2758
                 $field_with_model_name = $field;
2759 2759
             }
2760 2760
         }
2761
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2761
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2762 2762
             throw new EE_Error(sprintf(
2763 2763
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2764 2764
                 $this->get_this_model_name()
@@ -2894,13 +2894,13 @@  discard block
 block discarded – undo
2894 2894
                 || $this->get_primary_key_field()
2895 2895
                    instanceof
2896 2896
                    EE_Primary_Key_String_Field)
2897
-            && isset($fields_n_values[ $this->primary_key_name() ])
2897
+            && isset($fields_n_values[$this->primary_key_name()])
2898 2898
         ) {
2899
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2899
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2900 2900
         }
2901 2901
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2902 2902
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2903
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2903
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2904 2904
         }
2905 2905
         // if there is nothing to base this search on, then we shouldn't find anything
2906 2906
         if (empty($query_params)) {
@@ -2978,15 +2978,15 @@  discard block
 block discarded – undo
2978 2978
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2979 2979
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2980 2980
             if ($prepared_value !== null) {
2981
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2981
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2982 2982
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2983 2983
             }
2984 2984
         }
2985 2985
         if ($table instanceof EE_Secondary_Table && $new_id) {
2986 2986
             // its not the main table, so we should have already saved the main table's PK which we just inserted
2987 2987
             // so add the fk to the main table as a column
2988
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2989
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2988
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2989
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
2990 2990
         }
2991 2991
         // insert the new entry
2992 2992
         $result = $this->_do_wpdb_query(
@@ -3003,7 +3003,7 @@  discard block
 block discarded – undo
3003 3003
             }
3004 3004
             // it's not an auto-increment primary key, so
3005 3005
             // it must have been supplied
3006
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3006
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3007 3007
         }
3008 3008
         // we can't return a  primary key because there is none. instead return
3009 3009
         // a unique string indicating this model
@@ -3025,16 +3025,16 @@  discard block
 block discarded – undo
3025 3025
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3026 3026
     {
3027 3027
         // if this field doesn't allow nullable, don't allow it
3028
-        if (! $field_obj->is_nullable()
3028
+        if ( ! $field_obj->is_nullable()
3029 3029
             && (
3030
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3031
-                || $fields_n_values[ $field_obj->get_name() ] === null
3030
+                ! isset($fields_n_values[$field_obj->get_name()])
3031
+                || $fields_n_values[$field_obj->get_name()] === null
3032 3032
             )
3033 3033
         ) {
3034
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3034
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3035 3035
         }
3036
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3037
-            ? $fields_n_values[ $field_obj->get_name() ]
3036
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3037
+            ? $fields_n_values[$field_obj->get_name()]
3038 3038
             : null;
3039 3039
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3040 3040
     }
@@ -3135,7 +3135,7 @@  discard block
 block discarded – undo
3135 3135
      */
3136 3136
     public function get_table_obj_by_alias($table_alias = '')
3137 3137
     {
3138
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3138
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3139 3139
     }
3140 3140
 
3141 3141
 
@@ -3150,7 +3150,7 @@  discard block
 block discarded – undo
3150 3150
         $other_tables = array();
3151 3151
         foreach ($this->_tables as $table_alias => $table) {
3152 3152
             if ($table instanceof EE_Secondary_Table) {
3153
-                $other_tables[ $table_alias ] = $table;
3153
+                $other_tables[$table_alias] = $table;
3154 3154
             }
3155 3155
         }
3156 3156
         return $other_tables;
@@ -3166,7 +3166,7 @@  discard block
 block discarded – undo
3166 3166
      */
3167 3167
     public function _get_fields_for_table($table_alias)
3168 3168
     {
3169
-        return $this->_fields[ $table_alias ];
3169
+        return $this->_fields[$table_alias];
3170 3170
     }
3171 3171
 
3172 3172
 
@@ -3195,7 +3195,7 @@  discard block
 block discarded – undo
3195 3195
                     $query_info_carrier,
3196 3196
                     'group_by'
3197 3197
                 );
3198
-            } elseif (! empty($query_params['group_by'])) {
3198
+            } elseif ( ! empty($query_params['group_by'])) {
3199 3199
                 $this->_extract_related_model_info_from_query_param(
3200 3200
                     $query_params['group_by'],
3201 3201
                     $query_info_carrier,
@@ -3217,7 +3217,7 @@  discard block
 block discarded – undo
3217 3217
                     $query_info_carrier,
3218 3218
                     'order_by'
3219 3219
                 );
3220
-            } elseif (! empty($query_params['order_by'])) {
3220
+            } elseif ( ! empty($query_params['order_by'])) {
3221 3221
                 $this->_extract_related_model_info_from_query_param(
3222 3222
                     $query_params['order_by'],
3223 3223
                     $query_info_carrier,
@@ -3252,7 +3252,7 @@  discard block
 block discarded – undo
3252 3252
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253 3253
         $query_param_type
3254 3254
     ) {
3255
-        if (! empty($sub_query_params)) {
3255
+        if ( ! empty($sub_query_params)) {
3256 3256
             $sub_query_params = (array) $sub_query_params;
3257 3257
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258 3258
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
                 // of array('Registration.TXN_ID'=>23)
3268 3268
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3269 3269
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3270
-                    if (! is_array($possibly_array_of_params)) {
3270
+                    if ( ! is_array($possibly_array_of_params)) {
3271 3271
                         throw new EE_Error(sprintf(
3272 3272
                             __(
3273 3273
                                 "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'))",
@@ -3290,7 +3290,7 @@  discard block
 block discarded – undo
3290 3290
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3291 3291
                     // indicating that $possible_array_of_params[1] is actually a field name,
3292 3292
                     // from which we should extract query parameters!
3293
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3293
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3294 3294
                         throw new EE_Error(sprintf(__(
3295 3295
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3296 3296
                             "event_espresso"
@@ -3324,8 +3324,8 @@  discard block
 block discarded – undo
3324 3324
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3325 3325
         $query_param_type
3326 3326
     ) {
3327
-        if (! empty($sub_query_params)) {
3328
-            if (! is_array($sub_query_params)) {
3327
+        if ( ! empty($sub_query_params)) {
3328
+            if ( ! is_array($sub_query_params)) {
3329 3329
                 throw new EE_Error(sprintf(
3330 3330
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3331 3331
                     $sub_query_params
@@ -3359,7 +3359,7 @@  discard block
 block discarded – undo
3359 3359
      */
3360 3360
     public function _create_model_query_info_carrier($query_params)
3361 3361
     {
3362
-        if (! is_array($query_params)) {
3362
+        if ( ! is_array($query_params)) {
3363 3363
             EE_Error::doing_it_wrong(
3364 3364
                 'EEM_Base::_create_model_query_info_carrier',
3365 3365
                 sprintf(
@@ -3392,7 +3392,7 @@  discard block
 block discarded – undo
3392 3392
             // only include if related to a cpt where no password has been set
3393 3393
             $query_params[0]['OR*nopassword'] = array(
3394 3394
                 $where_param_key_for_password => '',
3395
-                $where_param_key_for_password . '*' => array('IS_NULL')
3395
+                $where_param_key_for_password.'*' => array('IS_NULL')
3396 3396
             );
3397 3397
         }
3398 3398
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3445,7 +3445,7 @@  discard block
 block discarded – undo
3445 3445
         // set limit
3446 3446
         if (array_key_exists('limit', $query_params)) {
3447 3447
             if (is_array($query_params['limit'])) {
3448
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3448
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3449 3449
                     $e = sprintf(
3450 3450
                         __(
3451 3451
                             "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)",
@@ -3453,12 +3453,12 @@  discard block
 block discarded – undo
3453 3453
                         ),
3454 3454
                         http_build_query($query_params['limit'])
3455 3455
                     );
3456
-                    throw new EE_Error($e . "|" . $e);
3456
+                    throw new EE_Error($e."|".$e);
3457 3457
                 }
3458 3458
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3459
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3460
-            } elseif (! empty($query_params['limit'])) {
3461
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3459
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3460
+            } elseif ( ! empty($query_params['limit'])) {
3461
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3462 3462
             }
3463 3463
         }
3464 3464
         // set order by
@@ -3490,10 +3490,10 @@  discard block
 block discarded – undo
3490 3490
                 $order_array = array();
3491 3491
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3492 3492
                     $order = $this->_extract_order($order);
3493
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3493
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3494 3494
                 }
3495
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3496
-            } elseif (! empty($query_params['order_by'])) {
3495
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3496
+            } elseif ( ! empty($query_params['order_by'])) {
3497 3497
                 $this->_extract_related_model_info_from_query_param(
3498 3498
                     $query_params['order_by'],
3499 3499
                     $query_object,
@@ -3504,18 +3504,18 @@  discard block
 block discarded – undo
3504 3504
                     ? $this->_extract_order($query_params['order'])
3505 3505
                     : 'DESC';
3506 3506
                 $query_object->set_order_by_sql(
3507
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3507
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3508 3508
                 );
3509 3509
             }
3510 3510
         }
3511 3511
         // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3512
-        if (! array_key_exists('order_by', $query_params)
3512
+        if ( ! array_key_exists('order_by', $query_params)
3513 3513
             && array_key_exists('order', $query_params)
3514 3514
             && ! empty($query_params['order'])
3515 3515
         ) {
3516 3516
             $pk_field = $this->get_primary_key_field();
3517 3517
             $order = $this->_extract_order($query_params['order']);
3518
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3518
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3519 3519
         }
3520 3520
         // set group by
3521 3521
         if (array_key_exists('group_by', $query_params)) {
@@ -3525,10 +3525,10 @@  discard block
 block discarded – undo
3525 3525
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3526 3526
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3527 3527
                 }
3528
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3529
-            } elseif (! empty($query_params['group_by'])) {
3528
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3529
+            } elseif ( ! empty($query_params['group_by'])) {
3530 3530
                 $query_object->set_group_by_sql(
3531
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3531
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3532 3532
                 );
3533 3533
             }
3534 3534
         }
@@ -3538,7 +3538,7 @@  discard block
 block discarded – undo
3538 3538
         }
3539 3539
         // now, just verify they didn't pass anything wack
3540 3540
         foreach ($query_params as $query_key => $query_value) {
3541
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3541
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3542 3542
                 throw new EE_Error(
3543 3543
                     sprintf(
3544 3544
                         __(
@@ -3646,7 +3646,7 @@  discard block
 block discarded – undo
3646 3646
         $where_query_params = array()
3647 3647
     ) {
3648 3648
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3649
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3649
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3650 3650
             throw new EE_Error(sprintf(
3651 3651
                 __(
3652 3652
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3778,19 +3778,19 @@  discard block
 block discarded – undo
3778 3778
     ) {
3779 3779
         $null_friendly_where_conditions = array();
3780 3780
         $none_overridden = true;
3781
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3781
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3782 3782
         foreach ($default_where_conditions as $key => $val) {
3783
-            if (isset($provided_where_conditions[ $key ])) {
3783
+            if (isset($provided_where_conditions[$key])) {
3784 3784
                 $none_overridden = false;
3785 3785
             } else {
3786
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3786
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3787 3787
             }
3788 3788
         }
3789 3789
         if ($none_overridden && $default_where_conditions) {
3790 3790
             if ($model->has_primary_key_field()) {
3791
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3791
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3792 3792
                                                                                 . "."
3793
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3793
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3794 3794
             }/*else{
3795 3795
                 //@todo NO PK, use other defaults
3796 3796
             }*/
@@ -3896,7 +3896,7 @@  discard block
 block discarded – undo
3896 3896
             foreach ($tables as $table_obj) {
3897 3897
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3898 3898
                                        . $table_obj->get_fully_qualified_pk_column();
3899
-                if (! in_array($qualified_pk_column, $selects)) {
3899
+                if ( ! in_array($qualified_pk_column, $selects)) {
3900 3900
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3901 3901
                 }
3902 3902
             }
@@ -4045,9 +4045,9 @@  discard block
 block discarded – undo
4045 4045
         $query_parameter_type
4046 4046
     ) {
4047 4047
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4048
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4048
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4049 4049
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4050
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4050
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4051 4051
                 if ($possible_join_string === '') {
4052 4052
                     // nothing left to $query_param
4053 4053
                     // we should actually end in a field name, not a model like this!
@@ -4177,7 +4177,7 @@  discard block
 block discarded – undo
4177 4177
     {
4178 4178
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4179 4179
         if ($SQL) {
4180
-            return " WHERE " . $SQL;
4180
+            return " WHERE ".$SQL;
4181 4181
         }
4182 4182
         return '';
4183 4183
     }
@@ -4196,7 +4196,7 @@  discard block
 block discarded – undo
4196 4196
     {
4197 4197
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4198 4198
         if ($SQL) {
4199
-            return " HAVING " . $SQL;
4199
+            return " HAVING ".$SQL;
4200 4200
         }
4201 4201
         return '';
4202 4202
     }
@@ -4215,7 +4215,7 @@  discard block
 block discarded – undo
4215 4215
     {
4216 4216
         $where_clauses = array();
4217 4217
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4218
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4218
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4219 4219
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4220 4220
                 switch ($query_param) {
4221 4221
                     case 'not':
@@ -4249,7 +4249,7 @@  discard block
 block discarded – undo
4249 4249
             } else {
4250 4250
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4251 4251
                 // if it's not a normal field, maybe it's a custom selection?
4252
-                if (! $field_obj) {
4252
+                if ( ! $field_obj) {
4253 4253
                     if ($this->_custom_selections instanceof CustomSelects) {
4254 4254
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4255 4255
                     } else {
@@ -4260,7 +4260,7 @@  discard block
 block discarded – undo
4260 4260
                     }
4261 4261
                 }
4262 4262
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4263
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4263
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4264 4264
             }
4265 4265
         }
4266 4266
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4283,7 +4283,7 @@  discard block
 block discarded – undo
4283 4283
                 $field->get_model_name(),
4284 4284
                 $query_param
4285 4285
             );
4286
-            return $table_alias_prefix . $field->get_qualified_column();
4286
+            return $table_alias_prefix.$field->get_qualified_column();
4287 4287
         }
4288 4288
         if ($this->_custom_selections instanceof CustomSelects
4289 4289
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4342,7 +4342,7 @@  discard block
 block discarded – undo
4342 4342
     {
4343 4343
         if (is_array($op_and_value)) {
4344 4344
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4345
-            if (! $operator) {
4345
+            if ( ! $operator) {
4346 4346
                 $php_array_like_string = array();
4347 4347
                 foreach ($op_and_value as $key => $value) {
4348 4348
                     $php_array_like_string[] = "$key=>$value";
@@ -4364,14 +4364,14 @@  discard block
 block discarded – undo
4364 4364
         }
4365 4365
         // check to see if the value is actually another field
4366 4366
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4367
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4367
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4368 4368
         }
4369 4369
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4370 4370
             // in this case, the value should be an array, or at least a comma-separated list
4371 4371
             // it will need to handle a little differently
4372 4372
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4373 4373
             // note: $cleaned_value has already been run through $wpdb->prepare()
4374
-            return $operator . SP . $cleaned_value;
4374
+            return $operator.SP.$cleaned_value;
4375 4375
         }
4376 4376
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4377 4377
             // the value should be an array with count of two.
@@ -4387,7 +4387,7 @@  discard block
 block discarded – undo
4387 4387
                 );
4388 4388
             }
4389 4389
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4390
-            return $operator . SP . $cleaned_value;
4390
+            return $operator.SP.$cleaned_value;
4391 4391
         }
4392 4392
         if (in_array($operator, $this->valid_null_style_operators())) {
4393 4393
             if ($value !== null) {
@@ -4407,10 +4407,10 @@  discard block
 block discarded – undo
4407 4407
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4408 4408
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4409 4409
             // remove other junk. So just treat it as a string.
4410
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4410
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4411 4411
         }
4412
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4413
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4412
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4413
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4414 4414
         }
4415 4415
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4416 4416
             throw new EE_Error(
@@ -4424,7 +4424,7 @@  discard block
 block discarded – undo
4424 4424
                 )
4425 4425
             );
4426 4426
         }
4427
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4427
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4428 4428
             throw new EE_Error(
4429 4429
                 sprintf(
4430 4430
                     __(
@@ -4464,7 +4464,7 @@  discard block
 block discarded – undo
4464 4464
         foreach ($values as $value) {
4465 4465
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4466 4466
         }
4467
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4467
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4468 4468
     }
4469 4469
 
4470 4470
 
@@ -4505,7 +4505,7 @@  discard block
 block discarded – undo
4505 4505
                                 . $main_table->get_table_name()
4506 4506
                                 . " WHERE FALSE";
4507 4507
         }
4508
-        return "(" . implode(",", $cleaned_values) . ")";
4508
+        return "(".implode(",", $cleaned_values).")";
4509 4509
     }
4510 4510
 
4511 4511
 
@@ -4526,7 +4526,7 @@  discard block
 block discarded – undo
4526 4526
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4527 4527
             );
4528 4528
         } //$field_obj should really just be a data type
4529
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4529
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4530 4530
             throw new EE_Error(
4531 4531
                 sprintf(
4532 4532
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4559,14 +4559,14 @@  discard block
 block discarded – undo
4559 4559
             ), $query_param_name));
4560 4560
         }
4561 4561
         $number_of_parts = count($query_param_parts);
4562
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4562
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4563 4563
         if ($number_of_parts === 1) {
4564 4564
             $field_name = $last_query_param_part;
4565 4565
             $model_obj = $this;
4566 4566
         } else {// $number_of_parts >= 2
4567 4567
             // the last part is the column name, and there are only 2parts. therefore...
4568 4568
             $field_name = $last_query_param_part;
4569
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4569
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4570 4570
         }
4571 4571
         try {
4572 4572
             return $model_obj->field_settings_for($field_name);
@@ -4588,7 +4588,7 @@  discard block
 block discarded – undo
4588 4588
     public function _get_qualified_column_for_field($field_name)
4589 4589
     {
4590 4590
         $all_fields = $this->field_settings();
4591
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4591
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4592 4592
         if ($field) {
4593 4593
             return $field->get_qualified_column();
4594 4594
         }
@@ -4659,10 +4659,10 @@  discard block
 block discarded – undo
4659 4659
      */
4660 4660
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4661 4661
     {
4662
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4662
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4663 4663
         $qualified_columns = array();
4664 4664
         foreach ($this->field_settings() as $field_name => $field) {
4665
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4665
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4666 4666
         }
4667 4667
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4668 4668
     }
@@ -4686,11 +4686,11 @@  discard block
 block discarded – undo
4686 4686
             if ($table_obj instanceof EE_Primary_Table) {
4687 4687
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4688 4688
                     ? $table_obj->get_select_join_limit($limit)
4689
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4689
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4690 4690
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4691 4691
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4692 4692
                     ? $table_obj->get_select_join_limit_join($limit)
4693
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4693
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4694 4694
             }
4695 4695
         }
4696 4696
         return $SQL;
@@ -4762,7 +4762,7 @@  discard block
 block discarded – undo
4762 4762
         foreach ($this->field_settings() as $field_obj) {
4763 4763
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4764 4764
             /** @var $field_obj EE_Model_Field_Base */
4765
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4765
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4766 4766
         }
4767 4767
         return $data_types;
4768 4768
     }
@@ -4778,14 +4778,14 @@  discard block
 block discarded – undo
4778 4778
      */
4779 4779
     public function get_related_model_obj($model_name)
4780 4780
     {
4781
-        $model_classname = "EEM_" . $model_name;
4782
-        if (! class_exists($model_classname)) {
4781
+        $model_classname = "EEM_".$model_name;
4782
+        if ( ! class_exists($model_classname)) {
4783 4783
             throw new EE_Error(sprintf(__(
4784 4784
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4785 4785
                 'event_espresso'
4786 4786
             ), $model_name, $model_classname));
4787 4787
         }
4788
-        return call_user_func($model_classname . "::instance");
4788
+        return call_user_func($model_classname."::instance");
4789 4789
     }
4790 4790
 
4791 4791
 
@@ -4814,7 +4814,7 @@  discard block
 block discarded – undo
4814 4814
         $belongs_to_relations = array();
4815 4815
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4816 4816
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4817
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4817
+                $belongs_to_relations[$model_name] = $relation_obj;
4818 4818
             }
4819 4819
         }
4820 4820
         return $belongs_to_relations;
@@ -4832,7 +4832,7 @@  discard block
 block discarded – undo
4832 4832
     public function related_settings_for($relation_name)
4833 4833
     {
4834 4834
         $relatedModels = $this->relation_settings();
4835
-        if (! array_key_exists($relation_name, $relatedModels)) {
4835
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4836 4836
             throw new EE_Error(
4837 4837
                 sprintf(
4838 4838
                     __(
@@ -4845,7 +4845,7 @@  discard block
 block discarded – undo
4845 4845
                 )
4846 4846
             );
4847 4847
         }
4848
-        return $relatedModels[ $relation_name ];
4848
+        return $relatedModels[$relation_name];
4849 4849
     }
4850 4850
 
4851 4851
 
@@ -4862,14 +4862,14 @@  discard block
 block discarded – undo
4862 4862
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4863 4863
     {
4864 4864
         $fieldSettings = $this->field_settings($include_db_only_fields);
4865
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4865
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4866 4866
             throw new EE_Error(sprintf(
4867 4867
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4868 4868
                 $fieldName,
4869 4869
                 get_class($this)
4870 4870
             ));
4871 4871
         }
4872
-        return $fieldSettings[ $fieldName ];
4872
+        return $fieldSettings[$fieldName];
4873 4873
     }
4874 4874
 
4875 4875
 
@@ -4883,7 +4883,7 @@  discard block
 block discarded – undo
4883 4883
     public function has_field($fieldName)
4884 4884
     {
4885 4885
         $fieldSettings = $this->field_settings(true);
4886
-        if (isset($fieldSettings[ $fieldName ])) {
4886
+        if (isset($fieldSettings[$fieldName])) {
4887 4887
             return true;
4888 4888
         }
4889 4889
         return false;
@@ -4900,7 +4900,7 @@  discard block
 block discarded – undo
4900 4900
     public function has_relation($relation_name)
4901 4901
     {
4902 4902
         $relations = $this->relation_settings();
4903
-        if (isset($relations[ $relation_name ])) {
4903
+        if (isset($relations[$relation_name])) {
4904 4904
             return true;
4905 4905
         }
4906 4906
         return false;
@@ -4938,7 +4938,7 @@  discard block
 block discarded – undo
4938 4938
                     break;
4939 4939
                 }
4940 4940
             }
4941
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4941
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4942 4942
                 throw new EE_Error(sprintf(
4943 4943
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
4944 4944
                     get_class($this)
@@ -4999,23 +4999,23 @@  discard block
 block discarded – undo
4999 4999
      */
5000 5000
     public function get_foreign_key_to($model_name)
5001 5001
     {
5002
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5002
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5003 5003
             foreach ($this->field_settings() as $field) {
5004 5004
                 if ($field instanceof EE_Foreign_Key_Field_Base
5005 5005
                     && in_array($model_name, $field->get_model_names_pointed_to())
5006 5006
                 ) {
5007
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5007
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5008 5008
                     break;
5009 5009
                 }
5010 5010
             }
5011
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5011
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5012 5012
                 throw new EE_Error(sprintf(__(
5013 5013
                     "There is no foreign key field pointing to model %s on model %s",
5014 5014
                     'event_espresso'
5015 5015
                 ), $model_name, get_class($this)));
5016 5016
             }
5017 5017
         }
5018
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5018
+        return $this->_cache_foreign_key_to_fields[$model_name];
5019 5019
     }
5020 5020
 
5021 5021
 
@@ -5031,7 +5031,7 @@  discard block
 block discarded – undo
5031 5031
     public function get_table_for_alias($table_alias)
5032 5032
     {
5033 5033
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5034
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5034
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5035 5035
     }
5036 5036
 
5037 5037
 
@@ -5050,7 +5050,7 @@  discard block
 block discarded – undo
5050 5050
                 $this->_cached_fields = array();
5051 5051
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5052 5052
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5053
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5053
+                        $this->_cached_fields[$field_name] = $field_obj;
5054 5054
                     }
5055 5055
                 }
5056 5056
             }
@@ -5061,8 +5061,8 @@  discard block
 block discarded – undo
5061 5061
             foreach ($this->_fields as $fields_corresponding_to_table) {
5062 5062
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5063 5063
                     /** @var $field_obj EE_Model_Field_Base */
5064
-                    if (! $field_obj->is_db_only_field()) {
5065
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5064
+                    if ( ! $field_obj->is_db_only_field()) {
5065
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5066 5066
                     }
5067 5067
                 }
5068 5068
             }
@@ -5103,12 +5103,12 @@  discard block
 block discarded – undo
5103 5103
                     $primary_key_field->get_qualified_column(),
5104 5104
                     $primary_key_field->get_table_column()
5105 5105
                 );
5106
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5106
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5107 5107
                     continue;
5108 5108
                 }
5109 5109
             }
5110 5110
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5111
-            if (! $classInstance) {
5111
+            if ( ! $classInstance) {
5112 5112
                 throw new EE_Error(
5113 5113
                     sprintf(
5114 5114
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5121,7 +5121,7 @@  discard block
 block discarded – undo
5121 5121
             $classInstance->set_timezone($this->_timezone);
5122 5122
             // make sure if there is any timezone setting present that we set the timezone for the object
5123 5123
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5124
-            $array_of_objects[ $key ] = $classInstance;
5124
+            $array_of_objects[$key] = $classInstance;
5125 5125
             // also, for all the relations of type BelongsTo, see if we can cache
5126 5126
             // those related models
5127 5127
             // (we could do this for other relations too, but if there are conditions
@@ -5165,9 +5165,9 @@  discard block
 block discarded – undo
5165 5165
         $results = array();
5166 5166
         if ($this->_custom_selections instanceof CustomSelects) {
5167 5167
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5168
-                if (isset($db_results_row[ $alias ])) {
5169
-                    $results[ $alias ] = $this->convertValueToDataType(
5170
-                        $db_results_row[ $alias ],
5168
+                if (isset($db_results_row[$alias])) {
5169
+                    $results[$alias] = $this->convertValueToDataType(
5170
+                        $db_results_row[$alias],
5171 5171
                         $this->_custom_selections->getDataTypeForAlias($alias)
5172 5172
                     );
5173 5173
                 }
@@ -5209,7 +5209,7 @@  discard block
 block discarded – undo
5209 5209
         $this_model_fields_and_values = array();
5210 5210
         // setup the row using default values;
5211 5211
         foreach ($this->field_settings() as $field_name => $field_obj) {
5212
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5212
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5213 5213
         }
5214 5214
         $className = $this->_get_class_name();
5215 5215
         $classInstance = EE_Registry::instance()
@@ -5227,20 +5227,20 @@  discard block
 block discarded – undo
5227 5227
      */
5228 5228
     public function instantiate_class_from_array_or_object($cols_n_values)
5229 5229
     {
5230
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5230
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5231 5231
             $cols_n_values = get_object_vars($cols_n_values);
5232 5232
         }
5233 5233
         $primary_key = null;
5234 5234
         // make sure the array only has keys that are fields/columns on this model
5235 5235
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5236
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5237
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5236
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5237
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5238 5238
         }
5239 5239
         $className = $this->_get_class_name();
5240 5240
         // check we actually found results that we can use to build our model object
5241 5241
         // if not, return null
5242 5242
         if ($this->has_primary_key_field()) {
5243
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5243
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5244 5244
                 return null;
5245 5245
             }
5246 5246
         } elseif ($this->unique_indexes()) {
@@ -5252,7 +5252,7 @@  discard block
 block discarded – undo
5252 5252
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5253 5253
         if ($primary_key) {
5254 5254
             $classInstance = $this->get_from_entity_map($primary_key);
5255
-            if (! $classInstance) {
5255
+            if ( ! $classInstance) {
5256 5256
                 $classInstance = EE_Registry::instance()
5257 5257
                                             ->load_class(
5258 5258
                                                 $className,
@@ -5285,8 +5285,8 @@  discard block
 block discarded – undo
5285 5285
      */
5286 5286
     public function get_from_entity_map($id)
5287 5287
     {
5288
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5289
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5288
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5289
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5290 5290
     }
5291 5291
 
5292 5292
 
@@ -5309,7 +5309,7 @@  discard block
 block discarded – undo
5309 5309
     public function add_to_entity_map(EE_Base_Class $object)
5310 5310
     {
5311 5311
         $className = $this->_get_class_name();
5312
-        if (! $object instanceof $className) {
5312
+        if ( ! $object instanceof $className) {
5313 5313
             throw new EE_Error(sprintf(
5314 5314
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5315 5315
                 is_object($object) ? get_class($object) : $object,
@@ -5317,7 +5317,7 @@  discard block
 block discarded – undo
5317 5317
             ));
5318 5318
         }
5319 5319
         /** @var $object EE_Base_Class */
5320
-        if (! $object->ID()) {
5320
+        if ( ! $object->ID()) {
5321 5321
             throw new EE_Error(sprintf(__(
5322 5322
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5323 5323
                 "event_espresso"
@@ -5328,7 +5328,7 @@  discard block
 block discarded – undo
5328 5328
         if ($classInstance) {
5329 5329
             return $classInstance;
5330 5330
         }
5331
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5331
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5332 5332
         return $object;
5333 5333
     }
5334 5334
 
@@ -5344,11 +5344,11 @@  discard block
 block discarded – undo
5344 5344
     public function clear_entity_map($id = null)
5345 5345
     {
5346 5346
         if (empty($id)) {
5347
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5347
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5348 5348
             return true;
5349 5349
         }
5350
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5351
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5350
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5351
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5352 5352
             return true;
5353 5353
         }
5354 5354
         return false;
@@ -5391,17 +5391,17 @@  discard block
 block discarded – undo
5391 5391
             // there is a primary key on this table and its not set. Use defaults for all its columns
5392 5392
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5393 5393
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5394
-                    if (! $field_obj->is_db_only_field()) {
5394
+                    if ( ! $field_obj->is_db_only_field()) {
5395 5395
                         // prepare field as if its coming from db
5396 5396
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5397
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5397
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5398 5398
                     }
5399 5399
                 }
5400 5400
             } else {
5401 5401
                 // the table's rows existed. Use their values
5402 5402
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5403
-                    if (! $field_obj->is_db_only_field()) {
5404
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5403
+                    if ( ! $field_obj->is_db_only_field()) {
5404
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5405 5405
                             $cols_n_values,
5406 5406
                             $field_obj->get_qualified_column(),
5407 5407
                             $field_obj->get_table_column()
@@ -5427,17 +5427,17 @@  discard block
 block discarded – undo
5427 5427
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5428 5428
         // does the field on the model relate to this column retrieved from the db?
5429 5429
         // or is it a db-only field? (not relating to the model)
5430
-        if (isset($cols_n_values[ $qualified_column ])) {
5431
-            $value = $cols_n_values[ $qualified_column ];
5432
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5433
-            $value = $cols_n_values[ $regular_column ];
5434
-        } elseif (! empty($this->foreign_key_aliases)) {
5430
+        if (isset($cols_n_values[$qualified_column])) {
5431
+            $value = $cols_n_values[$qualified_column];
5432
+        } elseif (isset($cols_n_values[$regular_column])) {
5433
+            $value = $cols_n_values[$regular_column];
5434
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5435 5435
             // no PK?  ok check if there is a foreign key alias set for this table
5436 5436
             // then check if that alias exists in the incoming data
5437 5437
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5438 5438
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5439
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5440
-                    $value = $cols_n_values[ $FK_alias ];
5439
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5440
+                    $value = $cols_n_values[$FK_alias];
5441 5441
                     break;
5442 5442
                 }
5443 5443
             }
@@ -5473,7 +5473,7 @@  discard block
 block discarded – undo
5473 5473
                     $obj_in_map->clear_cache($relation_name, null, true);
5474 5474
                 }
5475 5475
             }
5476
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5476
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5477 5477
             return $obj_in_map;
5478 5478
         }
5479 5479
         return $this->get_one_by_ID($id);
@@ -5526,7 +5526,7 @@  discard block
 block discarded – undo
5526 5526
      */
5527 5527
     private function _get_class_name()
5528 5528
     {
5529
-        return "EE_" . $this->get_this_model_name();
5529
+        return "EE_".$this->get_this_model_name();
5530 5530
     }
5531 5531
 
5532 5532
 
@@ -5574,7 +5574,7 @@  discard block
 block discarded – undo
5574 5574
     {
5575 5575
         $className = get_class($this);
5576 5576
         $tagName = "FHEE__{$className}__{$methodName}";
5577
-        if (! has_filter($tagName)) {
5577
+        if ( ! has_filter($tagName)) {
5578 5578
             throw new EE_Error(
5579 5579
                 sprintf(
5580 5580
                     __(
@@ -5745,7 +5745,7 @@  discard block
 block discarded – undo
5745 5745
         $unique_indexes = array();
5746 5746
         foreach ($this->_indexes as $name => $index) {
5747 5747
             if ($index instanceof EE_Unique_Index) {
5748
-                $unique_indexes [ $name ] = $index;
5748
+                $unique_indexes [$name] = $index;
5749 5749
             }
5750 5750
         }
5751 5751
         return $unique_indexes;
@@ -5812,7 +5812,7 @@  discard block
 block discarded – undo
5812 5812
         $key_vals_in_combined_pk = array();
5813 5813
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5814 5814
         foreach ($key_fields as $key_field_name => $field_obj) {
5815
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5815
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5816 5816
                 return null;
5817 5817
             }
5818 5818
         }
@@ -5833,7 +5833,7 @@  discard block
 block discarded – undo
5833 5833
     {
5834 5834
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5835 5835
         foreach ($keys_it_should_have as $key) {
5836
-            if (! isset($key_vals[ $key ])) {
5836
+            if ( ! isset($key_vals[$key])) {
5837 5837
                 return false;
5838 5838
             }
5839 5839
         }
@@ -5866,8 +5866,8 @@  discard block
 block discarded – undo
5866 5866
         }
5867 5867
         // even copies obviously won't have the same ID, so remove the primary key
5868 5868
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5869
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5870
-            unset($attributes_array[ $this->primary_key_name() ]);
5869
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5870
+            unset($attributes_array[$this->primary_key_name()]);
5871 5871
         }
5872 5872
         if (isset($query_params[0])) {
5873 5873
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5889,7 +5889,7 @@  discard block
 block discarded – undo
5889 5889
      */
5890 5890
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5891 5891
     {
5892
-        if (! is_array($query_params)) {
5892
+        if ( ! is_array($query_params)) {
5893 5893
             EE_Error::doing_it_wrong(
5894 5894
                 'EEM_Base::get_one_copy',
5895 5895
                 sprintf(
@@ -5939,7 +5939,7 @@  discard block
 block discarded – undo
5939 5939
      */
5940 5940
     private function _prepare_operator_for_sql($operator_supplied)
5941 5941
     {
5942
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5942
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5943 5943
             : null;
5944 5944
         if ($sql_operator) {
5945 5945
             return $sql_operator;
@@ -6030,7 +6030,7 @@  discard block
 block discarded – undo
6030 6030
         $objs = $this->get_all($query_params);
6031 6031
         $names = array();
6032 6032
         foreach ($objs as $obj) {
6033
-            $names[ $obj->ID() ] = $obj->name();
6033
+            $names[$obj->ID()] = $obj->name();
6034 6034
         }
6035 6035
         return $names;
6036 6036
     }
@@ -6051,7 +6051,7 @@  discard block
 block discarded – undo
6051 6051
      */
6052 6052
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6053 6053
     {
6054
-        if (! $this->has_primary_key_field()) {
6054
+        if ( ! $this->has_primary_key_field()) {
6055 6055
             if (WP_DEBUG) {
6056 6056
                 EE_Error::add_error(
6057 6057
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6064,7 +6064,7 @@  discard block
 block discarded – undo
6064 6064
         $IDs = array();
6065 6065
         foreach ($model_objects as $model_object) {
6066 6066
             $id = $model_object->ID();
6067
-            if (! $id) {
6067
+            if ( ! $id) {
6068 6068
                 if ($filter_out_empty_ids) {
6069 6069
                     continue;
6070 6070
                 }
@@ -6114,22 +6114,22 @@  discard block
 block discarded – undo
6114 6114
     {
6115 6115
         EEM_Base::verify_is_valid_cap_context($context);
6116 6116
         // check if we ought to run the restriction generator first
6117
-        if (isset($this->_cap_restriction_generators[ $context ])
6118
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6119
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6117
+        if (isset($this->_cap_restriction_generators[$context])
6118
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6119
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6120 6120
         ) {
6121
-            $this->_cap_restrictions[ $context ] = array_merge(
6122
-                $this->_cap_restrictions[ $context ],
6123
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6121
+            $this->_cap_restrictions[$context] = array_merge(
6122
+                $this->_cap_restrictions[$context],
6123
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6124 6124
             );
6125 6125
         }
6126 6126
         // and make sure we've finalized the construction of each restriction
6127
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6127
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6128 6128
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6129 6129
                 $where_conditions_obj->_finalize_construct($this);
6130 6130
             }
6131 6131
         }
6132
-        return $this->_cap_restrictions[ $context ];
6132
+        return $this->_cap_restrictions[$context];
6133 6133
     }
6134 6134
 
6135 6135
 
@@ -6159,10 +6159,10 @@  discard block
 block discarded – undo
6159 6159
         $missing_caps = array();
6160 6160
         $cap_restrictions = $this->cap_restrictions($context);
6161 6161
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6162
-            if (! EE_Capabilities::instance()
6163
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6162
+            if ( ! EE_Capabilities::instance()
6163
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6164 6164
             ) {
6165
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6165
+                $missing_caps[$cap] = $restriction_if_no_cap;
6166 6166
             }
6167 6167
         }
6168 6168
         return $missing_caps;
@@ -6197,8 +6197,8 @@  discard block
 block discarded – undo
6197 6197
     public function cap_action_for_context($context)
6198 6198
     {
6199 6199
         $mapping = $this->cap_contexts_to_cap_action_map();
6200
-        if (isset($mapping[ $context ])) {
6201
-            return $mapping[ $context ];
6200
+        if (isset($mapping[$context])) {
6201
+            return $mapping[$context];
6202 6202
         }
6203 6203
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6204 6204
             return $action;
@@ -6315,7 +6315,7 @@  discard block
 block discarded – undo
6315 6315
     {
6316 6316
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6317 6317
             if ($query_param_key === $logic_query_param_key
6318
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6318
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6319 6319
             ) {
6320 6320
                 return true;
6321 6321
             }
@@ -6368,7 +6368,7 @@  discard block
 block discarded – undo
6368 6368
         if ($password_field instanceof EE_Password_Field) {
6369 6369
             $field_names = $password_field->protectedFields();
6370 6370
             foreach ($field_names as $field_name) {
6371
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6371
+                $fields[$field_name] = $this->field_settings_for($field_name);
6372 6372
             }
6373 6373
         }
6374 6374
         return $fields;
@@ -6393,7 +6393,7 @@  discard block
 block discarded – undo
6393 6393
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6394 6394
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6395 6395
         }
6396
-        if (!is_array($model_obj_or_fields_n_values)) {
6396
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6397 6397
             throw new UnexpectedEntityException(
6398 6398
                 $model_obj_or_fields_n_values,
6399 6399
                 'EE_Base_Class',
@@ -6468,7 +6468,7 @@  discard block
 block discarded – undo
6468 6468
                 )
6469 6469
             );
6470 6470
         }
6471
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6471
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6472 6472
     }
6473 6473
 
6474 6474
     /**
Please login to merge, or discard this patch.
core/db_models/fields/EE_Email_Field.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -15,38 +15,38 @@
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * @param string $table_column
20
-     * @param string $nice_name
21
-     * @param bool   $nullable
22
-     * @param null   $default_value
23
-     * @throws InvalidArgumentException
24
-     */
25
-    public function __construct($table_column, $nice_name, $nullable, $default_value = null)
26
-    {
27
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
28
-        $this->setSchemaFormat('email');
29
-    }
18
+	/**
19
+	 * @param string $table_column
20
+	 * @param string $nice_name
21
+	 * @param bool   $nullable
22
+	 * @param null   $default_value
23
+	 * @throws InvalidArgumentException
24
+	 */
25
+	public function __construct($table_column, $nice_name, $nullable, $default_value = null)
26
+	{
27
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
28
+		$this->setSchemaFormat('email');
29
+	}
30 30
 
31 31
 
32 32
 
33
-    /**
34
-     * In form inputs, we should have called htmlentities and addslashes() on form inputs,
35
-     * so we need to undo that on setting of these fields
36
-     *
37
-     * @param string $email_address
38
-     * @return string
39
-     * @throws InvalidArgumentException
40
-     * @throws InvalidInterfaceException
41
-     * @throws InvalidDataTypeException
42
-     */
43
-    public function prepare_for_set($email_address)
44
-    {
45
-        try {
46
-            $email_address_obj = EmailAddressFactory::create($email_address);
47
-            return $email_address_obj instanceof EmailAddress ? $email_address_obj->get() : '';
48
-        } catch (EmailValidationException $e) {
49
-            return '';
50
-        }
51
-    }
33
+	/**
34
+	 * In form inputs, we should have called htmlentities and addslashes() on form inputs,
35
+	 * so we need to undo that on setting of these fields
36
+	 *
37
+	 * @param string $email_address
38
+	 * @return string
39
+	 * @throws InvalidArgumentException
40
+	 * @throws InvalidInterfaceException
41
+	 * @throws InvalidDataTypeException
42
+	 */
43
+	public function prepare_for_set($email_address)
44
+	{
45
+		try {
46
+			$email_address_obj = EmailAddressFactory::create($email_address);
47
+			return $email_address_obj instanceof EmailAddress ? $email_address_obj->get() : '';
48
+		} catch (EmailValidationException $e) {
49
+			return '';
50
+		}
51
+	}
52 52
 }
Please login to merge, or discard this patch.
core/db_models/EEM_WP_User.model.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -112,10 +112,10 @@
 block discarded – undo
112 112
         ];
113 113
         $this->_wp_core_model = true;
114 114
         $this->_caps_slug = 'users';
115
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
116
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
115
+        $this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read] = 'list';
116
+        $this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read_admin] = 'list';
117 117
         foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
118
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
118
+            $this->_cap_restriction_generators[$context] = new EE_Restriction_Generator_WP_User();
119 119
         }
120 120
         // @todo: account for create_users controls whether they can create users at all
121 121
         parent::__construct($timezone);
Please login to merge, or discard this patch.
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -13,133 +13,133 @@
 block discarded – undo
13 13
 class EEM_WP_User extends EEM_Base
14 14
 {
15 15
 
16
-    /**
17
-     * private instance of the EEM_WP_User object
18
-     *
19
-     * @type EEM_WP_User
20
-     */
21
-    protected static $_instance;
16
+	/**
17
+	 * private instance of the EEM_WP_User object
18
+	 *
19
+	 * @type EEM_WP_User
20
+	 */
21
+	protected static $_instance;
22 22
 
23 23
 
24
-    /**
25
-     *    constructor
26
-     *
27
-     * @param null              $timezone
28
-     * @param ModelFieldFactory $model_field_factory
29
-     * @throws EE_Error
30
-     * @throws InvalidArgumentException
31
-     */
32
-    protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
33
-    {
34
-        $this->singular_item = esc_html__('WP_User', 'event_espresso');
35
-        $this->plural_item = esc_html__('WP_Users', 'event_espresso');
36
-        global $wpdb;
37
-        $this->_tables = array(
38
-            'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
39
-        );
40
-        $this->_fields = array(
41
-            'WP_User' => array(
42
-                'ID'                  => $model_field_factory->createPrimaryKeyIntField(
43
-                    'ID',
44
-                    esc_html__('WP_User ID', 'event_espresso')
45
-                ),
46
-                'user_login'          => $model_field_factory->createPlainTextField(
47
-                    'user_login',
48
-                    esc_html__('User Login', 'event_espresso'),
49
-                    false
50
-                ),
51
-                'user_pass'           => $model_field_factory->createPlainTextField(
52
-                    'user_pass',
53
-                    esc_html__('User Password', 'event_espresso'),
54
-                    false
55
-                ),
56
-                'user_nicename'       => $model_field_factory->createPlainTextField(
57
-                    'user_nicename',
58
-                    esc_html__(' User Nice Name', 'event_espresso'),
59
-                    false
60
-                ),
61
-                'user_email'          => $model_field_factory->createEmailField(
62
-                    'user_email',
63
-                    esc_html__('User Email', 'event_espresso'),
64
-                    false,
65
-                    null
66
-                ),
67
-                'user_registered'     => $model_field_factory->createDatetimeField(
68
-                    'user_registered',
69
-                    esc_html__('Date User Registered', 'event_espresso'),
70
-                    $timezone
71
-                ),
72
-                'user_activation_key' => $model_field_factory->createPlainTextField(
73
-                    'user_activation_key',
74
-                    esc_html__('User Activation Key', 'event_espresso'),
75
-                    false
76
-                ),
77
-                'user_status'         => $model_field_factory->createIntegerField(
78
-                    'user_status',
79
-                    esc_html__('User Status', 'event_espresso')
80
-                ),
81
-                'display_name'        => $model_field_factory->createPlainTextField(
82
-                    'display_name',
83
-                    esc_html__('Display Name', 'event_espresso'),
84
-                    false
85
-                ),
86
-            ),
87
-        );
88
-        $this->_model_relations = array(
89
-            'Attendee'       => new EE_Has_Many_Relation(),
90
-            // all models are related to the change log
91
-            // 'Change_Log'     => new EE_Has_Many_Relation(),
92
-            'Event'          => new EE_Has_Many_Relation(),
93
-            'Message'        => new EE_Has_Many_Relation(),
94
-            'Payment_Method' => new EE_Has_Many_Relation(),
95
-            'Price'          => new EE_Has_Many_Relation(),
96
-            'Price_Type'     => new EE_Has_Many_Relation(),
97
-            'Question'       => new EE_Has_Many_Relation(),
98
-            'Question_Group' => new EE_Has_Many_Relation(),
99
-            'Ticket'         => new EE_Has_Many_Relation(),
100
-            'Venue'          => new EE_Has_Many_Relation(),
101
-        );
102
-        $this->foreign_key_aliases = [
103
-            'Event.EVT_wp_user'          => 'WP_User.ID',
104
-            'Payment_Method.PMD_wp_user' => 'WP_User.ID',
105
-            'Price.PRC_wp_user'          => 'WP_User.ID',
106
-            'Price_Type.PRT_wp_user'     => 'WP_User.ID',
107
-            'Question.QST_wp_user'       => 'WP_User.ID',
108
-            'Question_Group.QSG_wp_user' => 'WP_User.ID',
109
-            'Ticket.VNU_wp_user'         => 'WP_User.ID',
110
-            'Venue.TKT_wp_user'          => 'WP_User.ID',
111
-        ];
112
-        $this->_wp_core_model = true;
113
-        $this->_caps_slug = 'users';
114
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
115
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
116
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
117
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
118
-        }
119
-        // @todo: account for create_users controls whether they can create users at all
120
-        parent::__construct($timezone);
121
-    }
24
+	/**
25
+	 *    constructor
26
+	 *
27
+	 * @param null              $timezone
28
+	 * @param ModelFieldFactory $model_field_factory
29
+	 * @throws EE_Error
30
+	 * @throws InvalidArgumentException
31
+	 */
32
+	protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
33
+	{
34
+		$this->singular_item = esc_html__('WP_User', 'event_espresso');
35
+		$this->plural_item = esc_html__('WP_Users', 'event_espresso');
36
+		global $wpdb;
37
+		$this->_tables = array(
38
+			'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
39
+		);
40
+		$this->_fields = array(
41
+			'WP_User' => array(
42
+				'ID'                  => $model_field_factory->createPrimaryKeyIntField(
43
+					'ID',
44
+					esc_html__('WP_User ID', 'event_espresso')
45
+				),
46
+				'user_login'          => $model_field_factory->createPlainTextField(
47
+					'user_login',
48
+					esc_html__('User Login', 'event_espresso'),
49
+					false
50
+				),
51
+				'user_pass'           => $model_field_factory->createPlainTextField(
52
+					'user_pass',
53
+					esc_html__('User Password', 'event_espresso'),
54
+					false
55
+				),
56
+				'user_nicename'       => $model_field_factory->createPlainTextField(
57
+					'user_nicename',
58
+					esc_html__(' User Nice Name', 'event_espresso'),
59
+					false
60
+				),
61
+				'user_email'          => $model_field_factory->createEmailField(
62
+					'user_email',
63
+					esc_html__('User Email', 'event_espresso'),
64
+					false,
65
+					null
66
+				),
67
+				'user_registered'     => $model_field_factory->createDatetimeField(
68
+					'user_registered',
69
+					esc_html__('Date User Registered', 'event_espresso'),
70
+					$timezone
71
+				),
72
+				'user_activation_key' => $model_field_factory->createPlainTextField(
73
+					'user_activation_key',
74
+					esc_html__('User Activation Key', 'event_espresso'),
75
+					false
76
+				),
77
+				'user_status'         => $model_field_factory->createIntegerField(
78
+					'user_status',
79
+					esc_html__('User Status', 'event_espresso')
80
+				),
81
+				'display_name'        => $model_field_factory->createPlainTextField(
82
+					'display_name',
83
+					esc_html__('Display Name', 'event_espresso'),
84
+					false
85
+				),
86
+			),
87
+		);
88
+		$this->_model_relations = array(
89
+			'Attendee'       => new EE_Has_Many_Relation(),
90
+			// all models are related to the change log
91
+			// 'Change_Log'     => new EE_Has_Many_Relation(),
92
+			'Event'          => new EE_Has_Many_Relation(),
93
+			'Message'        => new EE_Has_Many_Relation(),
94
+			'Payment_Method' => new EE_Has_Many_Relation(),
95
+			'Price'          => new EE_Has_Many_Relation(),
96
+			'Price_Type'     => new EE_Has_Many_Relation(),
97
+			'Question'       => new EE_Has_Many_Relation(),
98
+			'Question_Group' => new EE_Has_Many_Relation(),
99
+			'Ticket'         => new EE_Has_Many_Relation(),
100
+			'Venue'          => new EE_Has_Many_Relation(),
101
+		);
102
+		$this->foreign_key_aliases = [
103
+			'Event.EVT_wp_user'          => 'WP_User.ID',
104
+			'Payment_Method.PMD_wp_user' => 'WP_User.ID',
105
+			'Price.PRC_wp_user'          => 'WP_User.ID',
106
+			'Price_Type.PRT_wp_user'     => 'WP_User.ID',
107
+			'Question.QST_wp_user'       => 'WP_User.ID',
108
+			'Question_Group.QSG_wp_user' => 'WP_User.ID',
109
+			'Ticket.VNU_wp_user'         => 'WP_User.ID',
110
+			'Venue.TKT_wp_user'          => 'WP_User.ID',
111
+		];
112
+		$this->_wp_core_model = true;
113
+		$this->_caps_slug = 'users';
114
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
115
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
116
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
117
+			$this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
118
+		}
119
+		// @todo: account for create_users controls whether they can create users at all
120
+		parent::__construct($timezone);
121
+	}
122 122
 
123 123
 
124
-    /**
125
-     * We don't need a foreign key to the WP_User model, we just need its primary key
126
-     *
127
-     * @return string
128
-     * @throws EE_Error
129
-     */
130
-    public function wp_user_field_name()
131
-    {
132
-        return $this->primary_key_name();
133
-    }
124
+	/**
125
+	 * We don't need a foreign key to the WP_User model, we just need its primary key
126
+	 *
127
+	 * @return string
128
+	 * @throws EE_Error
129
+	 */
130
+	public function wp_user_field_name()
131
+	{
132
+		return $this->primary_key_name();
133
+	}
134 134
 
135 135
 
136
-    /**
137
-     * This WP_User model IS owned, even though it doesn't have a foreign key to itself
138
-     *
139
-     * @return boolean
140
-     */
141
-    public function is_owned()
142
-    {
143
-        return true;
144
-    }
136
+	/**
137
+	 * This WP_User model IS owned, even though it doesn't have a foreign key to itself
138
+	 *
139
+	 * @return boolean
140
+	 */
141
+	public function is_owned()
142
+	{
143
+		return true;
144
+	}
145 145
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Payment_Method.model.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -287,9 +287,9 @@  discard block
 block discarded – undo
287 287
     /**
288 288
      * Overrides parent ot also check by the slug
289 289
      *
290
-     * @param string|int|EE_Payment_Method $base_class_obj_or_id
290
+     * @param EE_Payment_Method $base_class_obj_or_id
291 291
      * @param boolean                      $ensure_is_in_db
292
-     * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|int|string
292
+     * @return EE_Base_Class|null
293 293
      * @throws EE_Error
294 294
      * @see EEM_Base::ensure_is_obj()
295 295
      */
@@ -451,9 +451,9 @@  discard block
 block discarded – undo
451 451
      * Note: if an offline payment method was selected on the related transaction then this will have no payment
452 452
      * methods returned. It will ONLY return a payment method for a PAYMENT recorded against the registration.
453 453
      *
454
-     * @param EE_Registration|int $registration_or_reg_id Either the EE_Registration object or the id for the
454
+     * @param EE_Registration $registration_or_reg_id Either the EE_Registration object or the id for the
455 455
      *                                                    registration.
456
-     * @return EE_Payment|null
456
+     * @return null|EE_Base_Class
457 457
      * @throws EE_Error
458 458
      */
459 459
     public function get_last_used_for_registration($registration_or_reg_id)
Please login to merge, or discard this patch.
Indentation   +451 added lines, -451 removed lines patch added patch discarded remove patch
@@ -17,455 +17,455 @@
 block discarded – undo
17 17
 class EEM_Payment_Method extends EEM_Base
18 18
 {
19 19
 
20
-    const scope_cart = 'CART';
21
-
22
-    const scope_admin = 'ADMIN';
23
-
24
-    const scope_api = 'API';
25
-
26
-    /**
27
-     * @type EEM_Payment_Method
28
-     */
29
-    protected static $_instance = null;
30
-
31
-
32
-    /**
33
-     * private constructor to prevent direct creation
34
-     *
35
-     * @param null $timezone
36
-     * @throws EE_Error
37
-     */
38
-    protected function __construct($timezone = null)
39
-    {
40
-        $this->singular_item = esc_html__('Payment Method', 'event_espresso');
41
-        $this->plural_item = esc_html__('Payment Methods', 'event_espresso');
42
-        $this->_tables = [
43
-            'Payment_Method' => new EE_Primary_Table('esp_payment_method', 'PMD_ID'),
44
-        ];
45
-        $this->_fields = [
46
-            'Payment_Method' => [
47
-                'PMD_ID'              => new EE_Primary_Key_Int_Field(
48
-                    'PMD_ID',
49
-                    esc_html__('ID', 'event_espresso')
50
-                ),
51
-                'PMD_type'            => new EE_Plain_Text_Field(
52
-                    'PMD_type',
53
-                    esc_html__('Payment Method Type', 'event_espresso'),
54
-                    false,
55
-                    'Admin_Only'
56
-                ),
57
-                'PMD_name'            => new EE_Plain_Text_Field(
58
-                    'PMD_name',
59
-                    esc_html__('Name', 'event_espresso'),
60
-                    false
61
-                ),
62
-                'PMD_desc'            => new EE_Post_Content_Field(
63
-                    'PMD_desc',
64
-                    esc_html__('Description', 'event_espresso'),
65
-                    false,
66
-                    ''
67
-                ),
68
-                'PMD_admin_name'      => new EE_Plain_Text_Field(
69
-                    'PMD_admin_name',
70
-                    esc_html__('Admin-Only Name', 'event_espresso'),
71
-                    true
72
-                ),
73
-                'PMD_admin_desc'      => new EE_Post_Content_Field(
74
-                    'PMD_admin_desc',
75
-                    esc_html__('Admin-Only Description', 'event_espresso'),
76
-                    true
77
-                ),
78
-                'PMD_slug'            => new EE_Slug_Field(
79
-                    'PMD_slug',
80
-                    esc_html__('Slug', 'event_espresso'),
81
-                    false
82
-                ),
83
-                'PMD_order'           => new EE_Integer_Field(
84
-                    'PMD_order',
85
-                    esc_html__('Order', 'event_espresso'),
86
-                    false,
87
-                    0
88
-                ),
89
-                'PMD_debug_mode'      => new EE_Boolean_Field(
90
-                    'PMD_debug_mode',
91
-                    esc_html__('Debug Mode On?', 'event_espresso'),
92
-                    false,
93
-                    false
94
-                ),
95
-                'PMD_wp_user'         => new EE_WP_User_Field(
96
-                    'PMD_wp_user',
97
-                    esc_html__('Payment Method Creator ID', 'event_espresso'),
98
-                    false
99
-                ),
100
-                'PMD_open_by_default' => new EE_Boolean_Field(
101
-                    'PMD_open_by_default',
102
-                    esc_html__('Open by Default?', 'event_espresso'),
103
-                    false,
104
-                    false
105
-                ),
106
-                'PMD_button_url'      => new EE_Plain_Text_Field(
107
-                    'PMD_button_url',
108
-                    esc_html__('Button URL', 'event_espresso'),
109
-                    true,
110
-                    ''
111
-                ),
112
-                'PMD_scope'           => new EE_Serialized_Text_Field(
113
-                    'PMD_scope',
114
-                    esc_html__('Usable From?', 'event_espresso'),
115
-                    false,
116
-                    []// possible values currently are 'CART','ADMIN','API'
117
-                ),
118
-            ],
119
-        ];
120
-        $this->_model_relations = [
121
-            'Payment'     => new EE_Has_Many_Relation(),
122
-            'Currency'    => new EE_HABTM_Relation('Currency_Payment_Method'),
123
-            'Transaction' => new EE_Has_Many_Relation(),
124
-            'WP_User'     => new EE_Belongs_To_Relation(),
125
-        ];
126
-        parent::__construct($timezone);
127
-    }
128
-
129
-
130
-    /**
131
-     * Gets one by the slug provided
132
-     *
133
-     * @param string $slug
134
-     * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|NULL
135
-     * @throws EE_Error
136
-     */
137
-    public function get_one_by_slug($slug)
138
-    {
139
-        return $this->get_one([['PMD_slug' => $slug]]);
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()
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 an 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($scope)
171
-    {
172
-        $scopes = $this->scopes();
173
-        if (isset($scopes[ $scope ])) {
174
-            return true;
175
-        }
176
-        return false;
177
-    }
178
-
179
-
180
-    /**
181
-     * Gets all active payment methods
182
-     *
183
-     * @param string $scope one of
184
-     * @param array  $query_params
185
-     * @return EE_Base_Class[]|EE_Payment_Method[]
186
-     * @throws EE_Error
187
-     */
188
-    public function get_all_active($scope = null, $query_params = [])
189
-    {
190
-        if (! isset($query_params['order_by']) && ! isset($query_params['order'])) {
191
-            $query_params['order_by'] = ['PMD_order' => 'ASC', 'PMD_ID' => 'ASC'];
192
-        }
193
-        return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
194
-    }
195
-
196
-
197
-    /**
198
-     * Counts all active gateways in the specified scope
199
-     *
200
-     * @param string $scope one of EEM_Payment_Method::scope_*
201
-     * @param array  $query_params
202
-     * @return int
203
-     * @throws EE_Error
204
-     */
205
-    public function count_active($scope = null, $query_params = [])
206
-    {
207
-        return $this->count($this->_get_query_params_for_all_active($scope, $query_params));
208
-    }
209
-
210
-
211
-    /**
212
-     * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
213
-     * argument to get all active for a given scope
214
-     *
215
-     * @param string $scope one of the constants EEM_Payment_Method::scope_*
216
-     * @param array  $query_params
217
-     * @return array
218
-     * @throws EE_Error
219
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
220
-     */
221
-    protected function _get_query_params_for_all_active($scope = null, $query_params = [])
222
-    {
223
-        if ($scope) {
224
-            if ($this->is_valid_scope($scope)) {
225
-                return array_replace_recursive([['PMD_scope' => ['LIKE', "%$scope%"]]], $query_params);
226
-            }
227
-            throw new EE_Error(
228
-                sprintf(
229
-                    esc_html__("'%s' is not a valid scope for a payment method", 'event_espresso'),
230
-                    $scope
231
-                )
232
-            );
233
-        }
234
-        $acceptable_scopes = [];
235
-        $count = 0;
236
-        foreach ($this->scopes() as $scope_name => $desc) {
237
-            $count++;
238
-            $acceptable_scopes[ 'PMD_scope*' . $count ] = ['LIKE', '%' . $scope_name . '%'];
239
-        }
240
-        return array_replace_recursive([['OR*active_scope' => $acceptable_scopes]], $query_params);
241
-    }
242
-
243
-
244
-    /**
245
-     * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
246
-     * argument to get all active for a given scope
247
-     *
248
-     * @param string $scope one of the constants EEM_Payment_Method::scope_*
249
-     * @param array  $query_params
250
-     * @return array
251
-     * @throws EE_Error
252
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
253
-     */
254
-    public function get_query_params_for_all_active($scope = null, $query_params = [])
255
-    {
256
-        return $this->_get_query_params_for_all_active($scope, $query_params);
257
-    }
258
-
259
-
260
-    /**
261
-     * Gets one active payment method. see @get_all_active for documentation
262
-     *
263
-     * @param string $scope
264
-     * @param array  $query_params
265
-     * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|NULL
266
-     * @throws EE_Error
267
-     */
268
-    public function get_one_active($scope = null, $query_params = [])
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 its active or not
276
-     *
277
-     * @param string $type
278
-     * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|NULL
279
-     * @throws EE_Error
280
-     */
281
-    public function get_one_of_type($type)
282
-    {
283
-        return $this->get_one([['PMD_type' => $type]]);
284
-    }
285
-
286
-
287
-    /**
288
-     * Overrides parent ot also check by the slug
289
-     *
290
-     * @param string|int|EE_Payment_Method $base_class_obj_or_id
291
-     * @param boolean                      $ensure_is_in_db
292
-     * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|int|string
293
-     * @throws EE_Error
294
-     * @see EEM_Base::ensure_is_obj()
295
-     */
296
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
297
-    {
298
-        // first: check if it's a slug
299
-        if (is_string($base_class_obj_or_id)) {
300
-            $obj = $this->get_one_by_slug($base_class_obj_or_id);
301
-            if ($obj) {
302
-                return $obj;
303
-            }
304
-        }
305
-        // ok so it wasn't a slug we were passed. try the usual then (ie, it's an object or an ID)
306
-        try {
307
-            return parent::ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db);
308
-        } catch (EE_Error $e) {
309
-            // handle it outside the catch
310
-        }
311
-        throw new EE_Error(
312
-            sprintf(
313
-                esc_html__("'%s' is neither a Payment Method ID, slug, nor object.", 'event_espresso'),
314
-                $base_class_obj_or_id
315
-            )
316
-        );
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets the ID of this object, or if its a string finds the object's id
322
-     * associated with that slug
323
-     *
324
-     * @param mixed $base_obj_or_id_or_slug
325
-     * @return int
326
-     * @throws EE_Error
327
-     */
328
-    public function ensure_is_ID($base_obj_or_id_or_slug)
329
-    {
330
-        if (is_string($base_obj_or_id_or_slug)) {
331
-            // assume it's a slug
332
-            $base_obj_or_id_or_slug = $this->get_one_by_slug($base_obj_or_id_or_slug);
333
-        }
334
-        return parent::ensure_is_ID($base_obj_or_id_or_slug);
335
-    }
336
-
337
-
338
-    /**
339
-     * Verifies the button urls on all the passed payment methods have a valid button url.
340
-     * If not, resets them to their default.
341
-     *
342
-     * @param EE_Payment_Method[] $payment_methods if NULL, defaults to all payment methods active in the cart
343
-     * @throws EE_Error
344
-     * @throws ReflectionException
345
-     */
346
-    public function verify_button_urls($payment_methods = null)
347
-    {
348
-        $payment_methods = is_array($payment_methods)
349
-            ? $payment_methods
350
-            : $this->get_all_active(EEM_Payment_Method::scope_cart);
351
-        foreach ($payment_methods as $payment_method) {
352
-            try {
353
-                // If there is really no button URL at all, or if the button URLs still point to decaf folder even
354
-                // though this is a caffeinated install, reset it to the default.
355
-                $current_button_url = $payment_method->button_url();
356
-                if (empty($current_button_url)
357
-                    || (
358
-                        strpos($current_button_url, 'decaf') !== false
359
-                        && strpos($payment_method->type_obj()->default_button_url(), 'decaf') === false
360
-                    )
361
-                ) {
362
-                    $payment_method->save(
363
-                        [
364
-                            'PMD_button_url' => $payment_method->type_obj()->default_button_url(),
365
-                        ]
366
-                    );
367
-                }
368
-            } catch (EE_Error $e) {
369
-                $payment_method->deactivate();
370
-            }
371
-        }
372
-    }
373
-
374
-
375
-    /**
376
-     * Overrides parent to not only turn wpdb results into EE_Payment_Method objects,
377
-     * but also verifies the payment method type of each is a usable object. If not,
378
-     * deactivate it, sets a notification, and deactivates it
379
-     *
380
-     * @param array $rows
381
-     * @return EE_Payment_Method[]
382
-     * @throws EE_Error
383
-     * @throws InvalidDataTypeException
384
-     * @throws ReflectionException
385
-     */
386
-    protected function _create_objects($rows = [])
387
-    {
388
-        EE_Registry::instance()->load_lib('Payment_Method_Manager');
389
-        $payment_methods = parent::_create_objects($rows);
390
-        /* @var $payment_methods EE_Payment_Method[] */
391
-        $usable_payment_methods = [];
392
-        foreach ($payment_methods as $key => $payment_method) {
393
-            if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($payment_method->type())) {
394
-                $usable_payment_methods[ $key ] = $payment_method;
395
-                // some payment methods enqueue their scripts in EE_PMT_*::__construct
396
-                // which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
397
-                // its scripts). but for backwards-compat we should continue to do that
398
-                $payment_method->type_obj();
399
-            } elseif ($payment_method->active()) {
400
-                // only deactivate and notify the admin if the payment is active somewhere
401
-                $payment_method->deactivate();
402
-                $payment_method->save();
403
-                do_action(
404
-                    'AHEE__EEM_Payment_Method___create_objects_auto_deactivated_payment_method',
405
-                    $payment_method
406
-                );
407
-                new PersistentAdminNotice(
408
-                    'auto-deactivated-' . $payment_method->type(),
409
-                    sprintf(
410
-                        esc_html__(
411
-                            '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.',
412
-                            'event_espresso'
413
-                        ),
414
-                        $payment_method->admin_name(),
415
-                        '<br />',
416
-                        '<a href="' . admin_url('plugins.php') . '">',
417
-                        '</a>'
418
-                    ),
419
-                    true
420
-                );
421
-            }
422
-        }
423
-        return $usable_payment_methods;
424
-    }
425
-
426
-
427
-    /**
428
-     * Gets all the payment methods which can be used for transaction
429
-     * (according to the relations between payment methods and events, and
430
-     * the currencies used for the transaction and their relation to payment methods)
431
-     *
432
-     * @param EE_Transaction $transaction
433
-     * @param string         $scope @see EEM_Payment_Method::get_all_for_events
434
-     * @return EE_Payment_Method[]
435
-     * @throws EE_Error
436
-     */
437
-    public function get_all_for_transaction($transaction, $scope)
438
-    {
439
-        // give addons a chance to override what payment methods are chosen based on the transaction
440
-        return apply_filters(
441
-            'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
442
-            $this->get_all_active($scope, ['group_by' => 'PMD_type']),
443
-            $transaction,
444
-            $scope
445
-        );
446
-    }
447
-
448
-
449
-    /**
450
-     * Returns the payment method used for the last payment made for a registration.
451
-     * Note: if an offline payment method was selected on the related transaction then this will have no payment
452
-     * methods returned. It will ONLY return a payment method for a PAYMENT recorded against the registration.
453
-     *
454
-     * @param EE_Registration|int $registration_or_reg_id Either the EE_Registration object or the id for the
455
-     *                                                    registration.
456
-     * @return EE_Payment|null
457
-     * @throws EE_Error
458
-     */
459
-    public function get_last_used_for_registration($registration_or_reg_id)
460
-    {
461
-        $registration_id = EEM_Registration::instance()->ensure_is_ID($registration_or_reg_id);
462
-
463
-        $query_params = [
464
-            0          => [
465
-                'Payment.Registration.REG_ID' => $registration_id,
466
-            ],
467
-            'order_by' => ['Payment.PAY_ID' => 'DESC'],
468
-        ];
469
-        return $this->get_one($query_params);
470
-    }
20
+	const scope_cart = 'CART';
21
+
22
+	const scope_admin = 'ADMIN';
23
+
24
+	const scope_api = 'API';
25
+
26
+	/**
27
+	 * @type EEM_Payment_Method
28
+	 */
29
+	protected static $_instance = null;
30
+
31
+
32
+	/**
33
+	 * private constructor to prevent direct creation
34
+	 *
35
+	 * @param null $timezone
36
+	 * @throws EE_Error
37
+	 */
38
+	protected function __construct($timezone = null)
39
+	{
40
+		$this->singular_item = esc_html__('Payment Method', 'event_espresso');
41
+		$this->plural_item = esc_html__('Payment Methods', 'event_espresso');
42
+		$this->_tables = [
43
+			'Payment_Method' => new EE_Primary_Table('esp_payment_method', 'PMD_ID'),
44
+		];
45
+		$this->_fields = [
46
+			'Payment_Method' => [
47
+				'PMD_ID'              => new EE_Primary_Key_Int_Field(
48
+					'PMD_ID',
49
+					esc_html__('ID', 'event_espresso')
50
+				),
51
+				'PMD_type'            => new EE_Plain_Text_Field(
52
+					'PMD_type',
53
+					esc_html__('Payment Method Type', 'event_espresso'),
54
+					false,
55
+					'Admin_Only'
56
+				),
57
+				'PMD_name'            => new EE_Plain_Text_Field(
58
+					'PMD_name',
59
+					esc_html__('Name', 'event_espresso'),
60
+					false
61
+				),
62
+				'PMD_desc'            => new EE_Post_Content_Field(
63
+					'PMD_desc',
64
+					esc_html__('Description', 'event_espresso'),
65
+					false,
66
+					''
67
+				),
68
+				'PMD_admin_name'      => new EE_Plain_Text_Field(
69
+					'PMD_admin_name',
70
+					esc_html__('Admin-Only Name', 'event_espresso'),
71
+					true
72
+				),
73
+				'PMD_admin_desc'      => new EE_Post_Content_Field(
74
+					'PMD_admin_desc',
75
+					esc_html__('Admin-Only Description', 'event_espresso'),
76
+					true
77
+				),
78
+				'PMD_slug'            => new EE_Slug_Field(
79
+					'PMD_slug',
80
+					esc_html__('Slug', 'event_espresso'),
81
+					false
82
+				),
83
+				'PMD_order'           => new EE_Integer_Field(
84
+					'PMD_order',
85
+					esc_html__('Order', 'event_espresso'),
86
+					false,
87
+					0
88
+				),
89
+				'PMD_debug_mode'      => new EE_Boolean_Field(
90
+					'PMD_debug_mode',
91
+					esc_html__('Debug Mode On?', 'event_espresso'),
92
+					false,
93
+					false
94
+				),
95
+				'PMD_wp_user'         => new EE_WP_User_Field(
96
+					'PMD_wp_user',
97
+					esc_html__('Payment Method Creator ID', 'event_espresso'),
98
+					false
99
+				),
100
+				'PMD_open_by_default' => new EE_Boolean_Field(
101
+					'PMD_open_by_default',
102
+					esc_html__('Open by Default?', 'event_espresso'),
103
+					false,
104
+					false
105
+				),
106
+				'PMD_button_url'      => new EE_Plain_Text_Field(
107
+					'PMD_button_url',
108
+					esc_html__('Button URL', 'event_espresso'),
109
+					true,
110
+					''
111
+				),
112
+				'PMD_scope'           => new EE_Serialized_Text_Field(
113
+					'PMD_scope',
114
+					esc_html__('Usable From?', 'event_espresso'),
115
+					false,
116
+					[]// possible values currently are 'CART','ADMIN','API'
117
+				),
118
+			],
119
+		];
120
+		$this->_model_relations = [
121
+			'Payment'     => new EE_Has_Many_Relation(),
122
+			'Currency'    => new EE_HABTM_Relation('Currency_Payment_Method'),
123
+			'Transaction' => new EE_Has_Many_Relation(),
124
+			'WP_User'     => new EE_Belongs_To_Relation(),
125
+		];
126
+		parent::__construct($timezone);
127
+	}
128
+
129
+
130
+	/**
131
+	 * Gets one by the slug provided
132
+	 *
133
+	 * @param string $slug
134
+	 * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|NULL
135
+	 * @throws EE_Error
136
+	 */
137
+	public function get_one_by_slug($slug)
138
+	{
139
+		return $this->get_one([['PMD_slug' => $slug]]);
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()
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 an 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($scope)
171
+	{
172
+		$scopes = $this->scopes();
173
+		if (isset($scopes[ $scope ])) {
174
+			return true;
175
+		}
176
+		return false;
177
+	}
178
+
179
+
180
+	/**
181
+	 * Gets all active payment methods
182
+	 *
183
+	 * @param string $scope one of
184
+	 * @param array  $query_params
185
+	 * @return EE_Base_Class[]|EE_Payment_Method[]
186
+	 * @throws EE_Error
187
+	 */
188
+	public function get_all_active($scope = null, $query_params = [])
189
+	{
190
+		if (! isset($query_params['order_by']) && ! isset($query_params['order'])) {
191
+			$query_params['order_by'] = ['PMD_order' => 'ASC', 'PMD_ID' => 'ASC'];
192
+		}
193
+		return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
194
+	}
195
+
196
+
197
+	/**
198
+	 * Counts all active gateways in the specified scope
199
+	 *
200
+	 * @param string $scope one of EEM_Payment_Method::scope_*
201
+	 * @param array  $query_params
202
+	 * @return int
203
+	 * @throws EE_Error
204
+	 */
205
+	public function count_active($scope = null, $query_params = [])
206
+	{
207
+		return $this->count($this->_get_query_params_for_all_active($scope, $query_params));
208
+	}
209
+
210
+
211
+	/**
212
+	 * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
213
+	 * argument to get all active for a given scope
214
+	 *
215
+	 * @param string $scope one of the constants EEM_Payment_Method::scope_*
216
+	 * @param array  $query_params
217
+	 * @return array
218
+	 * @throws EE_Error
219
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
220
+	 */
221
+	protected function _get_query_params_for_all_active($scope = null, $query_params = [])
222
+	{
223
+		if ($scope) {
224
+			if ($this->is_valid_scope($scope)) {
225
+				return array_replace_recursive([['PMD_scope' => ['LIKE', "%$scope%"]]], $query_params);
226
+			}
227
+			throw new EE_Error(
228
+				sprintf(
229
+					esc_html__("'%s' is not a valid scope for a payment method", 'event_espresso'),
230
+					$scope
231
+				)
232
+			);
233
+		}
234
+		$acceptable_scopes = [];
235
+		$count = 0;
236
+		foreach ($this->scopes() as $scope_name => $desc) {
237
+			$count++;
238
+			$acceptable_scopes[ 'PMD_scope*' . $count ] = ['LIKE', '%' . $scope_name . '%'];
239
+		}
240
+		return array_replace_recursive([['OR*active_scope' => $acceptable_scopes]], $query_params);
241
+	}
242
+
243
+
244
+	/**
245
+	 * Creates the $query_params that can be passed into any EEM_Payment_Method as their $query_params
246
+	 * argument to get all active for a given scope
247
+	 *
248
+	 * @param string $scope one of the constants EEM_Payment_Method::scope_*
249
+	 * @param array  $query_params
250
+	 * @return array
251
+	 * @throws EE_Error
252
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
253
+	 */
254
+	public function get_query_params_for_all_active($scope = null, $query_params = [])
255
+	{
256
+		return $this->_get_query_params_for_all_active($scope, $query_params);
257
+	}
258
+
259
+
260
+	/**
261
+	 * Gets one active payment method. see @get_all_active for documentation
262
+	 *
263
+	 * @param string $scope
264
+	 * @param array  $query_params
265
+	 * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|NULL
266
+	 * @throws EE_Error
267
+	 */
268
+	public function get_one_active($scope = null, $query_params = [])
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 its active or not
276
+	 *
277
+	 * @param string $type
278
+	 * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|NULL
279
+	 * @throws EE_Error
280
+	 */
281
+	public function get_one_of_type($type)
282
+	{
283
+		return $this->get_one([['PMD_type' => $type]]);
284
+	}
285
+
286
+
287
+	/**
288
+	 * Overrides parent ot also check by the slug
289
+	 *
290
+	 * @param string|int|EE_Payment_Method $base_class_obj_or_id
291
+	 * @param boolean                      $ensure_is_in_db
292
+	 * @return EE_Base_Class|EE_Payment_Method|EE_Soft_Delete_Base_Class|int|string
293
+	 * @throws EE_Error
294
+	 * @see EEM_Base::ensure_is_obj()
295
+	 */
296
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
297
+	{
298
+		// first: check if it's a slug
299
+		if (is_string($base_class_obj_or_id)) {
300
+			$obj = $this->get_one_by_slug($base_class_obj_or_id);
301
+			if ($obj) {
302
+				return $obj;
303
+			}
304
+		}
305
+		// ok so it wasn't a slug we were passed. try the usual then (ie, it's an object or an ID)
306
+		try {
307
+			return parent::ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db);
308
+		} catch (EE_Error $e) {
309
+			// handle it outside the catch
310
+		}
311
+		throw new EE_Error(
312
+			sprintf(
313
+				esc_html__("'%s' is neither a Payment Method ID, slug, nor object.", 'event_espresso'),
314
+				$base_class_obj_or_id
315
+			)
316
+		);
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets the ID of this object, or if its a string finds the object's id
322
+	 * associated with that slug
323
+	 *
324
+	 * @param mixed $base_obj_or_id_or_slug
325
+	 * @return int
326
+	 * @throws EE_Error
327
+	 */
328
+	public function ensure_is_ID($base_obj_or_id_or_slug)
329
+	{
330
+		if (is_string($base_obj_or_id_or_slug)) {
331
+			// assume it's a slug
332
+			$base_obj_or_id_or_slug = $this->get_one_by_slug($base_obj_or_id_or_slug);
333
+		}
334
+		return parent::ensure_is_ID($base_obj_or_id_or_slug);
335
+	}
336
+
337
+
338
+	/**
339
+	 * Verifies the button urls on all the passed payment methods have a valid button url.
340
+	 * If not, resets them to their default.
341
+	 *
342
+	 * @param EE_Payment_Method[] $payment_methods if NULL, defaults to all payment methods active in the cart
343
+	 * @throws EE_Error
344
+	 * @throws ReflectionException
345
+	 */
346
+	public function verify_button_urls($payment_methods = null)
347
+	{
348
+		$payment_methods = is_array($payment_methods)
349
+			? $payment_methods
350
+			: $this->get_all_active(EEM_Payment_Method::scope_cart);
351
+		foreach ($payment_methods as $payment_method) {
352
+			try {
353
+				// If there is really no button URL at all, or if the button URLs still point to decaf folder even
354
+				// though this is a caffeinated install, reset it to the default.
355
+				$current_button_url = $payment_method->button_url();
356
+				if (empty($current_button_url)
357
+					|| (
358
+						strpos($current_button_url, 'decaf') !== false
359
+						&& strpos($payment_method->type_obj()->default_button_url(), 'decaf') === false
360
+					)
361
+				) {
362
+					$payment_method->save(
363
+						[
364
+							'PMD_button_url' => $payment_method->type_obj()->default_button_url(),
365
+						]
366
+					);
367
+				}
368
+			} catch (EE_Error $e) {
369
+				$payment_method->deactivate();
370
+			}
371
+		}
372
+	}
373
+
374
+
375
+	/**
376
+	 * Overrides parent to not only turn wpdb results into EE_Payment_Method objects,
377
+	 * but also verifies the payment method type of each is a usable object. If not,
378
+	 * deactivate it, sets a notification, and deactivates it
379
+	 *
380
+	 * @param array $rows
381
+	 * @return EE_Payment_Method[]
382
+	 * @throws EE_Error
383
+	 * @throws InvalidDataTypeException
384
+	 * @throws ReflectionException
385
+	 */
386
+	protected function _create_objects($rows = [])
387
+	{
388
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
389
+		$payment_methods = parent::_create_objects($rows);
390
+		/* @var $payment_methods EE_Payment_Method[] */
391
+		$usable_payment_methods = [];
392
+		foreach ($payment_methods as $key => $payment_method) {
393
+			if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($payment_method->type())) {
394
+				$usable_payment_methods[ $key ] = $payment_method;
395
+				// some payment methods enqueue their scripts in EE_PMT_*::__construct
396
+				// which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
397
+				// its scripts). but for backwards-compat we should continue to do that
398
+				$payment_method->type_obj();
399
+			} elseif ($payment_method->active()) {
400
+				// only deactivate and notify the admin if the payment is active somewhere
401
+				$payment_method->deactivate();
402
+				$payment_method->save();
403
+				do_action(
404
+					'AHEE__EEM_Payment_Method___create_objects_auto_deactivated_payment_method',
405
+					$payment_method
406
+				);
407
+				new PersistentAdminNotice(
408
+					'auto-deactivated-' . $payment_method->type(),
409
+					sprintf(
410
+						esc_html__(
411
+							'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.',
412
+							'event_espresso'
413
+						),
414
+						$payment_method->admin_name(),
415
+						'<br />',
416
+						'<a href="' . admin_url('plugins.php') . '">',
417
+						'</a>'
418
+					),
419
+					true
420
+				);
421
+			}
422
+		}
423
+		return $usable_payment_methods;
424
+	}
425
+
426
+
427
+	/**
428
+	 * Gets all the payment methods which can be used for transaction
429
+	 * (according to the relations between payment methods and events, and
430
+	 * the currencies used for the transaction and their relation to payment methods)
431
+	 *
432
+	 * @param EE_Transaction $transaction
433
+	 * @param string         $scope @see EEM_Payment_Method::get_all_for_events
434
+	 * @return EE_Payment_Method[]
435
+	 * @throws EE_Error
436
+	 */
437
+	public function get_all_for_transaction($transaction, $scope)
438
+	{
439
+		// give addons a chance to override what payment methods are chosen based on the transaction
440
+		return apply_filters(
441
+			'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
442
+			$this->get_all_active($scope, ['group_by' => 'PMD_type']),
443
+			$transaction,
444
+			$scope
445
+		);
446
+	}
447
+
448
+
449
+	/**
450
+	 * Returns the payment method used for the last payment made for a registration.
451
+	 * Note: if an offline payment method was selected on the related transaction then this will have no payment
452
+	 * methods returned. It will ONLY return a payment method for a PAYMENT recorded against the registration.
453
+	 *
454
+	 * @param EE_Registration|int $registration_or_reg_id Either the EE_Registration object or the id for the
455
+	 *                                                    registration.
456
+	 * @return EE_Payment|null
457
+	 * @throws EE_Error
458
+	 */
459
+	public function get_last_used_for_registration($registration_or_reg_id)
460
+	{
461
+		$registration_id = EEM_Registration::instance()->ensure_is_ID($registration_or_reg_id);
462
+
463
+		$query_params = [
464
+			0          => [
465
+				'Payment.Registration.REG_ID' => $registration_id,
466
+			],
467
+			'order_by' => ['Payment.PAY_ID' => 'DESC'],
468
+		];
469
+		return $this->get_one($query_params);
470
+	}
471 471
 }
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($scope)
171 171
     {
172 172
         $scopes = $this->scopes();
173
-        if (isset($scopes[ $scope ])) {
173
+        if (isset($scopes[$scope])) {
174 174
             return true;
175 175
         }
176 176
         return false;
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
      */
188 188
     public function get_all_active($scope = null, $query_params = [])
189 189
     {
190
-        if (! isset($query_params['order_by']) && ! isset($query_params['order'])) {
190
+        if ( ! isset($query_params['order_by']) && ! isset($query_params['order'])) {
191 191
             $query_params['order_by'] = ['PMD_order' => 'ASC', 'PMD_ID' => 'ASC'];
192 192
         }
193 193
         return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
         $count = 0;
236 236
         foreach ($this->scopes() as $scope_name => $desc) {
237 237
             $count++;
238
-            $acceptable_scopes[ 'PMD_scope*' . $count ] = ['LIKE', '%' . $scope_name . '%'];
238
+            $acceptable_scopes['PMD_scope*'.$count] = ['LIKE', '%'.$scope_name.'%'];
239 239
         }
240 240
         return array_replace_recursive([['OR*active_scope' => $acceptable_scopes]], $query_params);
241 241
     }
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
         $usable_payment_methods = [];
392 392
         foreach ($payment_methods as $key => $payment_method) {
393 393
             if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($payment_method->type())) {
394
-                $usable_payment_methods[ $key ] = $payment_method;
394
+                $usable_payment_methods[$key] = $payment_method;
395 395
                 // some payment methods enqueue their scripts in EE_PMT_*::__construct
396 396
                 // which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
397 397
                 // its scripts). but for backwards-compat we should continue to do that
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
                     $payment_method
406 406
                 );
407 407
                 new PersistentAdminNotice(
408
-                    'auto-deactivated-' . $payment_method->type(),
408
+                    'auto-deactivated-'.$payment_method->type(),
409 409
                     sprintf(
410 410
                         esc_html__(
411 411
                             '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.',
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
                         ),
414 414
                         $payment_method->admin_name(),
415 415
                         '<br />',
416
-                        '<a href="' . admin_url('plugins.php') . '">',
416
+                        '<a href="'.admin_url('plugins.php').'">',
417 417
                         '</a>'
418 418
                     ),
419 419
                     true
Please login to merge, or discard this patch.
core/db_models/EEM_Event_Message_Template.model.php 2 patches
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -12,116 +12,116 @@
 block discarded – undo
12 12
 class EEM_Event_Message_Template extends EEM_Base
13 13
 {
14 14
 
15
-    // private instance of the EEM_Event_Message_Template object
16
-    protected static $_instance = null;
15
+	// private instance of the EEM_Event_Message_Template object
16
+	protected static $_instance = null;
17 17
 
18 18
 
19
-    /**
20
-     * protected constructor to prevent direct creation
21
-     *
22
-     * @param null $timezone
23
-     * @throws EE_Error
24
-     */
25
-    protected function __construct($timezone = null)
26
-    {
27
-        $this->singular_item = esc_html__('Event Message Template', 'event_espresso');
28
-        $this->plural_item = esc_html__('Event Message Templates', 'event_espresso');
19
+	/**
20
+	 * protected constructor to prevent direct creation
21
+	 *
22
+	 * @param null $timezone
23
+	 * @throws EE_Error
24
+	 */
25
+	protected function __construct($timezone = null)
26
+	{
27
+		$this->singular_item = esc_html__('Event Message Template', 'event_espresso');
28
+		$this->plural_item = esc_html__('Event Message Templates', 'event_espresso');
29 29
 
30
-        $this->_tables = [
31
-            'Event_Message_Template' => new EE_Primary_Table('esp_event_message_template', 'EMT_ID'),
32
-        ];
33
-        $this->_fields = [
34
-            'Event_Message_Template' => [
35
-                'EMT_ID' => new EE_Primary_Key_Int_Field(
36
-                    'EMT_ID',
37
-                    esc_html__('Event Message Template ID', 'event_espresso')
38
-                ),
39
-                'EVT_ID' => new EE_Foreign_Key_Int_Field(
40
-                    'EVT_ID',
41
-                    esc_html__('The ID to the Event', 'event_espresso'),
42
-                    false,
43
-                    0,
44
-                    'Event'
45
-                ),
46
-                'GRP_ID' => new EE_Foreign_Key_Int_Field(
47
-                    'GRP_ID',
48
-                    esc_html__('The ID to the Message Template Group', 'event_espresso'),
49
-                    false,
50
-                    0,
51
-                    'Message_Template_Group'
52
-                ),
53
-            ],
54
-        ];
55
-        $this->_model_relations = [
56
-            'Event'                  => new EE_Belongs_To_Relation(),
57
-            'Message_Template_Group' => new EE_Belongs_To_Relation(),
58
-        ];
59
-        $path_to_event = 'Event';
60
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
61
-            $path_to_event
62
-        );
63
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
64
-            $path_to_event
65
-        );
66
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
67
-            $path_to_event
68
-        );
69
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
70
-            $path_to_event,
71
-            EEM_Base::caps_edit
72
-        );
73
-        parent::__construct($timezone);
74
-    }
30
+		$this->_tables = [
31
+			'Event_Message_Template' => new EE_Primary_Table('esp_event_message_template', 'EMT_ID'),
32
+		];
33
+		$this->_fields = [
34
+			'Event_Message_Template' => [
35
+				'EMT_ID' => new EE_Primary_Key_Int_Field(
36
+					'EMT_ID',
37
+					esc_html__('Event Message Template ID', 'event_espresso')
38
+				),
39
+				'EVT_ID' => new EE_Foreign_Key_Int_Field(
40
+					'EVT_ID',
41
+					esc_html__('The ID to the Event', 'event_espresso'),
42
+					false,
43
+					0,
44
+					'Event'
45
+				),
46
+				'GRP_ID' => new EE_Foreign_Key_Int_Field(
47
+					'GRP_ID',
48
+					esc_html__('The ID to the Message Template Group', 'event_espresso'),
49
+					false,
50
+					0,
51
+					'Message_Template_Group'
52
+				),
53
+			],
54
+		];
55
+		$this->_model_relations = [
56
+			'Event'                  => new EE_Belongs_To_Relation(),
57
+			'Message_Template_Group' => new EE_Belongs_To_Relation(),
58
+		];
59
+		$path_to_event = 'Event';
60
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
61
+			$path_to_event
62
+		);
63
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
64
+			$path_to_event
65
+		);
66
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
67
+			$path_to_event
68
+		);
69
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
70
+			$path_to_event,
71
+			EEM_Base::caps_edit
72
+		);
73
+		parent::__construct($timezone);
74
+	}
75 75
 
76 76
 
77
-    /**
78
-     * helper method to simply return an array of event ids for events attached to the given
79
-     * message template group.
80
-     *
81
-     * @param int $GRP_ID The MTP group we want attached events for.
82
-     * @return  array               An array of event ids.
83
-     * @throws EE_Error
84
-     * @since 4.3.0
85
-     */
86
-    public function get_attached_event_ids($GRP_ID)
87
-    {
88
-        $event_ids = $this->_get_all_wpdb_results([['GRP_ID' => $GRP_ID]], ARRAY_N, 'EVT_ID');
89
-        $event_ids = call_user_func_array('array_merge', $event_ids);
90
-        return $event_ids;
91
-    }
77
+	/**
78
+	 * helper method to simply return an array of event ids for events attached to the given
79
+	 * message template group.
80
+	 *
81
+	 * @param int $GRP_ID The MTP group we want attached events for.
82
+	 * @return  array               An array of event ids.
83
+	 * @throws EE_Error
84
+	 * @since 4.3.0
85
+	 */
86
+	public function get_attached_event_ids($GRP_ID)
87
+	{
88
+		$event_ids = $this->_get_all_wpdb_results([['GRP_ID' => $GRP_ID]], ARRAY_N, 'EVT_ID');
89
+		$event_ids = call_user_func_array('array_merge', $event_ids);
90
+		return $event_ids;
91
+	}
92 92
 
93 93
 
94
-    /**
95
-     * helper method for clearing event/group relations for the given event ids and grp ids.
96
-     *
97
-     * @param array $GRP_IDs An array of GRP_IDs. Optional. If empty then there must be EVT IDs.
98
-     * @param array $EVT_IDs An array of EVT_IDs.  Optional. If empty then there must be GRP IDs.
99
-     * @return int             How many rows were deleted.
100
-     * @throws EE_Error
101
-     * @throws EE_Error
102
-     */
103
-    public function delete_event_group_relations($GRP_IDs = [], $EVT_IDs = [])
104
-    {
105
-        if (empty($GRP_IDs) && empty($EVT_IDs)) {
106
-            throw new EE_Error(
107
-                sprintf(
108
-                    esc_html__(
109
-                        '%s requires either an array of GRP_IDs or EVT_IDs or both, but both cannot be empty.',
110
-                        'event_espresso'
111
-                    ),
112
-                    __METHOD__
113
-                )
114
-            );
115
-        }
94
+	/**
95
+	 * helper method for clearing event/group relations for the given event ids and grp ids.
96
+	 *
97
+	 * @param array $GRP_IDs An array of GRP_IDs. Optional. If empty then there must be EVT IDs.
98
+	 * @param array $EVT_IDs An array of EVT_IDs.  Optional. If empty then there must be GRP IDs.
99
+	 * @return int             How many rows were deleted.
100
+	 * @throws EE_Error
101
+	 * @throws EE_Error
102
+	 */
103
+	public function delete_event_group_relations($GRP_IDs = [], $EVT_IDs = [])
104
+	{
105
+		if (empty($GRP_IDs) && empty($EVT_IDs)) {
106
+			throw new EE_Error(
107
+				sprintf(
108
+					esc_html__(
109
+						'%s requires either an array of GRP_IDs or EVT_IDs or both, but both cannot be empty.',
110
+						'event_espresso'
111
+					),
112
+					__METHOD__
113
+				)
114
+			);
115
+		}
116 116
 
117
-        $where = [];
118
-        if (! empty($GRP_IDs)) {
119
-            $where['GRP_ID'] = ['IN', (array) $GRP_IDs];
120
-        }
121
-        if (! empty($EVT_IDs)) {
122
-            $where['EVT_ID'] = ['IN', (array) $EVT_IDs];
123
-        }
117
+		$where = [];
118
+		if (! empty($GRP_IDs)) {
119
+			$where['GRP_ID'] = ['IN', (array) $GRP_IDs];
120
+		}
121
+		if (! empty($EVT_IDs)) {
122
+			$where['EVT_ID'] = ['IN', (array) $EVT_IDs];
123
+		}
124 124
 
125
-        return $this->delete([$where], false);
126
-    }
125
+		return $this->delete([$where], false);
126
+	}
127 127
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -57,16 +57,16 @@  discard block
 block discarded – undo
57 57
             'Message_Template_Group' => new EE_Belongs_To_Relation(),
58 58
         ];
59 59
         $path_to_event = 'Event';
60
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
60
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public(
61 61
             $path_to_event
62 62
         );
63
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
63
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Event_Related_Protected(
64 64
             $path_to_event
65 65
         );
66
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
66
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Event_Related_Protected(
67 67
             $path_to_event
68 68
         );
69
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
69
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Event_Related_Protected(
70 70
             $path_to_event,
71 71
             EEM_Base::caps_edit
72 72
         );
@@ -115,10 +115,10 @@  discard block
 block discarded – undo
115 115
         }
116 116
 
117 117
         $where = [];
118
-        if (! empty($GRP_IDs)) {
118
+        if ( ! empty($GRP_IDs)) {
119 119
             $where['GRP_ID'] = ['IN', (array) $GRP_IDs];
120 120
         }
121
-        if (! empty($EVT_IDs)) {
121
+        if ( ! empty($EVT_IDs)) {
122 122
             $where['EVT_ID'] = ['IN', (array) $EVT_IDs];
123 123
         }
124 124
 
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 2 patches
Indentation   +1336 added lines, -1336 removed lines patch added patch discarded remove patch
@@ -23,1340 +23,1340 @@
 block discarded – undo
23 23
 class EED_Core_Rest_Api extends \EED_Module
24 24
 {
25 25
 
26
-    const ee_api_namespace = Domain::API_NAMESPACE;
27
-
28
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
29
-
30
-    const saved_routes_option_names = 'ee_core_routes';
31
-
32
-    /**
33
-     * string used in _links response bodies to make them globally unique.
34
-     *
35
-     * @see http://v2.wp-api.org/extending/linking/
36
-     */
37
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
38
-
39
-    /**
40
-     * @var CalculatedModelFields
41
-     */
42
-    protected static $_field_calculator;
43
-
44
-
45
-    /**
46
-     * @return EED_Core_Rest_Api|EED_Module
47
-     */
48
-    public static function instance()
49
-    {
50
-        self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields');
51
-        return parent::get_instance(__CLASS__);
52
-    }
53
-
54
-
55
-    /**
56
-     *    set_hooks - for hooking into EE Core, other modules, etc
57
-     *
58
-     * @access    public
59
-     * @return    void
60
-     */
61
-    public static function set_hooks()
62
-    {
63
-        self::set_hooks_both();
64
-    }
65
-
66
-
67
-    /**
68
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
-     *
70
-     * @access    public
71
-     * @return    void
72
-     */
73
-    public static function set_hooks_admin()
74
-    {
75
-        self::set_hooks_both();
76
-    }
77
-
78
-
79
-    public static function set_hooks_both()
80
-    {
81
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
82
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
84
-        add_filter(
85
-            'rest_index',
86
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex')
87
-        );
88
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
89
-    }
90
-
91
-
92
-    /**
93
-     * sets up hooks which only need to be included as part of REST API requests;
94
-     * other requests like to the frontend or admin etc don't need them
95
-     *
96
-     * @throws \EE_Error
97
-     */
98
-    public static function set_hooks_rest_api()
99
-    {
100
-        // set hooks which account for changes made to the API
101
-        EED_Core_Rest_Api::_set_hooks_for_changes();
102
-    }
103
-
104
-
105
-    /**
106
-     * public wrapper of _set_hooks_for_changes.
107
-     * Loads all the hooks which make requests to old versions of the API
108
-     * appear the same as they always did
109
-     *
110
-     * @throws EE_Error
111
-     */
112
-    public static function set_hooks_for_changes()
113
-    {
114
-        self::_set_hooks_for_changes();
115
-    }
116
-
117
-
118
-    /**
119
-     * Loads all the hooks which make requests to old versions of the API
120
-     * appear the same as they always did
121
-     *
122
-     * @throws EE_Error
123
-     */
124
-    protected static function _set_hooks_for_changes()
125
-    {
126
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
127
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
128
-            // ignore the base parent class
129
-            // and legacy named classes
130
-            if ($classname_in_namespace === 'ChangesInBase'
131
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
132
-            ) {
133
-                continue;
134
-            }
135
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
136
-            if (class_exists($full_classname)) {
137
-                $instance_of_class = new $full_classname;
138
-                if ($instance_of_class instanceof ChangesInBase) {
139
-                    $instance_of_class->setHooks();
140
-                }
141
-            }
142
-        }
143
-    }
144
-
145
-
146
-    /**
147
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
148
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
149
-     *
150
-     * @throws \EE_Error
151
-     */
152
-    public static function register_routes()
153
-    {
154
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
155
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
156
-                /**
157
-                 * @var array     $data_for_multiple_endpoints numerically indexed array
158
-                 *                                         but can also contain route options like {
159
-                 * @type array    $schema                      {
160
-                 * @type callable $schema_callback
161
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
162
-                 * WP_REST_Request of course
163
-                 * }
164
-                 * }
165
-                 */
166
-                // when registering routes, register all the endpoints' data at the same time
167
-                $multiple_endpoint_args = array();
168
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
169
-                    /**
170
-                     * @var array     $data_for_single_endpoint {
171
-                     * @type callable $callback
172
-                     * @type string methods
173
-                     * @type array args
174
-                     * @type array _links
175
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
176
-                     * WP_REST_Request of course
177
-                     * }
178
-                     */
179
-                    // skip route options
180
-                    if (! is_numeric($endpoint_key)) {
181
-                        continue;
182
-                    }
183
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184
-                        throw new EE_Error(
185
-                            esc_html__(
186
-                            // @codingStandardsIgnoreStart
187
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
188
-                                // @codingStandardsIgnoreEnd
189
-                                'event_espresso'
190
-                            )
191
-                        );
192
-                    }
193
-                    $callback = $data_for_single_endpoint['callback'];
194
-                    $single_endpoint_args = array(
195
-                        'methods' => $data_for_single_endpoint['methods'],
196
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
197
-                            : array(),
198
-                    );
199
-                    if (isset($data_for_single_endpoint['_links'])) {
200
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
201
-                    }
202
-                    if (isset($data_for_single_endpoint['callback_args'])) {
203
-                        $callback_args = $data_for_single_endpoint['callback_args'];
204
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
205
-                            $callback,
206
-                            $callback_args
207
-                        ) {
208
-                            array_unshift($callback_args, $request);
209
-                            return call_user_func_array(
210
-                                $callback,
211
-                                $callback_args
212
-                            );
213
-                        };
214
-                    } else {
215
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
216
-                    }
217
-                    // As of WordPress 5.5, if a permission_callback is not provided,
218
-                    // the REST API will issue a _doing_it_wrong notice.
219
-                    // Since the EE REST API defers capabilities to the db model system,
220
-                    // we will just use the generic WP callback for public endpoints
221
-                    if (! isset($single_endpoint_args['permission_callback'])) {
222
-                        $single_endpoint_args['permission_callback'] = '__return_true';
223
-                    }
224
-                    $multiple_endpoint_args[] = $single_endpoint_args;
225
-                }
226
-                if (isset($data_for_multiple_endpoints['schema'])) {
227
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
228
-                    $schema_callback = $schema_route_data['schema_callback'];
229
-                    $callback_args = $schema_route_data['callback_args'];
230
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
231
-                        return call_user_func_array(
232
-                            $schema_callback,
233
-                            $callback_args
234
-                        );
235
-                    };
236
-                }
237
-                register_rest_route(
238
-                    $namespace,
239
-                    $relative_route,
240
-                    $multiple_endpoint_args
241
-                );
242
-            }
243
-        }
244
-    }
245
-
246
-
247
-    /**
248
-     * Checks if there was a version change or something that merits invalidating the cached
249
-     * route data. If so, invalidates the cached route data so that it gets refreshed
250
-     * next time the WP API is used
251
-     */
252
-    public static function invalidate_cached_route_data_on_version_change()
253
-    {
254
-        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
255
-            EED_Core_Rest_Api::invalidate_cached_route_data();
256
-        }
257
-        foreach (EE_Registry::instance()->addons as $addon) {
258
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
259
-                EED_Core_Rest_Api::invalidate_cached_route_data();
260
-            }
261
-        }
262
-    }
263
-
264
-
265
-    /**
266
-     * Removes the cached route data so it will get refreshed next time the WP API is used
267
-     */
268
-    public static function invalidate_cached_route_data()
269
-    {
270
-        // delete the saved EE REST API routes
271
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
272
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
273
-        }
274
-    }
275
-
276
-
277
-    /**
278
-     * Gets the EE route data
279
-     *
280
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
281
-     * @throws \EE_Error
282
-     * @type string|array $callback
283
-     * @type string       $methods
284
-     * @type boolean      $hidden_endpoint
285
-     * }
286
-     */
287
-    public static function get_ee_route_data()
288
-    {
289
-        $ee_routes = array();
290
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
291
-            $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
292
-                $version,
293
-                $hidden_endpoints
294
-            );
295
-        }
296
-        return $ee_routes;
297
-    }
298
-
299
-
300
-    /**
301
-     * Gets the EE route data from the wp options if it exists already,
302
-     * otherwise re-generates it and saves it to the option
303
-     *
304
-     * @param string  $version
305
-     * @param boolean $hidden_endpoints
306
-     * @return array
307
-     * @throws \EE_Error
308
-     */
309
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
310
-    {
311
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
312
-        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
313
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
314
-        }
315
-        return $ee_routes;
316
-    }
317
-
318
-
319
-    /**
320
-     * Saves the EE REST API route data to a wp option and returns it
321
-     *
322
-     * @param string  $version
323
-     * @param boolean $hidden_endpoints
324
-     * @return mixed|null
325
-     * @throws \EE_Error
326
-     */
327
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
328
-    {
329
-        $instance = self::instance();
330
-        $routes = apply_filters(
331
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
332
-            array_replace_recursive(
333
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
334
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
335
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
336
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
337
-            )
338
-        );
339
-        $option_name = self::saved_routes_option_names . $version;
340
-        if (get_option($option_name)) {
341
-            update_option($option_name, $routes, true);
342
-        } else {
343
-            add_option($option_name, $routes, null, 'no');
344
-        }
345
-        return $routes;
346
-    }
347
-
348
-
349
-    /**
350
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
351
-     * need to calculate it on every request
352
-     *
353
-     * @deprecated since version 4.9.1
354
-     * @return void
355
-     */
356
-    public static function save_ee_routes()
357
-    {
358
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
359
-            $instance = self::instance();
360
-            $routes = apply_filters(
361
-                'EED_Core_Rest_Api__save_ee_routes__routes',
362
-                array_replace_recursive(
363
-                    $instance->_register_config_routes(),
364
-                    $instance->_register_meta_routes(),
365
-                    $instance->_register_model_routes(),
366
-                    $instance->_register_rpc_routes()
367
-                )
368
-            );
369
-            update_option(self::saved_routes_option_names, $routes, true);
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Gets all the route information relating to EE models
376
-     *
377
-     * @return array @see get_ee_route_data
378
-     * @deprecated since version 4.9.1
379
-     */
380
-    protected function _register_model_routes()
381
-    {
382
-        $model_routes = array();
383
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
384
-            $model_routes[ EED_Core_Rest_Api::ee_api_namespace
385
-                           . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
386
-        }
387
-        return $model_routes;
388
-    }
389
-
390
-
391
-    /**
392
-     * Decides whether or not to add write endpoints for this model.
393
-     *
394
-     * Currently, this defaults to exclude all global tables and models
395
-     * which would allow inserting WP core data (we don't want to duplicate
396
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
397
-     *
398
-     * @param EEM_Base $model
399
-     * @return bool
400
-     */
401
-    public static function should_have_write_endpoints(EEM_Base $model)
402
-    {
403
-        if ($model->is_wp_core_model()) {
404
-            return false;
405
-        }
406
-        foreach ($model->get_tables() as $table) {
407
-            if ($table->is_global()) {
408
-                return false;
409
-            }
410
-        }
411
-        return true;
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
417
-     * in this versioned namespace of EE4
418
-     *
419
-     * @param $version
420
-     * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
421
-     */
422
-    public static function model_names_with_plural_routes($version)
423
-    {
424
-        $model_version_info = new ModelVersionInfo($version);
425
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
426
-        // let's not bother having endpoints for extra metas
427
-        unset(
428
-            $models_to_register['Extra_Meta'],
429
-            $models_to_register['Extra_Join'],
430
-            $models_to_register['Post_Meta']
431
-        );
432
-        return apply_filters(
433
-            'FHEE__EED_Core_REST_API___register_model_routes',
434
-            $models_to_register
435
-        );
436
-    }
437
-
438
-
439
-    /**
440
-     * Gets the route data for EE models in the specified version
441
-     *
442
-     * @param string  $version
443
-     * @param boolean $hidden_endpoint
444
-     * @return array
445
-     * @throws EE_Error
446
-     */
447
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
448
-    {
449
-        $model_routes = array();
450
-        $model_version_info = new ModelVersionInfo($version);
451
-        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
452
-            $model = \EE_Registry::instance()->load_model($model_name);
453
-            // if this isn't a valid model then let's skip iterate to the next item in the loop.
454
-            if (! $model instanceof EEM_Base) {
455
-                continue;
456
-            }
457
-            // yes we could just register one route for ALL models, but then they wouldn't show up in the index
458
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
459
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
460
-            $model_routes[ $plural_model_route ] = array(
461
-                array(
462
-                    'callback'        => array(
463
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
464
-                        'handleRequestGetAll',
465
-                    ),
466
-                    'callback_args'   => array($version, $model_name),
467
-                    'methods'         => WP_REST_Server::READABLE,
468
-                    'hidden_endpoint' => $hidden_endpoint,
469
-                    'args'            => $this->_get_read_query_params($model, $version),
470
-                    '_links'          => array(
471
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
472
-                    ),
473
-                ),
474
-                'schema' => array(
475
-                    'schema_callback' => array(
476
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
477
-                        'handleSchemaRequest',
478
-                    ),
479
-                    'callback_args'   => array($version, $model_name),
480
-                ),
481
-            );
482
-            $model_routes[ $singular_model_route ] = array(
483
-                array(
484
-                    'callback'        => array(
485
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
486
-                        'handleRequestGetOne',
487
-                    ),
488
-                    'callback_args'   => array($version, $model_name),
489
-                    'methods'         => WP_REST_Server::READABLE,
490
-                    'hidden_endpoint' => $hidden_endpoint,
491
-                    'args'            => $this->_get_response_selection_query_params($model, $version, true),
492
-                ),
493
-            );
494
-            if (apply_filters(
495
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
496
-                EED_Core_Rest_Api::should_have_write_endpoints($model),
497
-                $model
498
-            )) {
499
-                $model_routes[ $plural_model_route ][] = array(
500
-                    'callback'        => array(
501
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
502
-                        'handleRequestInsert',
503
-                    ),
504
-                    'callback_args'   => array($version, $model_name),
505
-                    'methods'         => WP_REST_Server::CREATABLE,
506
-                    'hidden_endpoint' => $hidden_endpoint,
507
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
508
-                );
509
-                $model_routes[ $singular_model_route ] = array_merge(
510
-                    $model_routes[ $singular_model_route ],
511
-                    array(
512
-                        array(
513
-                            'callback'        => array(
514
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
515
-                                'handleRequestUpdate',
516
-                            ),
517
-                            'callback_args'   => array($version, $model_name),
518
-                            'methods'         => WP_REST_Server::EDITABLE,
519
-                            'hidden_endpoint' => $hidden_endpoint,
520
-                            'args'            => $this->_get_write_params($model_name, $model_version_info),
521
-                        ),
522
-                        array(
523
-                            'callback'        => array(
524
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
525
-                                'handleRequestDelete',
526
-                            ),
527
-                            'callback_args'   => array($version, $model_name),
528
-                            'methods'         => WP_REST_Server::DELETABLE,
529
-                            'hidden_endpoint' => $hidden_endpoint,
530
-                            'args'            => $this->_get_delete_query_params($model, $version),
531
-                        ),
532
-                    )
533
-                );
534
-            }
535
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
536
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
537
-                    $model,
538
-                    '(?P<id>[^\/]+)',
539
-                    $relation_obj
540
-                );
541
-                $model_routes[ $related_route ] = array(
542
-                    array(
543
-                        'callback'        => array(
544
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
545
-                            'handleRequestGetRelated',
546
-                        ),
547
-                        'callback_args'   => array($version, $model_name, $relation_name),
548
-                        'methods'         => WP_REST_Server::READABLE,
549
-                        'hidden_endpoint' => $hidden_endpoint,
550
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
551
-                    ),
552
-                );
553
-
554
-                $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
555
-                $model_routes[ $related_write_route ] = array(
556
-                    array(
557
-                        'callback'        => array(
558
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Write',
559
-                            'handleRequestAddRelation',
560
-                        ),
561
-                        'callback_args'   => array($version, $model_name, $relation_name),
562
-                        'methods'         => WP_REST_Server::EDITABLE,
563
-                        'hidden_endpoint' => $hidden_endpoint,
564
-                        'args'            => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version)
565
-                    ),
566
-                    array(
567
-                        'callback'        => array(
568
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Write',
569
-                            'handleRequestRemoveRelation',
570
-                        ),
571
-                        'callback_args'   => array($version, $model_name, $relation_name),
572
-                        'methods'         => WP_REST_Server::DELETABLE,
573
-                        'hidden_endpoint' => $hidden_endpoint,
574
-                        'args'            => array()
575
-                    ),
576
-                );
577
-            }
578
-        }
579
-        return $model_routes;
580
-    }
581
-
582
-
583
-    /**
584
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
585
-     * excluding the preceding slash.
586
-     * Eg you pass get_plural_route_to('Event') = 'events'
587
-     *
588
-     * @param EEM_Base $model
589
-     * @return string
590
-     */
591
-    public static function get_collection_route(EEM_Base $model)
592
-    {
593
-        return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
594
-    }
595
-
596
-
597
-    /**
598
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
599
-     * excluding the preceding slash.
600
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
601
-     *
602
-     * @param EEM_Base $model eg Event or Venue
603
-     * @param string   $id
604
-     * @return string
605
-     */
606
-    public static function get_entity_route($model, $id)
607
-    {
608
-        return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
609
-    }
610
-
611
-
612
-    /**
613
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
614
-     * excluding the preceding slash.
615
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
616
-     *
617
-     * @param EEM_Base               $model eg Event or Venue
618
-     * @param string                 $id
619
-     * @param EE_Model_Relation_Base $relation_obj
620
-     * @return string
621
-     */
622
-    public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
623
-    {
624
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
625
-            $relation_obj->get_other_model()->get_this_model_name(),
626
-            $relation_obj
627
-        );
628
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
629
-    }
630
-
631
-
632
-    /**
633
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
634
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
635
-     *
636
-     * @param string $relative_route
637
-     * @param string $version
638
-     * @return string
639
-     */
640
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36')
641
-    {
642
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
643
-    }
644
-
645
-
646
-    /**
647
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
648
-     * routes that don't conform to the traditional REST CRUD-style).
649
-     *
650
-     * @deprecated since 4.9.1
651
-     */
652
-    protected function _register_rpc_routes()
653
-    {
654
-        $routes = array();
655
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
656
-            $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
657
-                $version,
658
-                $hidden_endpoint
659
-            );
660
-        }
661
-        return $routes;
662
-    }
663
-
664
-
665
-    /**
666
-     * @param string  $version
667
-     * @param boolean $hidden_endpoint
668
-     * @return array
669
-     */
670
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
671
-    {
672
-        $this_versions_routes = array();
673
-        // checkin endpoint
674
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
675
-            array(
676
-                'callback'        => array(
677
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
678
-                    'handleRequestToggleCheckin',
679
-                ),
680
-                'methods'         => WP_REST_Server::CREATABLE,
681
-                'hidden_endpoint' => $hidden_endpoint,
682
-                'args'            => array(
683
-                    'force' => array(
684
-                        'required'    => false,
685
-                        'default'     => false,
686
-                        'description' => __(
687
-                        // @codingStandardsIgnoreStart
688
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
689
-                            // @codingStandardsIgnoreEnd
690
-                            'event_espresso'
691
-                        ),
692
-                    ),
693
-                ),
694
-                'callback_args'   => array($version),
695
-            ),
696
-        );
697
-        return apply_filters(
698
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
699
-            $this_versions_routes,
700
-            $version,
701
-            $hidden_endpoint
702
-        );
703
-    }
704
-
705
-
706
-    /**
707
-     * Gets the query params that can be used when request one or many
708
-     *
709
-     * @param EEM_Base $model
710
-     * @param string   $version
711
-     * @return array
712
-     */
713
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false)
714
-    {
715
-        $query_params = array(
716
-            'include'   => array(
717
-                'required' => false,
718
-                'default'  => '*',
719
-                'type'     => 'string',
720
-            ),
721
-            'calculate' => array(
722
-                'required'          => false,
723
-                'default'           => '',
724
-                'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
725
-                'type'              => 'string',
726
-                // because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
727
-                // freaks out. We'll just validate this argument while handling the request
728
-                'validate_callback' => null,
729
-                'sanitize_callback' => null,
730
-            ),
731
-            'password' => array(
732
-                'required' => false,
733
-                'default' => '',
734
-                'type' => 'string'
735
-            )
736
-        );
737
-        return apply_filters(
738
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
739
-            $query_params,
740
-            $model,
741
-            $version
742
-        );
743
-    }
744
-
745
-
746
-    /**
747
-     * Gets the parameters acceptable for delete requests
748
-     *
749
-     * @param \EEM_Base $model
750
-     * @param string    $version
751
-     * @return array
752
-     */
753
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
754
-    {
755
-        $params_for_delete = array(
756
-            'allow_blocking' => array(
757
-                'required' => false,
758
-                'default'  => true,
759
-                'type'     => 'boolean',
760
-            ),
761
-        );
762
-        $params_for_delete['force'] = array(
763
-            'required' => false,
764
-            'default'  => false,
765
-            'type'     => 'boolean',
766
-        );
767
-        return apply_filters(
768
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
769
-            $params_for_delete,
770
-            $model,
771
-            $version
772
-        );
773
-    }
774
-
775
-    protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
776
-    {
777
-        // if they're related through a HABTM relation, check for any non-FKs
778
-        $all_relation_settings = $source_model->relation_settings();
779
-        $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
780
-        $params = array();
781
-        if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
782
-            foreach ($relation_settings->getNonKeyFields() as $field) {
783
-                /* @var $field EE_Model_Field_Base */
784
-                $params[ $field->get_name() ] = array(
785
-                    'required' => ! $field->is_nullable(),
786
-                    'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
787
-                    'type' => $field->getSchemaType(),
788
-                    'validate_callbaack' => null,
789
-                    'sanitize_callback' => null
790
-                );
791
-            }
792
-        }
793
-        return $params;
794
-    }
795
-
796
-
797
-    /**
798
-     * Gets info about reading query params that are acceptable
799
-     *
800
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
801
-     * @param  string   $version
802
-     * @return array    describing the args acceptable when querying this model
803
-     * @throws EE_Error
804
-     */
805
-    protected function _get_read_query_params(\EEM_Base $model, $version)
806
-    {
807
-        $default_orderby = array();
808
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
809
-            $default_orderby[ $key_field->get_name() ] = 'ASC';
810
-        }
811
-        return array_merge(
812
-            $this->_get_response_selection_query_params($model, $version),
813
-            array(
814
-                'where'    => array(
815
-                    'required'          => false,
816
-                    'default'           => array(),
817
-                    'type'              => 'object',
818
-                    // because we accept an almost infinite list of possible where conditions, WP
819
-                    // core validation and sanitization freaks out. We'll just validate this argument
820
-                    // while handling the request
821
-                    'validate_callback' => null,
822
-                    'sanitize_callback' => null,
823
-                ),
824
-                'limit'    => array(
825
-                    'required'          => false,
826
-                    'default'           => EED_Core_Rest_Api::get_default_query_limit(),
827
-                    'type'              => array(
828
-                        'array',
829
-                        'string',
830
-                        'integer',
831
-                    ),
832
-                    // because we accept a variety of types, WP core validation and sanitization
833
-                    // freaks out. We'll just validate this argument while handling the request
834
-                    'validate_callback' => null,
835
-                    'sanitize_callback' => null,
836
-                ),
837
-                'order_by' => array(
838
-                    'required'          => false,
839
-                    'default'           => $default_orderby,
840
-                    'type'              => array(
841
-                        'object',
842
-                        'string',
843
-                    ),// because we accept a variety of types, WP core validation and sanitization
844
-                    // freaks out. We'll just validate this argument while handling the request
845
-                    'validate_callback' => null,
846
-                    'sanitize_callback' => null,
847
-                ),
848
-                'group_by' => array(
849
-                    'required'          => false,
850
-                    'default'           => null,
851
-                    'type'              => array(
852
-                        'object',
853
-                        'string',
854
-                    ),
855
-                    // because we accept  an almost infinite list of possible groupings,
856
-                    // WP core validation and sanitization
857
-                    // freaks out. We'll just validate this argument while handling the request
858
-                    'validate_callback' => null,
859
-                    'sanitize_callback' => null,
860
-                ),
861
-                'having'   => array(
862
-                    'required'          => false,
863
-                    'default'           => null,
864
-                    'type'              => 'object',
865
-                    // because we accept an almost infinite list of possible where conditions, WP
866
-                    // core validation and sanitization freaks out. We'll just validate this argument
867
-                    // while handling the request
868
-                    'validate_callback' => null,
869
-                    'sanitize_callback' => null,
870
-                ),
871
-                'caps'     => array(
872
-                    'required' => false,
873
-                    'default'  => EEM_Base::caps_read,
874
-                    'type'     => 'string',
875
-                    'enum'     => array(
876
-                        EEM_Base::caps_read,
877
-                        EEM_Base::caps_read_admin,
878
-                        EEM_Base::caps_edit,
879
-                        EEM_Base::caps_delete,
880
-                    ),
881
-                ),
882
-            )
883
-        );
884
-    }
885
-
886
-
887
-    /**
888
-     * Gets parameter information for a model regarding writing data
889
-     *
890
-     * @param string           $model_name
891
-     * @param ModelVersionInfo $model_version_info
892
-     * @param boolean          $create                                       whether this is for request to create (in
893
-     *                                                                       which case we need all required params) or
894
-     *                                                                       just to update (in which case we don't
895
-     *                                                                       need those on every request)
896
-     * @return array
897
-     */
898
-    protected function _get_write_params(
899
-        $model_name,
900
-        ModelVersionInfo $model_version_info,
901
-        $create = false
902
-    ) {
903
-        $model = EE_Registry::instance()->load_model($model_name);
904
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
905
-        $args_info = array();
906
-        foreach ($fields as $field_name => $field_obj) {
907
-            if ($field_obj->is_auto_increment()) {
908
-                // totally ignore auto increment IDs
909
-                continue;
910
-            }
911
-            $arg_info = $field_obj->getSchema();
912
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
913
-            $arg_info['required'] = $required;
914
-            // remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
915
-            unset($arg_info['readonly']);
916
-            $schema_properties = $field_obj->getSchemaProperties();
917
-            if (isset($schema_properties['raw'])
918
-                && $field_obj->getSchemaType() === 'object'
919
-            ) {
920
-                // if there's a "raw" form of this argument, use those properties instead
921
-                $arg_info = array_replace(
922
-                    $arg_info,
923
-                    $schema_properties['raw']
924
-                );
925
-            }
926
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
927
-                $field_obj,
928
-                $field_obj->get_default_value(),
929
-                $model_version_info->requestedVersion()
930
-            );
931
-            // we do our own validation and sanitization within the controller
932
-            if (function_exists('rest_validate_value_from_schema')) {
933
-                $sanitize_callback = array(
934
-                    'EED_Core_Rest_Api',
935
-                    'default_sanitize_callback',
936
-                );
937
-            } else {
938
-                $sanitize_callback = null;
939
-            }
940
-            $arg_info['sanitize_callback'] = $sanitize_callback;
941
-            $args_info[ $field_name ] = $arg_info;
942
-            if ($field_obj instanceof EE_Datetime_Field) {
943
-                $gmt_arg_info = $arg_info;
944
-                $gmt_arg_info['description'] = sprintf(
945
-                    esc_html__(
946
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
947
-                        'event_espresso'
948
-                    ),
949
-                    $field_obj->get_nicename(),
950
-                    $field_name
951
-                );
952
-                $args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
953
-            }
954
-        }
955
-        return $args_info;
956
-    }
957
-
958
-
959
-    /**
960
-     * Replacement for WP API's 'rest_parse_request_arg'.
961
-     * If the value is blank but not required, don't bother validating it.
962
-     * Also, it uses our email validation instead of WP API's default.
963
-     *
964
-     * @param                 $value
965
-     * @param WP_REST_Request $request
966
-     * @param                 $param
967
-     * @return bool|true|WP_Error
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidInterfaceException
970
-     * @throws InvalidDataTypeException
971
-     */
972
-    public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
973
-    {
974
-        $attributes = $request->get_attributes();
975
-        if (! isset($attributes['args'][ $param ])
976
-            || ! is_array($attributes['args'][ $param ])) {
977
-            $validation_result = true;
978
-        } else {
979
-            $args = $attributes['args'][ $param ];
980
-            if ((
981
-                    $value === ''
982
-                    || $value === null
983
-                )
984
-                && (! isset($args['required'])
985
-                    || $args['required'] === false
986
-                )
987
-            ) {
988
-                // not required and not provided? that's cool
989
-                $validation_result = true;
990
-            } elseif (isset($args['format'])
991
-                      && $args['format'] === 'email'
992
-            ) {
993
-                $validation_result = true;
994
-                if (! self::_validate_email($value)) {
995
-                    $validation_result = new WP_Error(
996
-                        'rest_invalid_param',
997
-                        esc_html__(
998
-                            'The email address is not valid or does not exist.',
999
-                            'event_espresso'
1000
-                        )
1001
-                    );
1002
-                }
1003
-            } else {
1004
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
1005
-            }
1006
-        }
1007
-        if (is_wp_error($validation_result)) {
1008
-            return $validation_result;
1009
-        }
1010
-        return rest_sanitize_request_arg($value, $request, $param);
1011
-    }
1012
-
1013
-
1014
-    /**
1015
-     * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1016
-     *
1017
-     * @param $email
1018
-     * @return bool
1019
-     * @throws InvalidArgumentException
1020
-     * @throws InvalidInterfaceException
1021
-     * @throws InvalidDataTypeException
1022
-     */
1023
-    protected static function _validate_email($email)
1024
-    {
1025
-        try {
1026
-            EmailAddressFactory::create($email);
1027
-            return true;
1028
-        } catch (EmailValidationException $e) {
1029
-            return false;
1030
-        }
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * Gets routes for the config
1036
-     *
1037
-     * @return array @see _register_model_routes
1038
-     * @deprecated since version 4.9.1
1039
-     */
1040
-    protected function _register_config_routes()
1041
-    {
1042
-        $config_routes = array();
1043
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1044
-            $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1045
-                $version,
1046
-                $hidden_endpoint
1047
-            );
1048
-        }
1049
-        return $config_routes;
1050
-    }
1051
-
1052
-
1053
-    /**
1054
-     * Gets routes for the config for the specified version
1055
-     *
1056
-     * @param string  $version
1057
-     * @param boolean $hidden_endpoint
1058
-     * @return array
1059
-     */
1060
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1061
-    {
1062
-        return array(
1063
-            'config'    => array(
1064
-                array(
1065
-                    'callback'        => array(
1066
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1067
-                        'handleRequest',
1068
-                    ),
1069
-                    'methods'         => WP_REST_Server::READABLE,
1070
-                    'hidden_endpoint' => $hidden_endpoint,
1071
-                    'callback_args'   => array($version),
1072
-                ),
1073
-            ),
1074
-            'site_info' => array(
1075
-                array(
1076
-                    'callback'        => array(
1077
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1078
-                        'handleRequestSiteInfo',
1079
-                    ),
1080
-                    'methods'         => WP_REST_Server::READABLE,
1081
-                    'hidden_endpoint' => $hidden_endpoint,
1082
-                    'callback_args'   => array($version),
1083
-                ),
1084
-            ),
1085
-        );
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     * Gets the meta info routes
1091
-     *
1092
-     * @return array @see _register_model_routes
1093
-     * @deprecated since version 4.9.1
1094
-     */
1095
-    protected function _register_meta_routes()
1096
-    {
1097
-        $meta_routes = array();
1098
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1099
-            $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1100
-                $version,
1101
-                $hidden_endpoint
1102
-            );
1103
-        }
1104
-        return $meta_routes;
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * @param string  $version
1110
-     * @param boolean $hidden_endpoint
1111
-     * @return array
1112
-     */
1113
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1114
-    {
1115
-        return array(
1116
-            'resources' => array(
1117
-                array(
1118
-                    'callback'        => array(
1119
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1120
-                        'handleRequestModelsMeta',
1121
-                    ),
1122
-                    'methods'         => WP_REST_Server::READABLE,
1123
-                    'hidden_endpoint' => $hidden_endpoint,
1124
-                    'callback_args'   => array($version),
1125
-                ),
1126
-            ),
1127
-        );
1128
-    }
1129
-
1130
-
1131
-    /**
1132
-     * Tries to hide old 4.6 endpoints from the
1133
-     *
1134
-     * @param array $route_data
1135
-     * @return array
1136
-     * @throws \EE_Error
1137
-     */
1138
-    public static function hide_old_endpoints($route_data)
1139
-    {
1140
-        // allow API clients to override which endpoints get hidden, in case
1141
-        // they want to discover particular endpoints
1142
-        // also, we don't have access to the request so we have to just grab it from the superglobal
1143
-        $force_show_ee_namespace = ltrim(
1144
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1145
-            '/'
1146
-        );
1147
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1148
-            foreach ($relative_urls as $resource_name => $endpoints) {
1149
-                foreach ($endpoints as $key => $endpoint) {
1150
-                    // skip schema and other route options
1151
-                    if (! is_numeric($key)) {
1152
-                        continue;
1153
-                    }
1154
-                    // by default, hide "hidden_endpoint"s, unless the request indicates
1155
-                    // to $force_show_ee_namespace, in which case only show that one
1156
-                    // namespace's endpoints (and hide all others)
1157
-                    if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1158
-                        || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1159
-                    ) {
1160
-                        $full_route = '/' . ltrim($namespace, '/');
1161
-                        $full_route .= '/' . ltrim($resource_name, '/');
1162
-                        unset($route_data[ $full_route ]);
1163
-                    }
1164
-                }
1165
-            }
1166
-        }
1167
-        return $route_data;
1168
-    }
1169
-
1170
-
1171
-    /**
1172
-     * Returns an array describing which versions of core support serving requests for.
1173
-     * Keys are core versions' major and minor version, and values are the
1174
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1175
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1176
-     * the answers table entirely, in which case it would be very difficult for
1177
-     * it to serve 4.6-style responses.
1178
-     * Versions of core that are missing from this array are unknowns.
1179
-     * previous ver
1180
-     *
1181
-     * @return array
1182
-     */
1183
-    public static function version_compatibilities()
1184
-    {
1185
-        return apply_filters(
1186
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1187
-            array(
1188
-                '4.8.29' => '4.8.29',
1189
-                '4.8.33' => '4.8.29',
1190
-                '4.8.34' => '4.8.29',
1191
-                '4.8.36' => '4.8.29',
1192
-            )
1193
-        );
1194
-    }
1195
-
1196
-
1197
-    /**
1198
-     * Gets the latest API version served. Eg if there
1199
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1200
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1201
-     *
1202
-     * @return string
1203
-     */
1204
-    public static function latest_rest_api_version()
1205
-    {
1206
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1207
-        $versions_served_keys = array_keys($versions_served);
1208
-        return end($versions_served_keys);
1209
-    }
1210
-
1211
-
1212
-    /**
1213
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1214
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1215
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1216
-     * We also indicate whether or not this version should be put in the index or not
1217
-     *
1218
-     * @return array keys are API version numbers (just major and minor numbers), and values
1219
-     * are whether or not they should be hidden
1220
-     */
1221
-    public static function versions_served()
1222
-    {
1223
-        $versions_served = array();
1224
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1225
-        $lowest_compatible_version = end($possibly_served_versions);
1226
-        reset($possibly_served_versions);
1227
-        $versions_served_historically = array_keys($possibly_served_versions);
1228
-        $latest_version = end($versions_served_historically);
1229
-        reset($versions_served_historically);
1230
-        // for each version of core we have ever served:
1231
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1232
-            // if it's not above the current core version, and it's compatible with the current version of core
1233
-
1234
-            if ($key_versioned_endpoint === $latest_version) {
1235
-                // don't hide the latest version in the index
1236
-                $versions_served[ $key_versioned_endpoint ] = false;
1237
-            } elseif (version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1238
-                && version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1239
-            ) {
1240
-                // include, but hide, previous versions which are still supported
1241
-                $versions_served[ $key_versioned_endpoint ] = true;
1242
-            } elseif (apply_filters(
1243
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1244
-                false,
1245
-                $possibly_served_versions
1246
-            )) {
1247
-                // if a version is no longer supported, don't include it in index or list of versions served
1248
-                $versions_served[ $key_versioned_endpoint ] = true;
1249
-            }
1250
-        }
1251
-        return $versions_served;
1252
-    }
1253
-
1254
-
1255
-    /**
1256
-     * Gets the major and minor version of EE core's version string
1257
-     *
1258
-     * @return string
1259
-     */
1260
-    public static function core_version()
1261
-    {
1262
-        return apply_filters(
1263
-            'FHEE__EED_Core_REST_API__core_version',
1264
-            implode(
1265
-                '.',
1266
-                array_slice(
1267
-                    explode(
1268
-                        '.',
1269
-                        espresso_version()
1270
-                    ),
1271
-                    0,
1272
-                    3
1273
-                )
1274
-            )
1275
-        );
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Gets the default limit that should be used when querying for resources
1281
-     *
1282
-     * @return int
1283
-     */
1284
-    public static function get_default_query_limit()
1285
-    {
1286
-        // we actually don't use a const because we want folks to always use
1287
-        // this method, not the const directly
1288
-        return apply_filters(
1289
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1290
-            50
1291
-        );
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     *
1297
-     * @param string $version api version string (i.e. '4.8.36')
1298
-     * @return array
1299
-     */
1300
-    public static function getCollectionRoutesIndexedByModelName($version = '')
1301
-    {
1302
-        $version = empty($version) ? self::latest_rest_api_version() : $version;
1303
-        $model_names = self::model_names_with_plural_routes($version);
1304
-        $collection_routes = array();
1305
-        foreach ($model_names as $model_name => $model_class_name) {
1306
-            $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1307
-                                                            . EEH_Inflector::pluralize_and_lower($model_name);
1308
-        }
1309
-        return $collection_routes;
1310
-    }
1311
-
1312
-
1313
-    /**
1314
-     * Returns an array of primary key names indexed by model names.
1315
-     * @param string $version
1316
-     * @return array
1317
-     */
1318
-    public static function getPrimaryKeyNamesIndexedByModelName($version = '')
1319
-    {
1320
-        $version = empty($version) ? self::latest_rest_api_version() : $version;
1321
-        $model_names = self::model_names_with_plural_routes($version);
1322
-        $primary_key_items = array();
1323
-        foreach ($model_names as $model_name => $model_class_name) {
1324
-            $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1325
-            foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1326
-                if (count($primary_keys) > 1) {
1327
-                    $primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1328
-                } else {
1329
-                    $primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1330
-                }
1331
-            }
1332
-        }
1333
-        return $primary_key_items;
1334
-    }
1335
-
1336
-    /**
1337
-     * Determines the EE REST API debug mode is activated, or not.
1338
-     * @since 4.9.76.p
1339
-     * @return bool
1340
-     */
1341
-    public static function debugMode()
1342
-    {
1343
-        static $debug_mode = null; // could be class prop
1344
-        if ($debug_mode === null) {
1345
-            $debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE;
1346
-        }
1347
-        return $debug_mode;
1348
-    }
1349
-
1350
-
1351
-
1352
-    /**
1353
-     *    run - initial module setup
1354
-     *
1355
-     * @access    public
1356
-     * @param  WP $WP
1357
-     * @return    void
1358
-     */
1359
-    public function run($WP)
1360
-    {
1361
-    }
26
+	const ee_api_namespace = Domain::API_NAMESPACE;
27
+
28
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
29
+
30
+	const saved_routes_option_names = 'ee_core_routes';
31
+
32
+	/**
33
+	 * string used in _links response bodies to make them globally unique.
34
+	 *
35
+	 * @see http://v2.wp-api.org/extending/linking/
36
+	 */
37
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
38
+
39
+	/**
40
+	 * @var CalculatedModelFields
41
+	 */
42
+	protected static $_field_calculator;
43
+
44
+
45
+	/**
46
+	 * @return EED_Core_Rest_Api|EED_Module
47
+	 */
48
+	public static function instance()
49
+	{
50
+		self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields');
51
+		return parent::get_instance(__CLASS__);
52
+	}
53
+
54
+
55
+	/**
56
+	 *    set_hooks - for hooking into EE Core, other modules, etc
57
+	 *
58
+	 * @access    public
59
+	 * @return    void
60
+	 */
61
+	public static function set_hooks()
62
+	{
63
+		self::set_hooks_both();
64
+	}
65
+
66
+
67
+	/**
68
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
+	 *
70
+	 * @access    public
71
+	 * @return    void
72
+	 */
73
+	public static function set_hooks_admin()
74
+	{
75
+		self::set_hooks_both();
76
+	}
77
+
78
+
79
+	public static function set_hooks_both()
80
+	{
81
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
82
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
84
+		add_filter(
85
+			'rest_index',
86
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex')
87
+		);
88
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
89
+	}
90
+
91
+
92
+	/**
93
+	 * sets up hooks which only need to be included as part of REST API requests;
94
+	 * other requests like to the frontend or admin etc don't need them
95
+	 *
96
+	 * @throws \EE_Error
97
+	 */
98
+	public static function set_hooks_rest_api()
99
+	{
100
+		// set hooks which account for changes made to the API
101
+		EED_Core_Rest_Api::_set_hooks_for_changes();
102
+	}
103
+
104
+
105
+	/**
106
+	 * public wrapper of _set_hooks_for_changes.
107
+	 * Loads all the hooks which make requests to old versions of the API
108
+	 * appear the same as they always did
109
+	 *
110
+	 * @throws EE_Error
111
+	 */
112
+	public static function set_hooks_for_changes()
113
+	{
114
+		self::_set_hooks_for_changes();
115
+	}
116
+
117
+
118
+	/**
119
+	 * Loads all the hooks which make requests to old versions of the API
120
+	 * appear the same as they always did
121
+	 *
122
+	 * @throws EE_Error
123
+	 */
124
+	protected static function _set_hooks_for_changes()
125
+	{
126
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
127
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
128
+			// ignore the base parent class
129
+			// and legacy named classes
130
+			if ($classname_in_namespace === 'ChangesInBase'
131
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
132
+			) {
133
+				continue;
134
+			}
135
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
136
+			if (class_exists($full_classname)) {
137
+				$instance_of_class = new $full_classname;
138
+				if ($instance_of_class instanceof ChangesInBase) {
139
+					$instance_of_class->setHooks();
140
+				}
141
+			}
142
+		}
143
+	}
144
+
145
+
146
+	/**
147
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
148
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
149
+	 *
150
+	 * @throws \EE_Error
151
+	 */
152
+	public static function register_routes()
153
+	{
154
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
155
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
156
+				/**
157
+				 * @var array     $data_for_multiple_endpoints numerically indexed array
158
+				 *                                         but can also contain route options like {
159
+				 * @type array    $schema                      {
160
+				 * @type callable $schema_callback
161
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
162
+				 * WP_REST_Request of course
163
+				 * }
164
+				 * }
165
+				 */
166
+				// when registering routes, register all the endpoints' data at the same time
167
+				$multiple_endpoint_args = array();
168
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
169
+					/**
170
+					 * @var array     $data_for_single_endpoint {
171
+					 * @type callable $callback
172
+					 * @type string methods
173
+					 * @type array args
174
+					 * @type array _links
175
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
176
+					 * WP_REST_Request of course
177
+					 * }
178
+					 */
179
+					// skip route options
180
+					if (! is_numeric($endpoint_key)) {
181
+						continue;
182
+					}
183
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184
+						throw new EE_Error(
185
+							esc_html__(
186
+							// @codingStandardsIgnoreStart
187
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
188
+								// @codingStandardsIgnoreEnd
189
+								'event_espresso'
190
+							)
191
+						);
192
+					}
193
+					$callback = $data_for_single_endpoint['callback'];
194
+					$single_endpoint_args = array(
195
+						'methods' => $data_for_single_endpoint['methods'],
196
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
197
+							: array(),
198
+					);
199
+					if (isset($data_for_single_endpoint['_links'])) {
200
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
201
+					}
202
+					if (isset($data_for_single_endpoint['callback_args'])) {
203
+						$callback_args = $data_for_single_endpoint['callback_args'];
204
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
205
+							$callback,
206
+							$callback_args
207
+						) {
208
+							array_unshift($callback_args, $request);
209
+							return call_user_func_array(
210
+								$callback,
211
+								$callback_args
212
+							);
213
+						};
214
+					} else {
215
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
216
+					}
217
+					// As of WordPress 5.5, if a permission_callback is not provided,
218
+					// the REST API will issue a _doing_it_wrong notice.
219
+					// Since the EE REST API defers capabilities to the db model system,
220
+					// we will just use the generic WP callback for public endpoints
221
+					if (! isset($single_endpoint_args['permission_callback'])) {
222
+						$single_endpoint_args['permission_callback'] = '__return_true';
223
+					}
224
+					$multiple_endpoint_args[] = $single_endpoint_args;
225
+				}
226
+				if (isset($data_for_multiple_endpoints['schema'])) {
227
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
228
+					$schema_callback = $schema_route_data['schema_callback'];
229
+					$callback_args = $schema_route_data['callback_args'];
230
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
231
+						return call_user_func_array(
232
+							$schema_callback,
233
+							$callback_args
234
+						);
235
+					};
236
+				}
237
+				register_rest_route(
238
+					$namespace,
239
+					$relative_route,
240
+					$multiple_endpoint_args
241
+				);
242
+			}
243
+		}
244
+	}
245
+
246
+
247
+	/**
248
+	 * Checks if there was a version change or something that merits invalidating the cached
249
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
250
+	 * next time the WP API is used
251
+	 */
252
+	public static function invalidate_cached_route_data_on_version_change()
253
+	{
254
+		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
255
+			EED_Core_Rest_Api::invalidate_cached_route_data();
256
+		}
257
+		foreach (EE_Registry::instance()->addons as $addon) {
258
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
259
+				EED_Core_Rest_Api::invalidate_cached_route_data();
260
+			}
261
+		}
262
+	}
263
+
264
+
265
+	/**
266
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
267
+	 */
268
+	public static function invalidate_cached_route_data()
269
+	{
270
+		// delete the saved EE REST API routes
271
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
272
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
273
+		}
274
+	}
275
+
276
+
277
+	/**
278
+	 * Gets the EE route data
279
+	 *
280
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
281
+	 * @throws \EE_Error
282
+	 * @type string|array $callback
283
+	 * @type string       $methods
284
+	 * @type boolean      $hidden_endpoint
285
+	 * }
286
+	 */
287
+	public static function get_ee_route_data()
288
+	{
289
+		$ee_routes = array();
290
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
291
+			$ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
292
+				$version,
293
+				$hidden_endpoints
294
+			);
295
+		}
296
+		return $ee_routes;
297
+	}
298
+
299
+
300
+	/**
301
+	 * Gets the EE route data from the wp options if it exists already,
302
+	 * otherwise re-generates it and saves it to the option
303
+	 *
304
+	 * @param string  $version
305
+	 * @param boolean $hidden_endpoints
306
+	 * @return array
307
+	 * @throws \EE_Error
308
+	 */
309
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
310
+	{
311
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
312
+		if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
313
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
314
+		}
315
+		return $ee_routes;
316
+	}
317
+
318
+
319
+	/**
320
+	 * Saves the EE REST API route data to a wp option and returns it
321
+	 *
322
+	 * @param string  $version
323
+	 * @param boolean $hidden_endpoints
324
+	 * @return mixed|null
325
+	 * @throws \EE_Error
326
+	 */
327
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
328
+	{
329
+		$instance = self::instance();
330
+		$routes = apply_filters(
331
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
332
+			array_replace_recursive(
333
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
334
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
335
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
336
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
337
+			)
338
+		);
339
+		$option_name = self::saved_routes_option_names . $version;
340
+		if (get_option($option_name)) {
341
+			update_option($option_name, $routes, true);
342
+		} else {
343
+			add_option($option_name, $routes, null, 'no');
344
+		}
345
+		return $routes;
346
+	}
347
+
348
+
349
+	/**
350
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
351
+	 * need to calculate it on every request
352
+	 *
353
+	 * @deprecated since version 4.9.1
354
+	 * @return void
355
+	 */
356
+	public static function save_ee_routes()
357
+	{
358
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
359
+			$instance = self::instance();
360
+			$routes = apply_filters(
361
+				'EED_Core_Rest_Api__save_ee_routes__routes',
362
+				array_replace_recursive(
363
+					$instance->_register_config_routes(),
364
+					$instance->_register_meta_routes(),
365
+					$instance->_register_model_routes(),
366
+					$instance->_register_rpc_routes()
367
+				)
368
+			);
369
+			update_option(self::saved_routes_option_names, $routes, true);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Gets all the route information relating to EE models
376
+	 *
377
+	 * @return array @see get_ee_route_data
378
+	 * @deprecated since version 4.9.1
379
+	 */
380
+	protected function _register_model_routes()
381
+	{
382
+		$model_routes = array();
383
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
384
+			$model_routes[ EED_Core_Rest_Api::ee_api_namespace
385
+						   . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
386
+		}
387
+		return $model_routes;
388
+	}
389
+
390
+
391
+	/**
392
+	 * Decides whether or not to add write endpoints for this model.
393
+	 *
394
+	 * Currently, this defaults to exclude all global tables and models
395
+	 * which would allow inserting WP core data (we don't want to duplicate
396
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
397
+	 *
398
+	 * @param EEM_Base $model
399
+	 * @return bool
400
+	 */
401
+	public static function should_have_write_endpoints(EEM_Base $model)
402
+	{
403
+		if ($model->is_wp_core_model()) {
404
+			return false;
405
+		}
406
+		foreach ($model->get_tables() as $table) {
407
+			if ($table->is_global()) {
408
+				return false;
409
+			}
410
+		}
411
+		return true;
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
417
+	 * in this versioned namespace of EE4
418
+	 *
419
+	 * @param $version
420
+	 * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
421
+	 */
422
+	public static function model_names_with_plural_routes($version)
423
+	{
424
+		$model_version_info = new ModelVersionInfo($version);
425
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
426
+		// let's not bother having endpoints for extra metas
427
+		unset(
428
+			$models_to_register['Extra_Meta'],
429
+			$models_to_register['Extra_Join'],
430
+			$models_to_register['Post_Meta']
431
+		);
432
+		return apply_filters(
433
+			'FHEE__EED_Core_REST_API___register_model_routes',
434
+			$models_to_register
435
+		);
436
+	}
437
+
438
+
439
+	/**
440
+	 * Gets the route data for EE models in the specified version
441
+	 *
442
+	 * @param string  $version
443
+	 * @param boolean $hidden_endpoint
444
+	 * @return array
445
+	 * @throws EE_Error
446
+	 */
447
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
448
+	{
449
+		$model_routes = array();
450
+		$model_version_info = new ModelVersionInfo($version);
451
+		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
452
+			$model = \EE_Registry::instance()->load_model($model_name);
453
+			// if this isn't a valid model then let's skip iterate to the next item in the loop.
454
+			if (! $model instanceof EEM_Base) {
455
+				continue;
456
+			}
457
+			// yes we could just register one route for ALL models, but then they wouldn't show up in the index
458
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
459
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
460
+			$model_routes[ $plural_model_route ] = array(
461
+				array(
462
+					'callback'        => array(
463
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
464
+						'handleRequestGetAll',
465
+					),
466
+					'callback_args'   => array($version, $model_name),
467
+					'methods'         => WP_REST_Server::READABLE,
468
+					'hidden_endpoint' => $hidden_endpoint,
469
+					'args'            => $this->_get_read_query_params($model, $version),
470
+					'_links'          => array(
471
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
472
+					),
473
+				),
474
+				'schema' => array(
475
+					'schema_callback' => array(
476
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
477
+						'handleSchemaRequest',
478
+					),
479
+					'callback_args'   => array($version, $model_name),
480
+				),
481
+			);
482
+			$model_routes[ $singular_model_route ] = array(
483
+				array(
484
+					'callback'        => array(
485
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
486
+						'handleRequestGetOne',
487
+					),
488
+					'callback_args'   => array($version, $model_name),
489
+					'methods'         => WP_REST_Server::READABLE,
490
+					'hidden_endpoint' => $hidden_endpoint,
491
+					'args'            => $this->_get_response_selection_query_params($model, $version, true),
492
+				),
493
+			);
494
+			if (apply_filters(
495
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
496
+				EED_Core_Rest_Api::should_have_write_endpoints($model),
497
+				$model
498
+			)) {
499
+				$model_routes[ $plural_model_route ][] = array(
500
+					'callback'        => array(
501
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
502
+						'handleRequestInsert',
503
+					),
504
+					'callback_args'   => array($version, $model_name),
505
+					'methods'         => WP_REST_Server::CREATABLE,
506
+					'hidden_endpoint' => $hidden_endpoint,
507
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
508
+				);
509
+				$model_routes[ $singular_model_route ] = array_merge(
510
+					$model_routes[ $singular_model_route ],
511
+					array(
512
+						array(
513
+							'callback'        => array(
514
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
515
+								'handleRequestUpdate',
516
+							),
517
+							'callback_args'   => array($version, $model_name),
518
+							'methods'         => WP_REST_Server::EDITABLE,
519
+							'hidden_endpoint' => $hidden_endpoint,
520
+							'args'            => $this->_get_write_params($model_name, $model_version_info),
521
+						),
522
+						array(
523
+							'callback'        => array(
524
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
525
+								'handleRequestDelete',
526
+							),
527
+							'callback_args'   => array($version, $model_name),
528
+							'methods'         => WP_REST_Server::DELETABLE,
529
+							'hidden_endpoint' => $hidden_endpoint,
530
+							'args'            => $this->_get_delete_query_params($model, $version),
531
+						),
532
+					)
533
+				);
534
+			}
535
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
536
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
537
+					$model,
538
+					'(?P<id>[^\/]+)',
539
+					$relation_obj
540
+				);
541
+				$model_routes[ $related_route ] = array(
542
+					array(
543
+						'callback'        => array(
544
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
545
+							'handleRequestGetRelated',
546
+						),
547
+						'callback_args'   => array($version, $model_name, $relation_name),
548
+						'methods'         => WP_REST_Server::READABLE,
549
+						'hidden_endpoint' => $hidden_endpoint,
550
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
551
+					),
552
+				);
553
+
554
+				$related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
555
+				$model_routes[ $related_write_route ] = array(
556
+					array(
557
+						'callback'        => array(
558
+							'EventEspresso\core\libraries\rest_api\controllers\model\Write',
559
+							'handleRequestAddRelation',
560
+						),
561
+						'callback_args'   => array($version, $model_name, $relation_name),
562
+						'methods'         => WP_REST_Server::EDITABLE,
563
+						'hidden_endpoint' => $hidden_endpoint,
564
+						'args'            => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version)
565
+					),
566
+					array(
567
+						'callback'        => array(
568
+							'EventEspresso\core\libraries\rest_api\controllers\model\Write',
569
+							'handleRequestRemoveRelation',
570
+						),
571
+						'callback_args'   => array($version, $model_name, $relation_name),
572
+						'methods'         => WP_REST_Server::DELETABLE,
573
+						'hidden_endpoint' => $hidden_endpoint,
574
+						'args'            => array()
575
+					),
576
+				);
577
+			}
578
+		}
579
+		return $model_routes;
580
+	}
581
+
582
+
583
+	/**
584
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
585
+	 * excluding the preceding slash.
586
+	 * Eg you pass get_plural_route_to('Event') = 'events'
587
+	 *
588
+	 * @param EEM_Base $model
589
+	 * @return string
590
+	 */
591
+	public static function get_collection_route(EEM_Base $model)
592
+	{
593
+		return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
594
+	}
595
+
596
+
597
+	/**
598
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
599
+	 * excluding the preceding slash.
600
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
601
+	 *
602
+	 * @param EEM_Base $model eg Event or Venue
603
+	 * @param string   $id
604
+	 * @return string
605
+	 */
606
+	public static function get_entity_route($model, $id)
607
+	{
608
+		return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
609
+	}
610
+
611
+
612
+	/**
613
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
614
+	 * excluding the preceding slash.
615
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
616
+	 *
617
+	 * @param EEM_Base               $model eg Event or Venue
618
+	 * @param string                 $id
619
+	 * @param EE_Model_Relation_Base $relation_obj
620
+	 * @return string
621
+	 */
622
+	public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
623
+	{
624
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
625
+			$relation_obj->get_other_model()->get_this_model_name(),
626
+			$relation_obj
627
+		);
628
+		return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
629
+	}
630
+
631
+
632
+	/**
633
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
634
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
635
+	 *
636
+	 * @param string $relative_route
637
+	 * @param string $version
638
+	 * @return string
639
+	 */
640
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36')
641
+	{
642
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
643
+	}
644
+
645
+
646
+	/**
647
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
648
+	 * routes that don't conform to the traditional REST CRUD-style).
649
+	 *
650
+	 * @deprecated since 4.9.1
651
+	 */
652
+	protected function _register_rpc_routes()
653
+	{
654
+		$routes = array();
655
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
656
+			$routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
657
+				$version,
658
+				$hidden_endpoint
659
+			);
660
+		}
661
+		return $routes;
662
+	}
663
+
664
+
665
+	/**
666
+	 * @param string  $version
667
+	 * @param boolean $hidden_endpoint
668
+	 * @return array
669
+	 */
670
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
671
+	{
672
+		$this_versions_routes = array();
673
+		// checkin endpoint
674
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
675
+			array(
676
+				'callback'        => array(
677
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
678
+					'handleRequestToggleCheckin',
679
+				),
680
+				'methods'         => WP_REST_Server::CREATABLE,
681
+				'hidden_endpoint' => $hidden_endpoint,
682
+				'args'            => array(
683
+					'force' => array(
684
+						'required'    => false,
685
+						'default'     => false,
686
+						'description' => __(
687
+						// @codingStandardsIgnoreStart
688
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
689
+							// @codingStandardsIgnoreEnd
690
+							'event_espresso'
691
+						),
692
+					),
693
+				),
694
+				'callback_args'   => array($version),
695
+			),
696
+		);
697
+		return apply_filters(
698
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
699
+			$this_versions_routes,
700
+			$version,
701
+			$hidden_endpoint
702
+		);
703
+	}
704
+
705
+
706
+	/**
707
+	 * Gets the query params that can be used when request one or many
708
+	 *
709
+	 * @param EEM_Base $model
710
+	 * @param string   $version
711
+	 * @return array
712
+	 */
713
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false)
714
+	{
715
+		$query_params = array(
716
+			'include'   => array(
717
+				'required' => false,
718
+				'default'  => '*',
719
+				'type'     => 'string',
720
+			),
721
+			'calculate' => array(
722
+				'required'          => false,
723
+				'default'           => '',
724
+				'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
725
+				'type'              => 'string',
726
+				// because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
727
+				// freaks out. We'll just validate this argument while handling the request
728
+				'validate_callback' => null,
729
+				'sanitize_callback' => null,
730
+			),
731
+			'password' => array(
732
+				'required' => false,
733
+				'default' => '',
734
+				'type' => 'string'
735
+			)
736
+		);
737
+		return apply_filters(
738
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
739
+			$query_params,
740
+			$model,
741
+			$version
742
+		);
743
+	}
744
+
745
+
746
+	/**
747
+	 * Gets the parameters acceptable for delete requests
748
+	 *
749
+	 * @param \EEM_Base $model
750
+	 * @param string    $version
751
+	 * @return array
752
+	 */
753
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
754
+	{
755
+		$params_for_delete = array(
756
+			'allow_blocking' => array(
757
+				'required' => false,
758
+				'default'  => true,
759
+				'type'     => 'boolean',
760
+			),
761
+		);
762
+		$params_for_delete['force'] = array(
763
+			'required' => false,
764
+			'default'  => false,
765
+			'type'     => 'boolean',
766
+		);
767
+		return apply_filters(
768
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
769
+			$params_for_delete,
770
+			$model,
771
+			$version
772
+		);
773
+	}
774
+
775
+	protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
776
+	{
777
+		// if they're related through a HABTM relation, check for any non-FKs
778
+		$all_relation_settings = $source_model->relation_settings();
779
+		$relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
780
+		$params = array();
781
+		if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
782
+			foreach ($relation_settings->getNonKeyFields() as $field) {
783
+				/* @var $field EE_Model_Field_Base */
784
+				$params[ $field->get_name() ] = array(
785
+					'required' => ! $field->is_nullable(),
786
+					'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
787
+					'type' => $field->getSchemaType(),
788
+					'validate_callbaack' => null,
789
+					'sanitize_callback' => null
790
+				);
791
+			}
792
+		}
793
+		return $params;
794
+	}
795
+
796
+
797
+	/**
798
+	 * Gets info about reading query params that are acceptable
799
+	 *
800
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
801
+	 * @param  string   $version
802
+	 * @return array    describing the args acceptable when querying this model
803
+	 * @throws EE_Error
804
+	 */
805
+	protected function _get_read_query_params(\EEM_Base $model, $version)
806
+	{
807
+		$default_orderby = array();
808
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
809
+			$default_orderby[ $key_field->get_name() ] = 'ASC';
810
+		}
811
+		return array_merge(
812
+			$this->_get_response_selection_query_params($model, $version),
813
+			array(
814
+				'where'    => array(
815
+					'required'          => false,
816
+					'default'           => array(),
817
+					'type'              => 'object',
818
+					// because we accept an almost infinite list of possible where conditions, WP
819
+					// core validation and sanitization freaks out. We'll just validate this argument
820
+					// while handling the request
821
+					'validate_callback' => null,
822
+					'sanitize_callback' => null,
823
+				),
824
+				'limit'    => array(
825
+					'required'          => false,
826
+					'default'           => EED_Core_Rest_Api::get_default_query_limit(),
827
+					'type'              => array(
828
+						'array',
829
+						'string',
830
+						'integer',
831
+					),
832
+					// because we accept a variety of types, WP core validation and sanitization
833
+					// freaks out. We'll just validate this argument while handling the request
834
+					'validate_callback' => null,
835
+					'sanitize_callback' => null,
836
+				),
837
+				'order_by' => array(
838
+					'required'          => false,
839
+					'default'           => $default_orderby,
840
+					'type'              => array(
841
+						'object',
842
+						'string',
843
+					),// because we accept a variety of types, WP core validation and sanitization
844
+					// freaks out. We'll just validate this argument while handling the request
845
+					'validate_callback' => null,
846
+					'sanitize_callback' => null,
847
+				),
848
+				'group_by' => array(
849
+					'required'          => false,
850
+					'default'           => null,
851
+					'type'              => array(
852
+						'object',
853
+						'string',
854
+					),
855
+					// because we accept  an almost infinite list of possible groupings,
856
+					// WP core validation and sanitization
857
+					// freaks out. We'll just validate this argument while handling the request
858
+					'validate_callback' => null,
859
+					'sanitize_callback' => null,
860
+				),
861
+				'having'   => array(
862
+					'required'          => false,
863
+					'default'           => null,
864
+					'type'              => 'object',
865
+					// because we accept an almost infinite list of possible where conditions, WP
866
+					// core validation and sanitization freaks out. We'll just validate this argument
867
+					// while handling the request
868
+					'validate_callback' => null,
869
+					'sanitize_callback' => null,
870
+				),
871
+				'caps'     => array(
872
+					'required' => false,
873
+					'default'  => EEM_Base::caps_read,
874
+					'type'     => 'string',
875
+					'enum'     => array(
876
+						EEM_Base::caps_read,
877
+						EEM_Base::caps_read_admin,
878
+						EEM_Base::caps_edit,
879
+						EEM_Base::caps_delete,
880
+					),
881
+				),
882
+			)
883
+		);
884
+	}
885
+
886
+
887
+	/**
888
+	 * Gets parameter information for a model regarding writing data
889
+	 *
890
+	 * @param string           $model_name
891
+	 * @param ModelVersionInfo $model_version_info
892
+	 * @param boolean          $create                                       whether this is for request to create (in
893
+	 *                                                                       which case we need all required params) or
894
+	 *                                                                       just to update (in which case we don't
895
+	 *                                                                       need those on every request)
896
+	 * @return array
897
+	 */
898
+	protected function _get_write_params(
899
+		$model_name,
900
+		ModelVersionInfo $model_version_info,
901
+		$create = false
902
+	) {
903
+		$model = EE_Registry::instance()->load_model($model_name);
904
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
905
+		$args_info = array();
906
+		foreach ($fields as $field_name => $field_obj) {
907
+			if ($field_obj->is_auto_increment()) {
908
+				// totally ignore auto increment IDs
909
+				continue;
910
+			}
911
+			$arg_info = $field_obj->getSchema();
912
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
913
+			$arg_info['required'] = $required;
914
+			// remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
915
+			unset($arg_info['readonly']);
916
+			$schema_properties = $field_obj->getSchemaProperties();
917
+			if (isset($schema_properties['raw'])
918
+				&& $field_obj->getSchemaType() === 'object'
919
+			) {
920
+				// if there's a "raw" form of this argument, use those properties instead
921
+				$arg_info = array_replace(
922
+					$arg_info,
923
+					$schema_properties['raw']
924
+				);
925
+			}
926
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
927
+				$field_obj,
928
+				$field_obj->get_default_value(),
929
+				$model_version_info->requestedVersion()
930
+			);
931
+			// we do our own validation and sanitization within the controller
932
+			if (function_exists('rest_validate_value_from_schema')) {
933
+				$sanitize_callback = array(
934
+					'EED_Core_Rest_Api',
935
+					'default_sanitize_callback',
936
+				);
937
+			} else {
938
+				$sanitize_callback = null;
939
+			}
940
+			$arg_info['sanitize_callback'] = $sanitize_callback;
941
+			$args_info[ $field_name ] = $arg_info;
942
+			if ($field_obj instanceof EE_Datetime_Field) {
943
+				$gmt_arg_info = $arg_info;
944
+				$gmt_arg_info['description'] = sprintf(
945
+					esc_html__(
946
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
947
+						'event_espresso'
948
+					),
949
+					$field_obj->get_nicename(),
950
+					$field_name
951
+				);
952
+				$args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
953
+			}
954
+		}
955
+		return $args_info;
956
+	}
957
+
958
+
959
+	/**
960
+	 * Replacement for WP API's 'rest_parse_request_arg'.
961
+	 * If the value is blank but not required, don't bother validating it.
962
+	 * Also, it uses our email validation instead of WP API's default.
963
+	 *
964
+	 * @param                 $value
965
+	 * @param WP_REST_Request $request
966
+	 * @param                 $param
967
+	 * @return bool|true|WP_Error
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws InvalidDataTypeException
971
+	 */
972
+	public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
973
+	{
974
+		$attributes = $request->get_attributes();
975
+		if (! isset($attributes['args'][ $param ])
976
+			|| ! is_array($attributes['args'][ $param ])) {
977
+			$validation_result = true;
978
+		} else {
979
+			$args = $attributes['args'][ $param ];
980
+			if ((
981
+					$value === ''
982
+					|| $value === null
983
+				)
984
+				&& (! isset($args['required'])
985
+					|| $args['required'] === false
986
+				)
987
+			) {
988
+				// not required and not provided? that's cool
989
+				$validation_result = true;
990
+			} elseif (isset($args['format'])
991
+					  && $args['format'] === 'email'
992
+			) {
993
+				$validation_result = true;
994
+				if (! self::_validate_email($value)) {
995
+					$validation_result = new WP_Error(
996
+						'rest_invalid_param',
997
+						esc_html__(
998
+							'The email address is not valid or does not exist.',
999
+							'event_espresso'
1000
+						)
1001
+					);
1002
+				}
1003
+			} else {
1004
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
1005
+			}
1006
+		}
1007
+		if (is_wp_error($validation_result)) {
1008
+			return $validation_result;
1009
+		}
1010
+		return rest_sanitize_request_arg($value, $request, $param);
1011
+	}
1012
+
1013
+
1014
+	/**
1015
+	 * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1016
+	 *
1017
+	 * @param $email
1018
+	 * @return bool
1019
+	 * @throws InvalidArgumentException
1020
+	 * @throws InvalidInterfaceException
1021
+	 * @throws InvalidDataTypeException
1022
+	 */
1023
+	protected static function _validate_email($email)
1024
+	{
1025
+		try {
1026
+			EmailAddressFactory::create($email);
1027
+			return true;
1028
+		} catch (EmailValidationException $e) {
1029
+			return false;
1030
+		}
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * Gets routes for the config
1036
+	 *
1037
+	 * @return array @see _register_model_routes
1038
+	 * @deprecated since version 4.9.1
1039
+	 */
1040
+	protected function _register_config_routes()
1041
+	{
1042
+		$config_routes = array();
1043
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1044
+			$config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1045
+				$version,
1046
+				$hidden_endpoint
1047
+			);
1048
+		}
1049
+		return $config_routes;
1050
+	}
1051
+
1052
+
1053
+	/**
1054
+	 * Gets routes for the config for the specified version
1055
+	 *
1056
+	 * @param string  $version
1057
+	 * @param boolean $hidden_endpoint
1058
+	 * @return array
1059
+	 */
1060
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1061
+	{
1062
+		return array(
1063
+			'config'    => array(
1064
+				array(
1065
+					'callback'        => array(
1066
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1067
+						'handleRequest',
1068
+					),
1069
+					'methods'         => WP_REST_Server::READABLE,
1070
+					'hidden_endpoint' => $hidden_endpoint,
1071
+					'callback_args'   => array($version),
1072
+				),
1073
+			),
1074
+			'site_info' => array(
1075
+				array(
1076
+					'callback'        => array(
1077
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1078
+						'handleRequestSiteInfo',
1079
+					),
1080
+					'methods'         => WP_REST_Server::READABLE,
1081
+					'hidden_endpoint' => $hidden_endpoint,
1082
+					'callback_args'   => array($version),
1083
+				),
1084
+			),
1085
+		);
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 * Gets the meta info routes
1091
+	 *
1092
+	 * @return array @see _register_model_routes
1093
+	 * @deprecated since version 4.9.1
1094
+	 */
1095
+	protected function _register_meta_routes()
1096
+	{
1097
+		$meta_routes = array();
1098
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1099
+			$meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1100
+				$version,
1101
+				$hidden_endpoint
1102
+			);
1103
+		}
1104
+		return $meta_routes;
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * @param string  $version
1110
+	 * @param boolean $hidden_endpoint
1111
+	 * @return array
1112
+	 */
1113
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1114
+	{
1115
+		return array(
1116
+			'resources' => array(
1117
+				array(
1118
+					'callback'        => array(
1119
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1120
+						'handleRequestModelsMeta',
1121
+					),
1122
+					'methods'         => WP_REST_Server::READABLE,
1123
+					'hidden_endpoint' => $hidden_endpoint,
1124
+					'callback_args'   => array($version),
1125
+				),
1126
+			),
1127
+		);
1128
+	}
1129
+
1130
+
1131
+	/**
1132
+	 * Tries to hide old 4.6 endpoints from the
1133
+	 *
1134
+	 * @param array $route_data
1135
+	 * @return array
1136
+	 * @throws \EE_Error
1137
+	 */
1138
+	public static function hide_old_endpoints($route_data)
1139
+	{
1140
+		// allow API clients to override which endpoints get hidden, in case
1141
+		// they want to discover particular endpoints
1142
+		// also, we don't have access to the request so we have to just grab it from the superglobal
1143
+		$force_show_ee_namespace = ltrim(
1144
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1145
+			'/'
1146
+		);
1147
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1148
+			foreach ($relative_urls as $resource_name => $endpoints) {
1149
+				foreach ($endpoints as $key => $endpoint) {
1150
+					// skip schema and other route options
1151
+					if (! is_numeric($key)) {
1152
+						continue;
1153
+					}
1154
+					// by default, hide "hidden_endpoint"s, unless the request indicates
1155
+					// to $force_show_ee_namespace, in which case only show that one
1156
+					// namespace's endpoints (and hide all others)
1157
+					if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1158
+						|| ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1159
+					) {
1160
+						$full_route = '/' . ltrim($namespace, '/');
1161
+						$full_route .= '/' . ltrim($resource_name, '/');
1162
+						unset($route_data[ $full_route ]);
1163
+					}
1164
+				}
1165
+			}
1166
+		}
1167
+		return $route_data;
1168
+	}
1169
+
1170
+
1171
+	/**
1172
+	 * Returns an array describing which versions of core support serving requests for.
1173
+	 * Keys are core versions' major and minor version, and values are the
1174
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1175
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1176
+	 * the answers table entirely, in which case it would be very difficult for
1177
+	 * it to serve 4.6-style responses.
1178
+	 * Versions of core that are missing from this array are unknowns.
1179
+	 * previous ver
1180
+	 *
1181
+	 * @return array
1182
+	 */
1183
+	public static function version_compatibilities()
1184
+	{
1185
+		return apply_filters(
1186
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1187
+			array(
1188
+				'4.8.29' => '4.8.29',
1189
+				'4.8.33' => '4.8.29',
1190
+				'4.8.34' => '4.8.29',
1191
+				'4.8.36' => '4.8.29',
1192
+			)
1193
+		);
1194
+	}
1195
+
1196
+
1197
+	/**
1198
+	 * Gets the latest API version served. Eg if there
1199
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1200
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1201
+	 *
1202
+	 * @return string
1203
+	 */
1204
+	public static function latest_rest_api_version()
1205
+	{
1206
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1207
+		$versions_served_keys = array_keys($versions_served);
1208
+		return end($versions_served_keys);
1209
+	}
1210
+
1211
+
1212
+	/**
1213
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1214
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1215
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1216
+	 * We also indicate whether or not this version should be put in the index or not
1217
+	 *
1218
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1219
+	 * are whether or not they should be hidden
1220
+	 */
1221
+	public static function versions_served()
1222
+	{
1223
+		$versions_served = array();
1224
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1225
+		$lowest_compatible_version = end($possibly_served_versions);
1226
+		reset($possibly_served_versions);
1227
+		$versions_served_historically = array_keys($possibly_served_versions);
1228
+		$latest_version = end($versions_served_historically);
1229
+		reset($versions_served_historically);
1230
+		// for each version of core we have ever served:
1231
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1232
+			// if it's not above the current core version, and it's compatible with the current version of core
1233
+
1234
+			if ($key_versioned_endpoint === $latest_version) {
1235
+				// don't hide the latest version in the index
1236
+				$versions_served[ $key_versioned_endpoint ] = false;
1237
+			} elseif (version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1238
+				&& version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1239
+			) {
1240
+				// include, but hide, previous versions which are still supported
1241
+				$versions_served[ $key_versioned_endpoint ] = true;
1242
+			} elseif (apply_filters(
1243
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1244
+				false,
1245
+				$possibly_served_versions
1246
+			)) {
1247
+				// if a version is no longer supported, don't include it in index or list of versions served
1248
+				$versions_served[ $key_versioned_endpoint ] = true;
1249
+			}
1250
+		}
1251
+		return $versions_served;
1252
+	}
1253
+
1254
+
1255
+	/**
1256
+	 * Gets the major and minor version of EE core's version string
1257
+	 *
1258
+	 * @return string
1259
+	 */
1260
+	public static function core_version()
1261
+	{
1262
+		return apply_filters(
1263
+			'FHEE__EED_Core_REST_API__core_version',
1264
+			implode(
1265
+				'.',
1266
+				array_slice(
1267
+					explode(
1268
+						'.',
1269
+						espresso_version()
1270
+					),
1271
+					0,
1272
+					3
1273
+				)
1274
+			)
1275
+		);
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Gets the default limit that should be used when querying for resources
1281
+	 *
1282
+	 * @return int
1283
+	 */
1284
+	public static function get_default_query_limit()
1285
+	{
1286
+		// we actually don't use a const because we want folks to always use
1287
+		// this method, not the const directly
1288
+		return apply_filters(
1289
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1290
+			50
1291
+		);
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 *
1297
+	 * @param string $version api version string (i.e. '4.8.36')
1298
+	 * @return array
1299
+	 */
1300
+	public static function getCollectionRoutesIndexedByModelName($version = '')
1301
+	{
1302
+		$version = empty($version) ? self::latest_rest_api_version() : $version;
1303
+		$model_names = self::model_names_with_plural_routes($version);
1304
+		$collection_routes = array();
1305
+		foreach ($model_names as $model_name => $model_class_name) {
1306
+			$collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1307
+															. EEH_Inflector::pluralize_and_lower($model_name);
1308
+		}
1309
+		return $collection_routes;
1310
+	}
1311
+
1312
+
1313
+	/**
1314
+	 * Returns an array of primary key names indexed by model names.
1315
+	 * @param string $version
1316
+	 * @return array
1317
+	 */
1318
+	public static function getPrimaryKeyNamesIndexedByModelName($version = '')
1319
+	{
1320
+		$version = empty($version) ? self::latest_rest_api_version() : $version;
1321
+		$model_names = self::model_names_with_plural_routes($version);
1322
+		$primary_key_items = array();
1323
+		foreach ($model_names as $model_name => $model_class_name) {
1324
+			$primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1325
+			foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1326
+				if (count($primary_keys) > 1) {
1327
+					$primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1328
+				} else {
1329
+					$primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1330
+				}
1331
+			}
1332
+		}
1333
+		return $primary_key_items;
1334
+	}
1335
+
1336
+	/**
1337
+	 * Determines the EE REST API debug mode is activated, or not.
1338
+	 * @since 4.9.76.p
1339
+	 * @return bool
1340
+	 */
1341
+	public static function debugMode()
1342
+	{
1343
+		static $debug_mode = null; // could be class prop
1344
+		if ($debug_mode === null) {
1345
+			$debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE;
1346
+		}
1347
+		return $debug_mode;
1348
+	}
1349
+
1350
+
1351
+
1352
+	/**
1353
+	 *    run - initial module setup
1354
+	 *
1355
+	 * @access    public
1356
+	 * @param  WP $WP
1357
+	 * @return    void
1358
+	 */
1359
+	public function run($WP)
1360
+	{
1361
+	}
1362 1362
 }
Please login to merge, or discard this patch.
Spacing   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
      */
124 124
     protected static function _set_hooks_for_changes()
125 125
     {
126
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
126
+        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api/changes'), false);
127 127
         foreach ($folder_contents as $classname_in_namespace => $filepath) {
128 128
             // ignore the base parent class
129 129
             // and legacy named classes
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
             ) {
133 133
                 continue;
134 134
             }
135
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
135
+            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace;
136 136
             if (class_exists($full_classname)) {
137 137
                 $instance_of_class = new $full_classname;
138 138
                 if ($instance_of_class instanceof ChangesInBase) {
@@ -177,10 +177,10 @@  discard block
 block discarded – undo
177 177
                      * }
178 178
                      */
179 179
                     // skip route options
180
-                    if (! is_numeric($endpoint_key)) {
180
+                    if ( ! is_numeric($endpoint_key)) {
181 181
                         continue;
182 182
                     }
183
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
183
+                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184 184
                         throw new EE_Error(
185 185
                             esc_html__(
186 186
                             // @codingStandardsIgnoreStart
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
                     }
202 202
                     if (isset($data_for_single_endpoint['callback_args'])) {
203 203
                         $callback_args = $data_for_single_endpoint['callback_args'];
204
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
204
+                        $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use (
205 205
                             $callback,
206 206
                             $callback_args
207 207
                         ) {
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
                     // the REST API will issue a _doing_it_wrong notice.
219 219
                     // Since the EE REST API defers capabilities to the db model system,
220 220
                     // we will just use the generic WP callback for public endpoints
221
-                    if (! isset($single_endpoint_args['permission_callback'])) {
221
+                    if ( ! isset($single_endpoint_args['permission_callback'])) {
222 222
                         $single_endpoint_args['permission_callback'] = '__return_true';
223 223
                     }
224 224
                     $multiple_endpoint_args[] = $single_endpoint_args;
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
                     $schema_route_data = $data_for_multiple_endpoints['schema'];
228 228
                     $schema_callback = $schema_route_data['schema_callback'];
229 229
                     $callback_args = $schema_route_data['callback_args'];
230
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
230
+                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) {
231 231
                         return call_user_func_array(
232 232
                             $schema_callback,
233 233
                             $callback_args
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
     {
270 270
         // delete the saved EE REST API routes
271 271
         foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
272
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
272
+            delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version);
273 273
         }
274 274
     }
275 275
 
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
     {
289 289
         $ee_routes = array();
290 290
         foreach (self::versions_served() as $version => $hidden_endpoints) {
291
-            $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
291
+            $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version(
292 292
                 $version,
293 293
                 $hidden_endpoints
294 294
             );
@@ -308,8 +308,8 @@  discard block
 block discarded – undo
308 308
      */
309 309
     protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
310 310
     {
311
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
312
-        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
311
+        $ee_routes = get_option(self::saved_routes_option_names.$version, null);
312
+        if ( ! $ee_routes || EED_Core_Rest_Api::debugMode()) {
313 313
             $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
314 314
         }
315 315
         return $ee_routes;
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
                 $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
337 337
             )
338 338
         );
339
-        $option_name = self::saved_routes_option_names . $version;
339
+        $option_name = self::saved_routes_option_names.$version;
340 340
         if (get_option($option_name)) {
341 341
             update_option($option_name, $routes, true);
342 342
         } else {
@@ -381,8 +381,8 @@  discard block
 block discarded – undo
381 381
     {
382 382
         $model_routes = array();
383 383
         foreach (self::versions_served() as $version => $hidden_endpoint) {
384
-            $model_routes[ EED_Core_Rest_Api::ee_api_namespace
385
-                           . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
384
+            $model_routes[EED_Core_Rest_Api::ee_api_namespace
385
+                           . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
386 386
         }
387 387
         return $model_routes;
388 388
     }
@@ -451,13 +451,13 @@  discard block
 block discarded – undo
451 451
         foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
452 452
             $model = \EE_Registry::instance()->load_model($model_name);
453 453
             // if this isn't a valid model then let's skip iterate to the next item in the loop.
454
-            if (! $model instanceof EEM_Base) {
454
+            if ( ! $model instanceof EEM_Base) {
455 455
                 continue;
456 456
             }
457 457
             // yes we could just register one route for ALL models, but then they wouldn't show up in the index
458 458
             $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
459 459
             $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
460
-            $model_routes[ $plural_model_route ] = array(
460
+            $model_routes[$plural_model_route] = array(
461 461
                 array(
462 462
                     'callback'        => array(
463 463
                         'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
                     'hidden_endpoint' => $hidden_endpoint,
469 469
                     'args'            => $this->_get_read_query_params($model, $version),
470 470
                     '_links'          => array(
471
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
471
+                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route),
472 472
                     ),
473 473
                 ),
474 474
                 'schema' => array(
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
                     'callback_args'   => array($version, $model_name),
480 480
                 ),
481 481
             );
482
-            $model_routes[ $singular_model_route ] = array(
482
+            $model_routes[$singular_model_route] = array(
483 483
                 array(
484 484
                     'callback'        => array(
485 485
                         'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
                 EED_Core_Rest_Api::should_have_write_endpoints($model),
497 497
                 $model
498 498
             )) {
499
-                $model_routes[ $plural_model_route ][] = array(
499
+                $model_routes[$plural_model_route][] = array(
500 500
                     'callback'        => array(
501 501
                         'EventEspresso\core\libraries\rest_api\controllers\model\Write',
502 502
                         'handleRequestInsert',
@@ -506,8 +506,8 @@  discard block
 block discarded – undo
506 506
                     'hidden_endpoint' => $hidden_endpoint,
507 507
                     'args'            => $this->_get_write_params($model_name, $model_version_info, true),
508 508
                 );
509
-                $model_routes[ $singular_model_route ] = array_merge(
510
-                    $model_routes[ $singular_model_route ],
509
+                $model_routes[$singular_model_route] = array_merge(
510
+                    $model_routes[$singular_model_route],
511 511
                     array(
512 512
                         array(
513 513
                             'callback'        => array(
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
                     '(?P<id>[^\/]+)',
539 539
                     $relation_obj
540 540
                 );
541
-                $model_routes[ $related_route ] = array(
541
+                $model_routes[$related_route] = array(
542 542
                     array(
543 543
                         'callback'        => array(
544 544
                             'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -551,8 +551,8 @@  discard block
 block discarded – undo
551 551
                     ),
552 552
                 );
553 553
 
554
-                $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
555
-                $model_routes[ $related_write_route ] = array(
554
+                $related_write_route = $related_route.'/'.'(?P<related_id>[^\/]+)';
555
+                $model_routes[$related_write_route] = array(
556 556
                     array(
557 557
                         'callback'        => array(
558 558
                             'EventEspresso\core\libraries\rest_api\controllers\model\Write',
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
      */
606 606
     public static function get_entity_route($model, $id)
607 607
     {
608
-        return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
608
+        return EED_Core_Rest_Api::get_collection_route($model).'/'.$id;
609 609
     }
610 610
 
611 611
 
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
             $relation_obj->get_other_model()->get_this_model_name(),
626 626
             $relation_obj
627 627
         );
628
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
628
+        return EED_Core_Rest_Api::get_entity_route($model, $id).'/'.$related_model_name_endpoint_part;
629 629
     }
630 630
 
631 631
 
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
      */
640 640
     public static function get_versioned_route_to($relative_route, $version = '4.8.36')
641 641
     {
642
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
642
+        return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route;
643 643
     }
644 644
 
645 645
 
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
     {
654 654
         $routes = array();
655 655
         foreach (self::versions_served() as $version => $hidden_endpoint) {
656
-            $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
656
+            $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version(
657 657
                 $version,
658 658
                 $hidden_endpoint
659 659
             );
@@ -776,12 +776,12 @@  discard block
 block discarded – undo
776 776
     {
777 777
         // if they're related through a HABTM relation, check for any non-FKs
778 778
         $all_relation_settings = $source_model->relation_settings();
779
-        $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
779
+        $relation_settings = $all_relation_settings[$related_model->get_this_model_name()];
780 780
         $params = array();
781 781
         if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
782 782
             foreach ($relation_settings->getNonKeyFields() as $field) {
783 783
                 /* @var $field EE_Model_Field_Base */
784
-                $params[ $field->get_name() ] = array(
784
+                $params[$field->get_name()] = array(
785 785
                     'required' => ! $field->is_nullable(),
786 786
                     'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
787 787
                     'type' => $field->getSchemaType(),
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
     {
807 807
         $default_orderby = array();
808 808
         foreach ($model->get_combined_primary_key_fields() as $key_field) {
809
-            $default_orderby[ $key_field->get_name() ] = 'ASC';
809
+            $default_orderby[$key_field->get_name()] = 'ASC';
810 810
         }
811 811
         return array_merge(
812 812
             $this->_get_response_selection_query_params($model, $version),
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
                     'type'              => array(
841 841
                         'object',
842 842
                         'string',
843
-                    ),// because we accept a variety of types, WP core validation and sanitization
843
+                    ), // because we accept a variety of types, WP core validation and sanitization
844 844
                     // freaks out. We'll just validate this argument while handling the request
845 845
                     'validate_callback' => null,
846 846
                     'sanitize_callback' => null,
@@ -938,7 +938,7 @@  discard block
 block discarded – undo
938 938
                 $sanitize_callback = null;
939 939
             }
940 940
             $arg_info['sanitize_callback'] = $sanitize_callback;
941
-            $args_info[ $field_name ] = $arg_info;
941
+            $args_info[$field_name] = $arg_info;
942 942
             if ($field_obj instanceof EE_Datetime_Field) {
943 943
                 $gmt_arg_info = $arg_info;
944 944
                 $gmt_arg_info['description'] = sprintf(
@@ -949,7 +949,7 @@  discard block
 block discarded – undo
949 949
                     $field_obj->get_nicename(),
950 950
                     $field_name
951 951
                 );
952
-                $args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
952
+                $args_info[$field_name.'_gmt'] = $gmt_arg_info;
953 953
             }
954 954
         }
955 955
         return $args_info;
@@ -972,16 +972,16 @@  discard block
 block discarded – undo
972 972
     public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
973 973
     {
974 974
         $attributes = $request->get_attributes();
975
-        if (! isset($attributes['args'][ $param ])
976
-            || ! is_array($attributes['args'][ $param ])) {
975
+        if ( ! isset($attributes['args'][$param])
976
+            || ! is_array($attributes['args'][$param])) {
977 977
             $validation_result = true;
978 978
         } else {
979
-            $args = $attributes['args'][ $param ];
979
+            $args = $attributes['args'][$param];
980 980
             if ((
981 981
                     $value === ''
982 982
                     || $value === null
983 983
                 )
984
-                && (! isset($args['required'])
984
+                && ( ! isset($args['required'])
985 985
                     || $args['required'] === false
986 986
                 )
987 987
             ) {
@@ -991,7 +991,7 @@  discard block
 block discarded – undo
991 991
                       && $args['format'] === 'email'
992 992
             ) {
993 993
                 $validation_result = true;
994
-                if (! self::_validate_email($value)) {
994
+                if ( ! self::_validate_email($value)) {
995 995
                     $validation_result = new WP_Error(
996 996
                         'rest_invalid_param',
997 997
                         esc_html__(
@@ -1041,7 +1041,7 @@  discard block
 block discarded – undo
1041 1041
     {
1042 1042
         $config_routes = array();
1043 1043
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1044
-            $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1044
+            $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version(
1045 1045
                 $version,
1046 1046
                 $hidden_endpoint
1047 1047
             );
@@ -1096,7 +1096,7 @@  discard block
 block discarded – undo
1096 1096
     {
1097 1097
         $meta_routes = array();
1098 1098
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1099
-            $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1099
+            $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version(
1100 1100
                 $version,
1101 1101
                 $hidden_endpoint
1102 1102
             );
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
             foreach ($relative_urls as $resource_name => $endpoints) {
1149 1149
                 foreach ($endpoints as $key => $endpoint) {
1150 1150
                     // skip schema and other route options
1151
-                    if (! is_numeric($key)) {
1151
+                    if ( ! is_numeric($key)) {
1152 1152
                         continue;
1153 1153
                     }
1154 1154
                     // by default, hide "hidden_endpoint"s, unless the request indicates
@@ -1157,9 +1157,9 @@  discard block
 block discarded – undo
1157 1157
                     if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1158 1158
                         || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1159 1159
                     ) {
1160
-                        $full_route = '/' . ltrim($namespace, '/');
1161
-                        $full_route .= '/' . ltrim($resource_name, '/');
1162
-                        unset($route_data[ $full_route ]);
1160
+                        $full_route = '/'.ltrim($namespace, '/');
1161
+                        $full_route .= '/'.ltrim($resource_name, '/');
1162
+                        unset($route_data[$full_route]);
1163 1163
                     }
1164 1164
                 }
1165 1165
             }
@@ -1233,19 +1233,19 @@  discard block
 block discarded – undo
1233 1233
 
1234 1234
             if ($key_versioned_endpoint === $latest_version) {
1235 1235
                 // don't hide the latest version in the index
1236
-                $versions_served[ $key_versioned_endpoint ] = false;
1236
+                $versions_served[$key_versioned_endpoint] = false;
1237 1237
             } elseif (version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1238 1238
                 && version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1239 1239
             ) {
1240 1240
                 // include, but hide, previous versions which are still supported
1241
-                $versions_served[ $key_versioned_endpoint ] = true;
1241
+                $versions_served[$key_versioned_endpoint] = true;
1242 1242
             } elseif (apply_filters(
1243 1243
                 'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1244 1244
                 false,
1245 1245
                 $possibly_served_versions
1246 1246
             )) {
1247 1247
                 // if a version is no longer supported, don't include it in index or list of versions served
1248
-                $versions_served[ $key_versioned_endpoint ] = true;
1248
+                $versions_served[$key_versioned_endpoint] = true;
1249 1249
             }
1250 1250
         }
1251 1251
         return $versions_served;
@@ -1303,7 +1303,7 @@  discard block
 block discarded – undo
1303 1303
         $model_names = self::model_names_with_plural_routes($version);
1304 1304
         $collection_routes = array();
1305 1305
         foreach ($model_names as $model_name => $model_class_name) {
1306
-            $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1306
+            $collection_routes[strtolower($model_name)] = '/'.self::ee_api_namespace.$version.'/'
1307 1307
                                                             . EEH_Inflector::pluralize_and_lower($model_name);
1308 1308
         }
1309 1309
         return $collection_routes;
@@ -1324,9 +1324,9 @@  discard block
 block discarded – undo
1324 1324
             $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1325 1325
             foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1326 1326
                 if (count($primary_keys) > 1) {
1327
-                    $primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1327
+                    $primary_key_items[strtolower($model_name)][] = $primary_key_name;
1328 1328
                 } else {
1329
-                    $primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1329
+                    $primary_key_items[strtolower($model_name)] = $primary_key_name;
1330 1330
                 }
1331 1331
             }
1332 1332
         }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Post_Content_Field.php 1 patch
Indentation   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -7,129 +7,129 @@
 block discarded – undo
7 7
 class EE_Post_Content_Field extends EE_Text_Field_Base
8 8
 {
9 9
 
10
-    /**
11
-     * @param string $table_column
12
-     * @param string $nicename
13
-     * @param bool   $nullable
14
-     * @param null   $default_value
15
-     */
16
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
17
-    {
18
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
19
-        $this->setSchemaType('object');
20
-    }
10
+	/**
11
+	 * @param string $table_column
12
+	 * @param string $nicename
13
+	 * @param bool   $nullable
14
+	 * @param null   $default_value
15
+	 */
16
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
17
+	{
18
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
19
+		$this->setSchemaType('object');
20
+	}
21 21
 
22 22
 
23
-    /**
24
-     * removes all tags which a WP Post wouldn't allow in its content normally
25
-     *
26
-     * @param string $value
27
-     * @return string
28
-     */
29
-    public function prepare_for_set($value)
30
-    {
31
-        if (! current_user_can('unfiltered_html')) {
32
-            $value = wp_kses("$value", wp_kses_allowed_html('post'));
33
-        }
34
-        return parent::prepare_for_set($value);
35
-    }
23
+	/**
24
+	 * removes all tags which a WP Post wouldn't allow in its content normally
25
+	 *
26
+	 * @param string $value
27
+	 * @return string
28
+	 */
29
+	public function prepare_for_set($value)
30
+	{
31
+		if (! current_user_can('unfiltered_html')) {
32
+			$value = wp_kses("$value", wp_kses_allowed_html('post'));
33
+		}
34
+		return parent::prepare_for_set($value);
35
+	}
36 36
 
37 37
 
38 38
 
39
-    /**
40
-     * Runs the content through `the_content`, or if prepares the content for placing in a form input
41
-     * @param string $value_on_field_to_be_outputted
42
-     * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
43
-     * @return string
44
-     * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
45
-     */
46
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
47
-    {
48
-        switch ($schema) {
49
-            case 'form_input':
50
-                return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
51
-            case 'the_content':
52
-                if (doing_filter('the_content')) {
53
-                    if (defined('WP_DEBUG') && WP_DEBUG) {
54
-                        throw new EE_Error(
55
-                            sprintf(
56
-                                esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
57
-                                'EE_Post_Content_Field::prepare_for_pretty_echoing',
58
-                                '$schema',
59
-                                'the_content',
60
-                                'the_content_wp_core_only'
61
-                            )
62
-                        );
63
-                    } else {
64
-                        return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
65
-                    }
66
-                }
67
-                return apply_filters(
68
-                    'the_content',
69
-                    parent::prepare_for_pretty_echoing(
70
-                        $value_on_field_to_be_outputted,
71
-                        $schema
72
-                    )
73
-                );
74
-            case 'the_content_wp_core_only':
75
-            default:
76
-                self::_setup_the_content_wp_core_only_filters();
77
-                $return_value = apply_filters(
78
-                    'the_content_wp_core_only',
79
-                    parent::prepare_for_pretty_echoing(
80
-                        $value_on_field_to_be_outputted,
81
-                        $schema
82
-                    )
83
-                );
84
-                // ya know what? adding these filters is super fast. Let's just
85
-                // avoid needing to maintain global state and set this up as-needed
86
-                remove_all_filters('the_content_wp_core_only');
87
-                do_action('AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
88
-                return $return_value;
89
-        }
90
-    }
39
+	/**
40
+	 * Runs the content through `the_content`, or if prepares the content for placing in a form input
41
+	 * @param string $value_on_field_to_be_outputted
42
+	 * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
43
+	 * @return string
44
+	 * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
45
+	 */
46
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
47
+	{
48
+		switch ($schema) {
49
+			case 'form_input':
50
+				return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
51
+			case 'the_content':
52
+				if (doing_filter('the_content')) {
53
+					if (defined('WP_DEBUG') && WP_DEBUG) {
54
+						throw new EE_Error(
55
+							sprintf(
56
+								esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
57
+								'EE_Post_Content_Field::prepare_for_pretty_echoing',
58
+								'$schema',
59
+								'the_content',
60
+								'the_content_wp_core_only'
61
+							)
62
+						);
63
+					} else {
64
+						return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
65
+					}
66
+				}
67
+				return apply_filters(
68
+					'the_content',
69
+					parent::prepare_for_pretty_echoing(
70
+						$value_on_field_to_be_outputted,
71
+						$schema
72
+					)
73
+				);
74
+			case 'the_content_wp_core_only':
75
+			default:
76
+				self::_setup_the_content_wp_core_only_filters();
77
+				$return_value = apply_filters(
78
+					'the_content_wp_core_only',
79
+					parent::prepare_for_pretty_echoing(
80
+						$value_on_field_to_be_outputted,
81
+						$schema
82
+					)
83
+				);
84
+				// ya know what? adding these filters is super fast. Let's just
85
+				// avoid needing to maintain global state and set this up as-needed
86
+				remove_all_filters('the_content_wp_core_only');
87
+				do_action('AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
88
+				return $return_value;
89
+		}
90
+	}
91 91
 
92 92
 
93 93
 
94
-    /**
95
-     * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
96
-     */
97
-    protected static function _setup_the_content_wp_core_only_filters()
98
-    {
99
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
100
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
101
-        add_filter('the_content_wp_core_only', 'wptexturize', 10);
102
-        add_filter('the_content_wp_core_only', 'wpautop', 10);
103
-        add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
104
-        add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
105
-        if (function_exists('wp_filter_content_tags')) {
106
-            add_filter('the_content_wp_core_only', 'wp_filter_content_tags', 10);
107
-        } elseif (function_exists('wp_make_content_images_responsive')) {
108
-            add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
109
-        }
110
-        add_filter('the_content_wp_core_only', 'do_shortcode', 11);
111
-        add_filter('the_content_wp_core_only', 'convert_smilies', 20);
112
-    }
94
+	/**
95
+	 * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
96
+	 */
97
+	protected static function _setup_the_content_wp_core_only_filters()
98
+	{
99
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
100
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
101
+		add_filter('the_content_wp_core_only', 'wptexturize', 10);
102
+		add_filter('the_content_wp_core_only', 'wpautop', 10);
103
+		add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
104
+		add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
105
+		if (function_exists('wp_filter_content_tags')) {
106
+			add_filter('the_content_wp_core_only', 'wp_filter_content_tags', 10);
107
+		} elseif (function_exists('wp_make_content_images_responsive')) {
108
+			add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
109
+		}
110
+		add_filter('the_content_wp_core_only', 'do_shortcode', 11);
111
+		add_filter('the_content_wp_core_only', 'convert_smilies', 20);
112
+	}
113 113
 
114 114
 
115 115
 
116
-    public function getSchemaProperties()
117
-    {
118
-        return array(
119
-            'raw' => array(
120
-                'description' =>  sprintf(
121
-                    __('%s - the content as it exists in the database.', 'event_espresso'),
122
-                    $this->get_nicename()
123
-                ),
124
-                'type' => 'string'
125
-            ),
126
-            'rendered' => array(
127
-                'description' =>  sprintf(
128
-                    __('%s - the content rendered for display.', 'event_espresso'),
129
-                    $this->get_nicename()
130
-                ),
131
-                'type' => 'string'
132
-            )
133
-        );
134
-    }
116
+	public function getSchemaProperties()
117
+	{
118
+		return array(
119
+			'raw' => array(
120
+				'description' =>  sprintf(
121
+					__('%s - the content as it exists in the database.', 'event_espresso'),
122
+					$this->get_nicename()
123
+				),
124
+				'type' => 'string'
125
+			),
126
+			'rendered' => array(
127
+				'description' =>  sprintf(
128
+					__('%s - the content rendered for display.', 'event_espresso'),
129
+					$this->get_nicename()
130
+				),
131
+				'type' => 'string'
132
+			)
133
+		);
134
+	}
135 135
 }
Please login to merge, or discard this patch.