Completed
Branch models-cleanup/model-relations (b772ed)
by
unknown
56:02 queued 47:06
created
core/db_models/relations/EE_Model_Relation_Base.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
      * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
118 118
      * model objects will only be soft-deleted.
119 119
      *
120
-     * @param EE_Base_Class|int|string $model_object_or_id
120
+     * @param EE_Base_Class|null $model_object_or_id
121 121
      * @param array                    $query_params
122 122
      * @return int of how many related models got deleted
123 123
      * @throws EE_Error
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
      * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
294 294
      * model objects will only be soft-deleted.
295 295
      *
296
-     * @param EE_Base_Class|int|string $model_object_or_id
296
+     * @param EE_Base_Class|null $model_object_or_id
297 297
      * @param array                    $query_params
298 298
      * @return int of how many related models got deleted
299 299
      * @throws EE_Error
@@ -536,9 +536,9 @@  discard block
 block discarded – undo
536 536
 
537 537
     /**
538 538
      * @param        $other_table
539
-     * @param        $other_table_alias
539
+     * @param        string $other_table_alias
540 540
      * @param        $other_table_column
541
-     * @param        $this_table_alias
541
+     * @param        string $this_table_alias
542 542
      * @param        $this_table_join_column
543 543
      * @param string $extra_join_sql
544 544
      * @return string
Please login to merge, or discard this patch.
Indentation   +548 added lines, -548 removed lines patch added patch discarded remove patch
@@ -17,552 +17,552 @@
 block discarded – undo
17 17
 abstract class EE_Model_Relation_Base implements HasSchemaInterface
18 18
 {
19 19
 
20
-    /**
21
-     * @var bool
22
-     */
23
-    protected $_blocking_delete = false;
24
-
25
-    /**
26
-     * If you try to delete "this_model", and there are related "other_models",
27
-     * and this isn't null, then abandon the deletion and add this warning.
28
-     * This effectively makes it impossible to delete "this_model" while there are
29
-     * related "other_models" along this relation.
30
-     *
31
-     * @var string (internationalized)
32
-     */
33
-    protected $_blocking_delete_error_message;
34
-
35
-    /**
36
-     * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
37
-     *
38
-     * @var string eg Event, Question_Group, Registration
39
-     */
40
-    private $_other_model_name;
41
-
42
-    /**
43
-     * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
44
-     *
45
-     * @var string eg Event, Question_Group, Registration
46
-     */
47
-    private $_this_model_name;
48
-
49
-    /**
50
-     * this is typically used when calling the relation models to make sure they inherit any set timezone from the
51
-     * initiating model.
52
-     *
53
-     * @var string
54
-     */
55
-    protected $_timezone;
56
-
57
-
58
-    /**
59
-     * Object representing the relationship between two models. This knows how to join the models,
60
-     * get related models across the relation, and add-and-remove the relationships.
61
-     *
62
-     * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
63
-     *                                               and add an error) the deletion of this model
64
-     * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
65
-     *                                               default
66
-     */
67
-    public function __construct($block_deletes, $blocking_delete_error_message)
68
-    {
69
-        $this->_blocking_delete               = $block_deletes;
70
-        $this->_blocking_delete_error_message = $blocking_delete_error_message;
71
-    }
72
-
73
-
74
-    /**
75
-     * @param $this_model_name
76
-     * @param $other_model_name
77
-     * @throws EE_Error
78
-     */
79
-    public function _construct_finalize_set_models($this_model_name, $other_model_name)
80
-    {
81
-        $this->_this_model_name  = $this_model_name;
82
-        $this->_other_model_name = $other_model_name;
83
-        if (is_string($this->_blocking_delete)) {
84
-            throw new EE_Error(
85
-                sprintf(
86
-                    esc_html__(
87
-                        "When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
88
-                        "event_espresso"
89
-                    ),
90
-                    get_class($this),
91
-                    $this_model_name,
92
-                    $other_model_name,
93
-                    $this->_blocking_delete
94
-                )
95
-            );
96
-        }
97
-    }
98
-
99
-
100
-    /**
101
-     * entirely possible that relations may be called from a model and we need to make sure those relations have their
102
-     * timezone set correctly.
103
-     *
104
-     * @param string $timezone timezone to set.
105
-     */
106
-    public function set_timezone($timezone)
107
-    {
108
-        if (! empty($timezone)) {
109
-            $this->_timezone = $timezone;
110
-        }
111
-    }
112
-
113
-
114
-    /**
115
-     * Deletes the related model objects which meet the query parameters. If no
116
-     * parameters are specified, then all related model objects will be deleted.
117
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
118
-     * model objects will only be soft-deleted.
119
-     *
120
-     * @param EE_Base_Class|int|string $model_object_or_id
121
-     * @param array                    $query_params
122
-     * @return int of how many related models got deleted
123
-     * @throws EE_Error
124
-     * @throws ReflectionException
125
-     */
126
-    public function delete_all_related($model_object_or_id, $query_params = [])
127
-    {
128
-        // for each thing we would delete,
129
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
130
-        // determine if it's blocked by anything else before it can be deleted
131
-        $deleted_count = 0;
132
-        foreach ($related_model_objects as $related_model_object) {
133
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
134
-                $related_model_object,
135
-                $model_object_or_id
136
-            );
137
-            /* @var $model_object_or_id EE_Base_Class */
138
-            if (! $delete_is_blocked) {
139
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
140
-                $related_model_object->delete();
141
-                $deleted_count++;
142
-            }
143
-        }
144
-        return $deleted_count;
145
-    }
146
-
147
-
148
-    /**
149
-     * Gets all the model objects of type of other model related to $model_object,
150
-     * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
151
-     * For both of those child classes, $model_object must be saved so that it has an ID before querying,
152
-     * otherwise an error will be thrown. Note: by default we disable default_where_conditions
153
-     * EE_Belongs_To_Relation doesn't need to be saved before querying.
154
-     *
155
-     * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
156
-     * @param array             $query_params                            @see
157
-     *                                                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
158
-     * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
159
-     * @return EE_Base_Class[]
160
-     * @throws EE_Error
161
-     * @throws ReflectionException
162
-     */
163
-    public function get_all_related(
164
-        $model_object_or_id,
165
-        $query_params = [],
166
-        $values_already_prepared_by_model_object = false
167
-    ) {
168
-        if ($values_already_prepared_by_model_object !== false) {
169
-            EE_Error::doing_it_wrong(
170
-                'EE_Model_Relation_Base::get_all_related',
171
-                esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
172
-                '4.8.1'
173
-            );
174
-        }
175
-        $query_params                                        =
176
-            $this->_disable_default_where_conditions_on_query_param($query_params);
177
-        $query_param_where_this_model_pk                     = $this->get_this_model()->get_this_model_name()
178
-                                                               .
179
-                                                               "."
180
-                                                               .
181
-                                                               $this->get_this_model()
182
-                                                                    ->get_primary_key_field()
183
-                                                                    ->get_name();
184
-        $model_object_id                                     = $this->_get_model_object_id($model_object_or_id);
185
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
186
-        return $this->get_other_model()->get_all($query_params);
187
-    }
188
-
189
-
190
-    /**
191
-     * Gets the model which this relation establishes the relation TO (ie,
192
-     * this relation object was defined on get_this_model(), get_other_model() is the other one)
193
-     *
194
-     * @return EEM_Base
195
-     * @throws EE_Error
196
-     * @throws ReflectionException
197
-     */
198
-    public function get_other_model()
199
-    {
200
-        return $this->_get_model($this->_other_model_name);
201
-    }
202
-
203
-
204
-    /**
205
-     * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
206
-     * model objects
207
-     *
208
-     * @param       $this_obj_or_id
209
-     * @param       $other_obj_or_id
210
-     * @param array $where_query
211
-     * @return bool
212
-     */
213
-    abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = []);
214
-
215
-
216
-    /**
217
-     * Alters the $query_params to disable default where conditions, unless otherwise specified
218
-     *
219
-     * @param array $query_params
220
-     * @return array
221
-     */
222
-    protected function _disable_default_where_conditions_on_query_param($query_params)
223
-    {
224
-        if (! isset($query_params['default_where_conditions'])) {
225
-            $query_params['default_where_conditions'] = 'none';
226
-        }
227
-        return $query_params;
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets the model where this relation is defined.
233
-     *
234
-     * @return EEM_Base
235
-     * @throws EE_Error
236
-     * @throws ReflectionException
237
-     */
238
-    public function get_this_model()
239
-    {
240
-        return $this->_get_model($this->_this_model_name);
241
-    }
242
-
243
-
244
-    /**
245
-     * this just returns a model_object_id for incoming item that could be an object or id.
246
-     *
247
-     * @param EE_Base_Class|int $model_object_or_id model object or the primary key of this model
248
-     * @return int
249
-     * @throws EE_Error
250
-     * @throws ReflectionException
251
-     */
252
-    protected function _get_model_object_id($model_object_or_id)
253
-    {
254
-        $model_object_id = $model_object_or_id;
255
-        if ($model_object_or_id instanceof EE_Base_Class) {
256
-            $model_object_id = $model_object_or_id->ID();
257
-        }
258
-        if (! $model_object_id) {
259
-            throw new EE_Error(
260
-                sprintf(
261
-                    esc_html__(
262
-                        "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
263
-                        "event_espresso"
264
-                    ),
265
-                    $this->get_other_model()->get_this_model_name(),
266
-                    $this->get_this_model()->get_this_model_name()
267
-                )
268
-            );
269
-        }
270
-        return $model_object_id;
271
-    }
272
-
273
-
274
-    /**
275
-     * Internally used by get_this_model() and get_other_model()
276
-     *
277
-     * @param string $model_name like Event, Question_Group, etc. omit the EEM_
278
-     * @return EEM_Base
279
-     * @throws EE_Error
280
-     * @throws ReflectionException
281
-     */
282
-    protected function _get_model($model_name)
283
-    {
284
-        $modelInstance = EE_Registry::instance()->load_model($model_name);
285
-        $modelInstance->set_timezone($this->_timezone);
286
-        return $modelInstance;
287
-    }
288
-
289
-
290
-    /**
291
-     * Deletes the related model objects which meet the query parameters. If no
292
-     * parameters are specified, then all related model objects will be deleted.
293
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
294
-     * model objects will only be soft-deleted.
295
-     *
296
-     * @param EE_Base_Class|int|string $model_object_or_id
297
-     * @param array                    $query_params
298
-     * @return int of how many related models got deleted
299
-     * @throws EE_Error
300
-     * @throws ReflectionException
301
-     */
302
-    public function delete_related_permanently($model_object_or_id, $query_params = [])
303
-    {
304
-        // for each thing we would delete,
305
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
306
-        // determine if it's blocked by anything else before it can be deleted
307
-        $deleted_count = 0;
308
-        foreach ($related_model_objects as $related_model_object) {
309
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
310
-                $related_model_object,
311
-                $model_object_or_id
312
-            );
313
-            /* @var $model_object_or_id EE_Base_Class */
314
-            if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
315
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
316
-                $deleted_count++;
317
-                if (! $delete_is_blocked) {
318
-                    $related_model_object->delete_permanently();
319
-                } else {
320
-                    // delete is blocked
321
-                    // brent and darren, in this case, wanted to just soft delete it then
322
-                    $related_model_object->delete();
323
-                }
324
-            } else {
325
-                // its not a soft-deletable thing anyways. do the normal logic.
326
-                if (! $delete_is_blocked) {
327
-                    $this->remove_relation_to($model_object_or_id, $related_model_object);
328
-                    $related_model_object->delete();
329
-                    $deleted_count++;
330
-                }
331
-            }
332
-        }
333
-        return $deleted_count;
334
-    }
335
-
336
-
337
-    /**
338
-     * Gets the SQL string for performing the join between this model and the other model.
339
-     *
340
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
341
-     * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
342
-     *                                     other_model_primary_table.fk" etc
343
-     */
344
-    abstract public function get_join_statement($model_relation_chain);
345
-
346
-
347
-    /**
348
-     * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
349
-     * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
350
-     * relationship only allows this model to be related to a single other model of this type)
351
-     *
352
-     * @param       $this_obj_or_id
353
-     * @param       $other_obj_or_id
354
-     * @param array $extra_join_model_fields_n_values
355
-     * @return EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
356
-     *                        $other_obj_or_id)
357
-     */
358
-    abstract public function add_relation_to(
359
-        $this_obj_or_id,
360
-        $other_obj_or_id,
361
-        $extra_join_model_fields_n_values = []
362
-    );
363
-
364
-
365
-    /**
366
-     * Removes ALL relation instances for this relation obj
367
-     *
368
-     * @param EE_Base_Class|int $this_obj_or_id
369
-     * @param array             $where_query_param @see
370
-     *                                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
371
-     * @return EE_Base_Class[]
372
-     * @throws EE_Error
373
-     * @throws ReflectionException
374
-     */
375
-    public function remove_relations($this_obj_or_id, $where_query_param = [])
376
-    {
377
-        $related_things = $this->get_all_related($this_obj_or_id, [$where_query_param]);
378
-        $objs_removed   = [];
379
-        foreach ($related_things as $related_thing) {
380
-            $objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
381
-        }
382
-        return $objs_removed;
383
-    }
384
-
385
-
386
-    /**
387
-     * If you aren't allowed to delete this model when there are related models across this
388
-     * relation object, return true. Otherwise, if you can delete this model even though
389
-     * related objects exist, returns false.
390
-     *
391
-     * @return boolean
392
-     */
393
-    public function block_delete_if_related_models_exist()
394
-    {
395
-        return $this->_blocking_delete;
396
-    }
397
-
398
-
399
-    /**
400
-     * Gets the error message to show
401
-     *
402
-     * @return string
403
-     * @throws EE_Error
404
-     * @throws ReflectionException
405
-     */
406
-    public function get_deletion_error_message()
407
-    {
408
-        if ($this->_blocking_delete_error_message) {
409
-            return $this->_blocking_delete_error_message;
410
-        }
411
-        return sprintf(
412
-            esc_html__(
413
-                'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
414
-                "event_espresso"
415
-            ),
416
-            $this->get_this_model()->item_name(),
417
-            $this->get_other_model()->item_name(),
418
-            $this->get_other_model()->item_name(2)
419
-        );
420
-    }
421
-
422
-
423
-    /**
424
-     * This returns elements used to represent this field in the json schema.
425
-     *
426
-     * @link http://json-schema.org/
427
-     * @return array
428
-     * @throws EE_Error
429
-     * @throws ReflectionException
430
-     */
431
-    public function getSchema()
432
-    {
433
-        $schema = [
434
-            'description'   => $this->getSchemaDescription(),
435
-            'type'          => $this->getSchemaType(),
436
-            'relation'      => true,
437
-            'relation_type' => get_class($this),
438
-            'readonly'      => $this->getSchemaReadonly(),
439
-        ];
440
-
441
-        if ($this instanceof EE_HABTM_Relation) {
442
-            $schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
443
-        }
444
-
445
-        if ($this->getSchemaType() === 'array') {
446
-            $schema['items'] = [
447
-                'type' => 'object',
448
-            ];
449
-        }
450
-
451
-        return $schema;
452
-    }
453
-
454
-
455
-    /**
456
-     * Returns whatever is set as the nice name for the object.
457
-     *
458
-     * @return string
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function getSchemaDescription()
463
-    {
464
-        $description = $this instanceof EE_Belongs_To_Relation
465
-            ? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
466
-            : esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
467
-        return sprintf(
468
-            $description,
469
-            $this->get_other_model()->get_this_model_name(),
470
-            $this->get_this_model()->get_this_model_name()
471
-        );
472
-    }
473
-
474
-
475
-    /**
476
-     * If a child class has enum values, they should override this method and provide a simple array
477
-     * of the enum values.
478
-     * The reason this is not a property on the class is because there may be filterable enum values that
479
-     * are set on the instantiated object that could be filtered after construct.
480
-     *
481
-     * @return array
482
-     */
483
-    public function getSchemaEnum()
484
-    {
485
-        return [];
486
-    }
487
-
488
-
489
-    /**
490
-     * This returns the value of the $_schema_format property on the object.
491
-     *
492
-     * @return array
493
-     */
494
-    public function getSchemaFormat()
495
-    {
496
-        return [];
497
-    }
498
-
499
-
500
-    /**
501
-     * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
502
-     * this method and return the properties for the schema.
503
-     * The reason this is not a property on the class is because there may be filters set on the values for the property
504
-     * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
505
-     *
506
-     * @return array
507
-     */
508
-    public function getSchemaProperties()
509
-    {
510
-        return [];
511
-    }
512
-
513
-
514
-    /**
515
-     * This returns the value of the $_schema_readonly property on the object.
516
-     *
517
-     * @return bool
518
-     */
519
-    public function getSchemaReadonly()
520
-    {
521
-        return true;
522
-    }
523
-
524
-
525
-    /**
526
-     * Returns whatever is set as the $_schema_type property for the object.
527
-     * Note: this will automatically add 'null' to the schema if the object is_nullable()
528
-     *
529
-     * @return string|array
530
-     */
531
-    public function getSchemaType()
532
-    {
533
-        return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
534
-    }
535
-
536
-
537
-    /**
538
-     * @param        $other_table
539
-     * @param        $other_table_alias
540
-     * @param        $other_table_column
541
-     * @param        $this_table_alias
542
-     * @param        $this_table_join_column
543
-     * @param string $extra_join_sql
544
-     * @return string
545
-     */
546
-    protected function _left_join(
547
-        $other_table,
548
-        $other_table_alias,
549
-        $other_table_column,
550
-        $this_table_alias,
551
-        $this_table_join_column,
552
-        $extra_join_sql = ''
553
-    ) {
554
-        return " LEFT JOIN " .
555
-               $other_table .
556
-               " AS " .
557
-               $other_table_alias .
558
-               " ON " .
559
-               $other_table_alias .
560
-               "." .
561
-               $other_table_column .
562
-               "=" .
563
-               $this_table_alias .
564
-               "." .
565
-               $this_table_join_column .
566
-               ($extra_join_sql ? " AND $extra_join_sql" : '');
567
-    }
20
+	/**
21
+	 * @var bool
22
+	 */
23
+	protected $_blocking_delete = false;
24
+
25
+	/**
26
+	 * If you try to delete "this_model", and there are related "other_models",
27
+	 * and this isn't null, then abandon the deletion and add this warning.
28
+	 * This effectively makes it impossible to delete "this_model" while there are
29
+	 * related "other_models" along this relation.
30
+	 *
31
+	 * @var string (internationalized)
32
+	 */
33
+	protected $_blocking_delete_error_message;
34
+
35
+	/**
36
+	 * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
37
+	 *
38
+	 * @var string eg Event, Question_Group, Registration
39
+	 */
40
+	private $_other_model_name;
41
+
42
+	/**
43
+	 * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
44
+	 *
45
+	 * @var string eg Event, Question_Group, Registration
46
+	 */
47
+	private $_this_model_name;
48
+
49
+	/**
50
+	 * this is typically used when calling the relation models to make sure they inherit any set timezone from the
51
+	 * initiating model.
52
+	 *
53
+	 * @var string
54
+	 */
55
+	protected $_timezone;
56
+
57
+
58
+	/**
59
+	 * Object representing the relationship between two models. This knows how to join the models,
60
+	 * get related models across the relation, and add-and-remove the relationships.
61
+	 *
62
+	 * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
63
+	 *                                               and add an error) the deletion of this model
64
+	 * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
65
+	 *                                               default
66
+	 */
67
+	public function __construct($block_deletes, $blocking_delete_error_message)
68
+	{
69
+		$this->_blocking_delete               = $block_deletes;
70
+		$this->_blocking_delete_error_message = $blocking_delete_error_message;
71
+	}
72
+
73
+
74
+	/**
75
+	 * @param $this_model_name
76
+	 * @param $other_model_name
77
+	 * @throws EE_Error
78
+	 */
79
+	public function _construct_finalize_set_models($this_model_name, $other_model_name)
80
+	{
81
+		$this->_this_model_name  = $this_model_name;
82
+		$this->_other_model_name = $other_model_name;
83
+		if (is_string($this->_blocking_delete)) {
84
+			throw new EE_Error(
85
+				sprintf(
86
+					esc_html__(
87
+						"When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
88
+						"event_espresso"
89
+					),
90
+					get_class($this),
91
+					$this_model_name,
92
+					$other_model_name,
93
+					$this->_blocking_delete
94
+				)
95
+			);
96
+		}
97
+	}
98
+
99
+
100
+	/**
101
+	 * entirely possible that relations may be called from a model and we need to make sure those relations have their
102
+	 * timezone set correctly.
103
+	 *
104
+	 * @param string $timezone timezone to set.
105
+	 */
106
+	public function set_timezone($timezone)
107
+	{
108
+		if (! empty($timezone)) {
109
+			$this->_timezone = $timezone;
110
+		}
111
+	}
112
+
113
+
114
+	/**
115
+	 * Deletes the related model objects which meet the query parameters. If no
116
+	 * parameters are specified, then all related model objects will be deleted.
117
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
118
+	 * model objects will only be soft-deleted.
119
+	 *
120
+	 * @param EE_Base_Class|int|string $model_object_or_id
121
+	 * @param array                    $query_params
122
+	 * @return int of how many related models got deleted
123
+	 * @throws EE_Error
124
+	 * @throws ReflectionException
125
+	 */
126
+	public function delete_all_related($model_object_or_id, $query_params = [])
127
+	{
128
+		// for each thing we would delete,
129
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
130
+		// determine if it's blocked by anything else before it can be deleted
131
+		$deleted_count = 0;
132
+		foreach ($related_model_objects as $related_model_object) {
133
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
134
+				$related_model_object,
135
+				$model_object_or_id
136
+			);
137
+			/* @var $model_object_or_id EE_Base_Class */
138
+			if (! $delete_is_blocked) {
139
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
140
+				$related_model_object->delete();
141
+				$deleted_count++;
142
+			}
143
+		}
144
+		return $deleted_count;
145
+	}
146
+
147
+
148
+	/**
149
+	 * Gets all the model objects of type of other model related to $model_object,
150
+	 * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
151
+	 * For both of those child classes, $model_object must be saved so that it has an ID before querying,
152
+	 * otherwise an error will be thrown. Note: by default we disable default_where_conditions
153
+	 * EE_Belongs_To_Relation doesn't need to be saved before querying.
154
+	 *
155
+	 * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
156
+	 * @param array             $query_params                            @see
157
+	 *                                                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
158
+	 * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
159
+	 * @return EE_Base_Class[]
160
+	 * @throws EE_Error
161
+	 * @throws ReflectionException
162
+	 */
163
+	public function get_all_related(
164
+		$model_object_or_id,
165
+		$query_params = [],
166
+		$values_already_prepared_by_model_object = false
167
+	) {
168
+		if ($values_already_prepared_by_model_object !== false) {
169
+			EE_Error::doing_it_wrong(
170
+				'EE_Model_Relation_Base::get_all_related',
171
+				esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
172
+				'4.8.1'
173
+			);
174
+		}
175
+		$query_params                                        =
176
+			$this->_disable_default_where_conditions_on_query_param($query_params);
177
+		$query_param_where_this_model_pk                     = $this->get_this_model()->get_this_model_name()
178
+															   .
179
+															   "."
180
+															   .
181
+															   $this->get_this_model()
182
+																	->get_primary_key_field()
183
+																	->get_name();
184
+		$model_object_id                                     = $this->_get_model_object_id($model_object_or_id);
185
+		$query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
186
+		return $this->get_other_model()->get_all($query_params);
187
+	}
188
+
189
+
190
+	/**
191
+	 * Gets the model which this relation establishes the relation TO (ie,
192
+	 * this relation object was defined on get_this_model(), get_other_model() is the other one)
193
+	 *
194
+	 * @return EEM_Base
195
+	 * @throws EE_Error
196
+	 * @throws ReflectionException
197
+	 */
198
+	public function get_other_model()
199
+	{
200
+		return $this->_get_model($this->_other_model_name);
201
+	}
202
+
203
+
204
+	/**
205
+	 * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
206
+	 * model objects
207
+	 *
208
+	 * @param       $this_obj_or_id
209
+	 * @param       $other_obj_or_id
210
+	 * @param array $where_query
211
+	 * @return bool
212
+	 */
213
+	abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = []);
214
+
215
+
216
+	/**
217
+	 * Alters the $query_params to disable default where conditions, unless otherwise specified
218
+	 *
219
+	 * @param array $query_params
220
+	 * @return array
221
+	 */
222
+	protected function _disable_default_where_conditions_on_query_param($query_params)
223
+	{
224
+		if (! isset($query_params['default_where_conditions'])) {
225
+			$query_params['default_where_conditions'] = 'none';
226
+		}
227
+		return $query_params;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets the model where this relation is defined.
233
+	 *
234
+	 * @return EEM_Base
235
+	 * @throws EE_Error
236
+	 * @throws ReflectionException
237
+	 */
238
+	public function get_this_model()
239
+	{
240
+		return $this->_get_model($this->_this_model_name);
241
+	}
242
+
243
+
244
+	/**
245
+	 * this just returns a model_object_id for incoming item that could be an object or id.
246
+	 *
247
+	 * @param EE_Base_Class|int $model_object_or_id model object or the primary key of this model
248
+	 * @return int
249
+	 * @throws EE_Error
250
+	 * @throws ReflectionException
251
+	 */
252
+	protected function _get_model_object_id($model_object_or_id)
253
+	{
254
+		$model_object_id = $model_object_or_id;
255
+		if ($model_object_or_id instanceof EE_Base_Class) {
256
+			$model_object_id = $model_object_or_id->ID();
257
+		}
258
+		if (! $model_object_id) {
259
+			throw new EE_Error(
260
+				sprintf(
261
+					esc_html__(
262
+						"Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
263
+						"event_espresso"
264
+					),
265
+					$this->get_other_model()->get_this_model_name(),
266
+					$this->get_this_model()->get_this_model_name()
267
+				)
268
+			);
269
+		}
270
+		return $model_object_id;
271
+	}
272
+
273
+
274
+	/**
275
+	 * Internally used by get_this_model() and get_other_model()
276
+	 *
277
+	 * @param string $model_name like Event, Question_Group, etc. omit the EEM_
278
+	 * @return EEM_Base
279
+	 * @throws EE_Error
280
+	 * @throws ReflectionException
281
+	 */
282
+	protected function _get_model($model_name)
283
+	{
284
+		$modelInstance = EE_Registry::instance()->load_model($model_name);
285
+		$modelInstance->set_timezone($this->_timezone);
286
+		return $modelInstance;
287
+	}
288
+
289
+
290
+	/**
291
+	 * Deletes the related model objects which meet the query parameters. If no
292
+	 * parameters are specified, then all related model objects will be deleted.
293
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
294
+	 * model objects will only be soft-deleted.
295
+	 *
296
+	 * @param EE_Base_Class|int|string $model_object_or_id
297
+	 * @param array                    $query_params
298
+	 * @return int of how many related models got deleted
299
+	 * @throws EE_Error
300
+	 * @throws ReflectionException
301
+	 */
302
+	public function delete_related_permanently($model_object_or_id, $query_params = [])
303
+	{
304
+		// for each thing we would delete,
305
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
306
+		// determine if it's blocked by anything else before it can be deleted
307
+		$deleted_count = 0;
308
+		foreach ($related_model_objects as $related_model_object) {
309
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
310
+				$related_model_object,
311
+				$model_object_or_id
312
+			);
313
+			/* @var $model_object_or_id EE_Base_Class */
314
+			if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
315
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
316
+				$deleted_count++;
317
+				if (! $delete_is_blocked) {
318
+					$related_model_object->delete_permanently();
319
+				} else {
320
+					// delete is blocked
321
+					// brent and darren, in this case, wanted to just soft delete it then
322
+					$related_model_object->delete();
323
+				}
324
+			} else {
325
+				// its not a soft-deletable thing anyways. do the normal logic.
326
+				if (! $delete_is_blocked) {
327
+					$this->remove_relation_to($model_object_or_id, $related_model_object);
328
+					$related_model_object->delete();
329
+					$deleted_count++;
330
+				}
331
+			}
332
+		}
333
+		return $deleted_count;
334
+	}
335
+
336
+
337
+	/**
338
+	 * Gets the SQL string for performing the join between this model and the other model.
339
+	 *
340
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
341
+	 * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
342
+	 *                                     other_model_primary_table.fk" etc
343
+	 */
344
+	abstract public function get_join_statement($model_relation_chain);
345
+
346
+
347
+	/**
348
+	 * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
349
+	 * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
350
+	 * relationship only allows this model to be related to a single other model of this type)
351
+	 *
352
+	 * @param       $this_obj_or_id
353
+	 * @param       $other_obj_or_id
354
+	 * @param array $extra_join_model_fields_n_values
355
+	 * @return EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
356
+	 *                        $other_obj_or_id)
357
+	 */
358
+	abstract public function add_relation_to(
359
+		$this_obj_or_id,
360
+		$other_obj_or_id,
361
+		$extra_join_model_fields_n_values = []
362
+	);
363
+
364
+
365
+	/**
366
+	 * Removes ALL relation instances for this relation obj
367
+	 *
368
+	 * @param EE_Base_Class|int $this_obj_or_id
369
+	 * @param array             $where_query_param @see
370
+	 *                                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
371
+	 * @return EE_Base_Class[]
372
+	 * @throws EE_Error
373
+	 * @throws ReflectionException
374
+	 */
375
+	public function remove_relations($this_obj_or_id, $where_query_param = [])
376
+	{
377
+		$related_things = $this->get_all_related($this_obj_or_id, [$where_query_param]);
378
+		$objs_removed   = [];
379
+		foreach ($related_things as $related_thing) {
380
+			$objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
381
+		}
382
+		return $objs_removed;
383
+	}
384
+
385
+
386
+	/**
387
+	 * If you aren't allowed to delete this model when there are related models across this
388
+	 * relation object, return true. Otherwise, if you can delete this model even though
389
+	 * related objects exist, returns false.
390
+	 *
391
+	 * @return boolean
392
+	 */
393
+	public function block_delete_if_related_models_exist()
394
+	{
395
+		return $this->_blocking_delete;
396
+	}
397
+
398
+
399
+	/**
400
+	 * Gets the error message to show
401
+	 *
402
+	 * @return string
403
+	 * @throws EE_Error
404
+	 * @throws ReflectionException
405
+	 */
406
+	public function get_deletion_error_message()
407
+	{
408
+		if ($this->_blocking_delete_error_message) {
409
+			return $this->_blocking_delete_error_message;
410
+		}
411
+		return sprintf(
412
+			esc_html__(
413
+				'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
414
+				"event_espresso"
415
+			),
416
+			$this->get_this_model()->item_name(),
417
+			$this->get_other_model()->item_name(),
418
+			$this->get_other_model()->item_name(2)
419
+		);
420
+	}
421
+
422
+
423
+	/**
424
+	 * This returns elements used to represent this field in the json schema.
425
+	 *
426
+	 * @link http://json-schema.org/
427
+	 * @return array
428
+	 * @throws EE_Error
429
+	 * @throws ReflectionException
430
+	 */
431
+	public function getSchema()
432
+	{
433
+		$schema = [
434
+			'description'   => $this->getSchemaDescription(),
435
+			'type'          => $this->getSchemaType(),
436
+			'relation'      => true,
437
+			'relation_type' => get_class($this),
438
+			'readonly'      => $this->getSchemaReadonly(),
439
+		];
440
+
441
+		if ($this instanceof EE_HABTM_Relation) {
442
+			$schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
443
+		}
444
+
445
+		if ($this->getSchemaType() === 'array') {
446
+			$schema['items'] = [
447
+				'type' => 'object',
448
+			];
449
+		}
450
+
451
+		return $schema;
452
+	}
453
+
454
+
455
+	/**
456
+	 * Returns whatever is set as the nice name for the object.
457
+	 *
458
+	 * @return string
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function getSchemaDescription()
463
+	{
464
+		$description = $this instanceof EE_Belongs_To_Relation
465
+			? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
466
+			: esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
467
+		return sprintf(
468
+			$description,
469
+			$this->get_other_model()->get_this_model_name(),
470
+			$this->get_this_model()->get_this_model_name()
471
+		);
472
+	}
473
+
474
+
475
+	/**
476
+	 * If a child class has enum values, they should override this method and provide a simple array
477
+	 * of the enum values.
478
+	 * The reason this is not a property on the class is because there may be filterable enum values that
479
+	 * are set on the instantiated object that could be filtered after construct.
480
+	 *
481
+	 * @return array
482
+	 */
483
+	public function getSchemaEnum()
484
+	{
485
+		return [];
486
+	}
487
+
488
+
489
+	/**
490
+	 * This returns the value of the $_schema_format property on the object.
491
+	 *
492
+	 * @return array
493
+	 */
494
+	public function getSchemaFormat()
495
+	{
496
+		return [];
497
+	}
498
+
499
+
500
+	/**
501
+	 * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
502
+	 * this method and return the properties for the schema.
503
+	 * The reason this is not a property on the class is because there may be filters set on the values for the property
504
+	 * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
505
+	 *
506
+	 * @return array
507
+	 */
508
+	public function getSchemaProperties()
509
+	{
510
+		return [];
511
+	}
512
+
513
+
514
+	/**
515
+	 * This returns the value of the $_schema_readonly property on the object.
516
+	 *
517
+	 * @return bool
518
+	 */
519
+	public function getSchemaReadonly()
520
+	{
521
+		return true;
522
+	}
523
+
524
+
525
+	/**
526
+	 * Returns whatever is set as the $_schema_type property for the object.
527
+	 * Note: this will automatically add 'null' to the schema if the object is_nullable()
528
+	 *
529
+	 * @return string|array
530
+	 */
531
+	public function getSchemaType()
532
+	{
533
+		return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
534
+	}
535
+
536
+
537
+	/**
538
+	 * @param        $other_table
539
+	 * @param        $other_table_alias
540
+	 * @param        $other_table_column
541
+	 * @param        $this_table_alias
542
+	 * @param        $this_table_join_column
543
+	 * @param string $extra_join_sql
544
+	 * @return string
545
+	 */
546
+	protected function _left_join(
547
+		$other_table,
548
+		$other_table_alias,
549
+		$other_table_column,
550
+		$this_table_alias,
551
+		$this_table_join_column,
552
+		$extra_join_sql = ''
553
+	) {
554
+		return " LEFT JOIN " .
555
+			   $other_table .
556
+			   " AS " .
557
+			   $other_table_alias .
558
+			   " ON " .
559
+			   $other_table_alias .
560
+			   "." .
561
+			   $other_table_column .
562
+			   "=" .
563
+			   $this_table_alias .
564
+			   "." .
565
+			   $this_table_join_column .
566
+			   ($extra_join_sql ? " AND $extra_join_sql" : '');
567
+	}
568 568
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
      */
106 106
     public function set_timezone($timezone)
107 107
     {
108
-        if (! empty($timezone)) {
108
+        if ( ! empty($timezone)) {
109 109
             $this->_timezone = $timezone;
110 110
         }
111 111
     }
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
                 $model_object_or_id
136 136
             );
137 137
             /* @var $model_object_or_id EE_Base_Class */
138
-            if (! $delete_is_blocked) {
138
+            if ( ! $delete_is_blocked) {
139 139
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
140 140
                 $related_model_object->delete();
141 141
                 $deleted_count++;
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
                                                                     ->get_primary_key_field()
183 183
                                                                     ->get_name();
184 184
         $model_object_id                                     = $this->_get_model_object_id($model_object_or_id);
185
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
185
+        $query_params[0][$query_param_where_this_model_pk] = $model_object_id;
186 186
         return $this->get_other_model()->get_all($query_params);
187 187
     }
188 188
 
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
      */
222 222
     protected function _disable_default_where_conditions_on_query_param($query_params)
223 223
     {
224
-        if (! isset($query_params['default_where_conditions'])) {
224
+        if ( ! isset($query_params['default_where_conditions'])) {
225 225
             $query_params['default_where_conditions'] = 'none';
226 226
         }
227 227
         return $query_params;
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
         if ($model_object_or_id instanceof EE_Base_Class) {
256 256
             $model_object_id = $model_object_or_id->ID();
257 257
         }
258
-        if (! $model_object_id) {
258
+        if ( ! $model_object_id) {
259 259
             throw new EE_Error(
260 260
                 sprintf(
261 261
                     esc_html__(
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
             if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
315 315
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
316 316
                 $deleted_count++;
317
-                if (! $delete_is_blocked) {
317
+                if ( ! $delete_is_blocked) {
318 318
                     $related_model_object->delete_permanently();
319 319
                 } else {
320 320
                     // delete is blocked
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
                 }
324 324
             } else {
325 325
                 // its not a soft-deletable thing anyways. do the normal logic.
326
-                if (! $delete_is_blocked) {
326
+                if ( ! $delete_is_blocked) {
327 327
                     $this->remove_relation_to($model_object_or_id, $related_model_object);
328 328
                     $related_model_object->delete();
329 329
                     $deleted_count++;
@@ -551,18 +551,18 @@  discard block
 block discarded – undo
551 551
         $this_table_join_column,
552 552
         $extra_join_sql = ''
553 553
     ) {
554
-        return " LEFT JOIN " .
555
-               $other_table .
556
-               " AS " .
557
-               $other_table_alias .
558
-               " ON " .
559
-               $other_table_alias .
560
-               "." .
561
-               $other_table_column .
562
-               "=" .
563
-               $this_table_alias .
564
-               "." .
565
-               $this_table_join_column .
554
+        return " LEFT JOIN ".
555
+               $other_table.
556
+               " AS ".
557
+               $other_table_alias.
558
+               " ON ".
559
+               $other_table_alias.
560
+               ".".
561
+               $other_table_column.
562
+               "=".
563
+               $this_table_alias.
564
+               ".".
565
+               $this_table_join_column.
566 566
                ($extra_join_sql ? " AND $extra_join_sql" : '');
567 567
     }
568 568
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6549 added lines, -6549 removed lines patch added patch discarded remove patch
@@ -37,6555 +37,6555 @@
 block discarded – undo
37 37
 abstract class EEM_Base extends EE_Base implements ResettableInterface
38 38
 {
39 39
 
40
-    /**
41
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
-     */
43
-    const caps_read       = 'read';
44
-
45
-    const caps_read_admin = 'read_admin';
46
-
47
-    const caps_edit       = 'edit';
48
-
49
-    const caps_delete     = 'delete';
50
-
51
-
52
-    /**
53
-     * constant used to show EEM_Base has not yet verified the db on this http request
54
-     */
55
-    const db_verified_none = 0;
56
-
57
-    /**
58
-     * constant used to show EEM_Base has verified the EE core db on this http request,
59
-     * but not the addons' dbs
60
-     */
61
-    const db_verified_core = 1;
62
-
63
-    /**
64
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
-     * the EE core db too)
66
-     */
67
-    const db_verified_addons = 2;
68
-
69
-    /**
70
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
-     *        registrations for non-trashed tickets for non-trashed datetimes)
73
-     */
74
-    const default_where_conditions_all = 'all';
75
-
76
-    /**
77
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
-     *        models which share tables with other models, this can return data for the wrong model.
82
-     */
83
-    const default_where_conditions_this_only = 'this_model_only';
84
-
85
-    /**
86
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
-     */
90
-    const default_where_conditions_others_only = 'other_models_only';
91
-
92
-    /**
93
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
96
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
-     *        (regardless of whether those events and venues are trashed)
98
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
-     *        events.
100
-     */
101
-    const default_where_conditions_minimum_all = 'minimum';
102
-
103
-    /**
104
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
-     *        not)
108
-     */
109
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
-
111
-    /**
112
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
-     *        it's possible it will return table entries for other models. You should use
115
-     *        EEM_Base::default_where_conditions_minimum_all instead.
116
-     */
117
-    const default_where_conditions_none = 'none';
118
-
119
-    /**
120
-     * when $_values_already_prepared_by_model_object equals this, we assume
121
-     * the data is just like form input that needs to have the model fields'
122
-     * prepare_for_set and prepare_for_use_in_db called on it
123
-     */
124
-    const not_prepared_by_model_object = 0;
125
-
126
-    /**
127
-     * when $_values_already_prepared_by_model_object equals this, we
128
-     * assume this value is coming from a model object and doesn't need to have
129
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
130
-     */
131
-    const prepared_by_model_object = 1;
132
-
133
-    /**
134
-     * when $_values_already_prepared_by_model_object equals this, we assume
135
-     * the values are already to be used in the database (ie no processing is done
136
-     * on them by the model's fields)
137
-     */
138
-    const prepared_for_use_in_db = 2;
139
-
140
-    /**
141
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
-     * They almost always WILL NOT, but it's not necessarily a requirement.
144
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
-     *
146
-     * @var boolean
147
-     */
148
-    private $_values_already_prepared_by_model_object = 0;
149
-
150
-
151
-    /**
152
-     * @var string
153
-     */
154
-    protected $singular_item = 'Item';
155
-
156
-    /**
157
-     * @var string
158
-     */
159
-    protected $plural_item = 'Items';
160
-
161
-    /**
162
-     * array of EE_Table objects for defining which tables comprise this model.
163
-     *
164
-     * @type EE_Table_Base[] $_tables
165
-     */
166
-    protected $_tables;
167
-
168
-    /**
169
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
-     *
173
-     * @var EE_Model_Field_Base[][] $_fields
174
-     */
175
-    protected $_fields;
176
-
177
-    /**
178
-     * array of different kinds of relations
179
-     *
180
-     * @var EE_Model_Relation_Base[] $_model_relations
181
-     */
182
-    protected $_model_relations;
183
-
184
-    /**
185
-     * @var EE_Index[] $_indexes
186
-     */
187
-    protected $_indexes = [];
188
-
189
-    /**
190
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
191
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
-     * by setting the same columns as used in these queries in the query yourself.
193
-     *
194
-     * @var EE_Default_Where_Conditions
195
-     */
196
-    protected $_default_where_conditions_strategy;
197
-
198
-    /**
199
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
-     * This is particularly useful when you want something between 'none' and 'default'
201
-     *
202
-     * @var EE_Default_Where_Conditions
203
-     */
204
-    protected $_minimum_where_conditions_strategy;
205
-
206
-    /**
207
-     * String describing how to find the "owner" of this model's objects.
208
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
-     * But when there isn't, this indicates which related model, or transiently-related model,
210
-     * has the foreign key to the wp_users table.
211
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
-     * related to events, and events have a foreign key to wp_users.
213
-     * On EEM_Transaction, this would be 'Transaction.Event'
214
-     *
215
-     * @var string
216
-     */
217
-    protected $_model_chain_to_wp_user = '';
218
-
219
-    /**
220
-     * String describing how to find the model with a password controlling access to this model. This property has the
221
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
-     * This value is the path of models to follow to arrive at the model with the password field.
223
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
-     * model with a password that should affect reading this on the front-end.
225
-     * Eg this is an empty string for the Event model because it has a password.
226
-     * This is null for the Registration model, because its event's password has no bearing on whether
227
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
-     * should hide tickets for datetimes for events that have a password set.
230
-     *
231
-     * @var string |null
232
-     */
233
-    protected $model_chain_to_password = null;
234
-
235
-    /**
236
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
-     * don't need it (particularly CPT models)
238
-     *
239
-     * @var bool
240
-     */
241
-    protected $_ignore_where_strategy = false;
242
-
243
-    /**
244
-     * String used in caps relating to this model. Eg, if the caps relating to this
245
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
-     *
247
-     * @var string. If null it hasn't been initialized yet. If false then we
248
-     * have indicated capabilities don't apply to this
249
-     */
250
-    protected $_caps_slug = null;
251
-
252
-    /**
253
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
-     * and next-level keys are capability names, and values are a
255
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
-     * they specify which context to use (ie, frontend, backend, edit or delete)
257
-     * and then each capability in the corresponding sub-array that they're missing
258
-     * adds the where conditions onto the query.
259
-     *
260
-     * @var array
261
-     */
262
-    protected $_cap_restrictions = [
263
-        self::caps_read       => [],
264
-        self::caps_read_admin => [],
265
-        self::caps_edit       => [],
266
-        self::caps_delete     => [],
267
-    ];
268
-
269
-    /**
270
-     * Array defining which cap restriction generators to use to create default
271
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
272
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
-     * automatically set this to false (not just null).
275
-     *
276
-     * @var EE_Restriction_Generator_Base[]
277
-     */
278
-    protected $_cap_restriction_generators = [];
279
-
280
-    /**
281
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
-     * maps to 'read' because when looking for relevant permissions we're going to use
284
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
285
-     *
286
-     * @var array
287
-     */
288
-    protected $_cap_contexts_to_cap_action_map = [
289
-        self::caps_read       => 'read',
290
-        self::caps_read_admin => 'read',
291
-        self::caps_edit       => 'edit',
292
-        self::caps_delete     => 'delete',
293
-    ];
294
-
295
-    /**
296
-     * Timezone
297
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
-     * EE_Datetime_Field data type will have access to it.
301
-     *
302
-     * @var string
303
-     */
304
-    protected $_timezone;
305
-
306
-
307
-    /**
308
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
-     * multisite.
310
-     *
311
-     * @var int
312
-     */
313
-    protected static $_model_query_blog_id;
314
-
315
-    /**
316
-     * A copy of _fields, except the array keys are the model names pointed to by
317
-     * the field
318
-     *
319
-     * @var EE_Model_Field_Base[]
320
-     */
321
-    private $_cache_foreign_key_to_fields = [];
322
-
323
-    /**
324
-     * Cached list of all the fields on the model, indexed by their name
325
-     *
326
-     * @var EE_Model_Field_Base[]
327
-     */
328
-    private $_cached_fields = null;
329
-
330
-    /**
331
-     * Cached list of all the fields on the model, except those that are
332
-     * marked as only pertinent to the database
333
-     *
334
-     * @var EE_Model_Field_Base[]
335
-     */
336
-    private $_cached_fields_non_db_only = null;
337
-
338
-    /**
339
-     * A cached reference to the primary key for quick lookup
340
-     *
341
-     * @var EE_Model_Field_Base
342
-     */
343
-    private $_primary_key_field = null;
344
-
345
-    /**
346
-     * Flag indicating whether this model has a primary key or not
347
-     *
348
-     * @var boolean
349
-     */
350
-    protected $_has_primary_key_field = null;
351
-
352
-    /**
353
-     * array in the format:  [ FK alias => full PK ]
354
-     * where keys are local column name aliases for foreign keys
355
-     * and values are the fully qualified column name for the primary key they represent
356
-     *  ex:
357
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
-     *
359
-     * @var array $foreign_key_aliases
360
-     */
361
-    protected $foreign_key_aliases = [];
362
-
363
-    /**
364
-     * Whether or not this model is based off a table in WP core only (CPTs should set
365
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
-     * This should be true for models that deal with data that should exist independent of EE.
367
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
369
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
371
-     *
372
-     * @var boolean
373
-     */
374
-    protected $_wp_core_model = false;
375
-
376
-    /**
377
-     * @var bool stores whether this model has a password field or not.
378
-     * null until initialized by hasPasswordField()
379
-     */
380
-    protected $has_password_field;
381
-
382
-    /**
383
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
-     */
385
-    protected $password_field;
386
-
387
-    /**
388
-     *    List of valid operators that can be used for querying.
389
-     * The keys are all operators we'll accept, the values are the real SQL
390
-     * operators used
391
-     *
392
-     * @var array
393
-     */
394
-    protected $_valid_operators = [
395
-        '='           => '=',
396
-        '<='          => '<=',
397
-        '<'           => '<',
398
-        '>='          => '>=',
399
-        '>'           => '>',
400
-        '!='          => '!=',
401
-        'LIKE'        => 'LIKE',
402
-        'like'        => 'LIKE',
403
-        'NOT_LIKE'    => 'NOT LIKE',
404
-        'not_like'    => 'NOT LIKE',
405
-        'NOT LIKE'    => 'NOT LIKE',
406
-        'not like'    => 'NOT LIKE',
407
-        'IN'          => 'IN',
408
-        'in'          => 'IN',
409
-        'NOT_IN'      => 'NOT IN',
410
-        'not_in'      => 'NOT IN',
411
-        'NOT IN'      => 'NOT IN',
412
-        'not in'      => 'NOT IN',
413
-        'between'     => 'BETWEEN',
414
-        'BETWEEN'     => 'BETWEEN',
415
-        'IS_NOT_NULL' => 'IS NOT NULL',
416
-        'is_not_null' => 'IS NOT NULL',
417
-        'IS NOT NULL' => 'IS NOT NULL',
418
-        'is not null' => 'IS NOT NULL',
419
-        'IS_NULL'     => 'IS NULL',
420
-        'is_null'     => 'IS NULL',
421
-        'IS NULL'     => 'IS NULL',
422
-        'is null'     => 'IS NULL',
423
-        'REGEXP'      => 'REGEXP',
424
-        'regexp'      => 'REGEXP',
425
-        'NOT_REGEXP'  => 'NOT REGEXP',
426
-        'not_regexp'  => 'NOT REGEXP',
427
-        'NOT REGEXP'  => 'NOT REGEXP',
428
-        'not regexp'  => 'NOT REGEXP',
429
-    ];
430
-
431
-    /**
432
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
-     *
434
-     * @var array
435
-     */
436
-    protected $_in_style_operators = ['IN', 'NOT IN'];
437
-
438
-    /**
439
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
-     * '12-31-2012'"
441
-     *
442
-     * @var array
443
-     */
444
-    protected $_between_style_operators = ['BETWEEN'];
445
-
446
-    /**
447
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
-
453
-    /**
454
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
-     * on a join table.
456
-     *
457
-     * @var array
458
-     */
459
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
-
461
-    /**
462
-     * Allowed values for $query_params['order'] for ordering in queries
463
-     *
464
-     * @var array
465
-     */
466
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
-
468
-    /**
469
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
471
-     *
472
-     * @var array
473
-     */
474
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
-
476
-    /**
477
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
479
-     *
480
-     * @var array
481
-     */
482
-    private $_allowed_query_params = [
483
-        0,
484
-        'limit',
485
-        'order_by',
486
-        'group_by',
487
-        'having',
488
-        'force_join',
489
-        'order',
490
-        'on_join_limit',
491
-        'default_where_conditions',
492
-        'caps',
493
-        'extra_selects',
494
-        'exclude_protected',
495
-    ];
496
-
497
-    /**
498
-     * All the data types that can be used in $wpdb->prepare statements.
499
-     *
500
-     * @var array
501
-     */
502
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
-
504
-    /**
505
-     * @var EE_Registry $EE
506
-     */
507
-    protected $EE = null;
508
-
509
-
510
-    /**
511
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
-     *
513
-     * @var int
514
-     */
515
-    protected $_show_next_x_db_queries = 0;
516
-
517
-    /**
518
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
-     * WHERE, GROUP_BY, etc.
521
-     *
522
-     * @var CustomSelects
523
-     */
524
-    protected $_custom_selections = [];
525
-
526
-    /**
527
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
-     * caches every model object we've fetched from the DB on this request
529
-     *
530
-     * @var array
531
-     */
532
-    protected $_entity_map;
533
-
534
-    /**
535
-     * @var LoaderInterface $loader
536
-     */
537
-    private static $loader;
538
-
539
-    /**
540
-     * indicates whether an EEM_Base child has already re-verified the DB
541
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
542
-     * looking like EEM_Base::db_verified_*
543
-     *
544
-     * @var int - 0 = none, 1 = core, 2 = addons
545
-     */
546
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
547
-
548
-
549
-    /**
550
-     * About all child constructors:
551
-     * they should define the _tables, _fields and _model_relations arrays.
552
-     * Should ALWAYS be called after child constructor.
553
-     * In order to make the child constructors to be as simple as possible, this parent constructor
554
-     * finalizes constructing all the object's attributes.
555
-     * Generally, rather than requiring a child to code
556
-     * $this->_tables = array(
557
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
-     *        ...);
559
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
-     * each EE_Table has a function to set the table's alias after the constructor, using
561
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
-     * do something similar.
563
-     *
564
-     * @param string $timezone
565
-     * @throws EE_Error
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                /** @var $table_obj EE_Secondary_Table */
599
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
-            }
601
-        }
602
-        /**
603
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
-         * EE_Register_Model_Extension
605
-         *
606
-         * @param EE_Model_Field_Base[] $_fields
607
-         */
608
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
-        $this->_invalidate_field_caches();
610
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
612
-                throw new EE_Error(
613
-                    sprintf(
614
-                        esc_html__(
615
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
-                            'event_espresso'
617
-                        ),
618
-                        $table_alias,
619
-                        implode(",", $this->_fields)
620
-                    )
621
-                );
622
-            }
623
-            foreach ($fields_for_table as $field_name => $field_obj) {
624
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
-                // primary key field base has a slightly different _construct_finalize
626
-                /** @var $field_obj EE_Model_Field_Base */
627
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
-            }
629
-        }
630
-        // everything is related to Extra_Meta
631
-        if (get_class($this) !== 'EEM_Extra_Meta') {
632
-            // make extra meta related to everything, but don't block deleting things just
633
-            // because they have related extra meta info. For now just orphan those extra meta
634
-            // in the future we should automatically delete them
635
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
-        }
637
-        // and change logs
638
-        if (get_class($this) !== 'EEM_Change_Log') {
639
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
-        }
641
-        /**
642
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
-         * EE_Register_Model_Extension
644
-         *
645
-         * @param EE_Model_Relation_Base[] $_model_relations
646
-         */
647
-        $this->_model_relations = (array) apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
649
-            $this->_model_relations
650
-        );
651
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
652
-            /** @var $relation_obj EE_Model_Relation_Base */
653
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
-        }
655
-        foreach ($this->_indexes as $index_name => $index_obj) {
656
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
-        }
658
-        $this->set_timezone($timezone);
659
-        // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
661
-            // nothing was set during child constructor, so set default
662
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
-        }
664
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
666
-            // nothing was set during child constructor, so set default
667
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
-        }
669
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
671
-        // to indicate to NOT set it, set it to the logical default
672
-        if ($this->_caps_slug === null) {
673
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
-        }
675
-        // initialize the standard cap restriction generators if none were specified by the child constructor
676
-        if ($this->_cap_restriction_generators !== false) {
677
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
-                        new EE_Restriction_Generator_Protected(),
682
-                        $cap_context,
683
-                        $this
684
-                    );
685
-                }
686
-            }
687
-        }
688
-        // if there are cap restriction generators, use them to make the default cap restrictions
689
-        if ($this->_cap_restriction_generators !== false) {
690
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
692
-                    continue;
693
-                }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
-                    throw new EE_Error(
696
-                        sprintf(
697
-                            esc_html__(
698
-                                '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.',
699
-                                'event_espresso'
700
-                            ),
701
-                            $context,
702
-                            $this->get_this_model_name()
703
-                        )
704
-                    );
705
-                }
706
-                $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
708
-                    $generator_object->_construct_finalize($this, $action);
709
-                }
710
-            }
711
-        }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
713
-    }
714
-
715
-
716
-    /**
717
-     * Used to set the $_model_query_blog_id static property.
718
-     *
719
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
-     *                      value for get_current_blog_id() will be used.
721
-     */
722
-    public static function set_model_query_blog_id($blog_id = 0)
723
-    {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
725
-    }
726
-
727
-
728
-    /**
729
-     * Returns whatever is set as the internal $model_query_blog_id.
730
-     *
731
-     * @return int
732
-     */
733
-    public static function get_model_query_blog_id()
734
-    {
735
-        return EEM_Base::$_model_query_blog_id;
736
-    }
737
-
738
-
739
-    /**
740
-     * This function is a singleton method used to instantiate the Espresso_model object
741
-     *
742
-     * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
-     *                                (and any incoming timezone data that gets saved).
744
-     *                                Note this just sends the timezone info to the date time model field objects.
745
-     *                                Default is NULL
746
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
-     * @return EEM_Base (as in the concrete child class)
748
-     * @throws EE_Error
749
-     * @throws InvalidArgumentException
750
-     * @throws InvalidDataTypeException
751
-     * @throws InvalidInterfaceException
752
-     */
753
-    public static function instance($timezone = '')
754
-    {
755
-        // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
757
-            // instantiate Espresso_model
758
-            static::$_instance = new static(
759
-                $timezone,
760
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
-            );
762
-        }
763
-        // Espresso model object
764
-        return static::$_instance;
765
-    }
766
-
767
-
768
-    /**
769
-     * resets the model and returns it
770
-     *
771
-     * @param string $timezone
772
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
-     * all its properties reset; if it wasn't instantiated, returns null)
774
-     * @throws EE_Error
775
-     * @throws ReflectionException
776
-     * @throws InvalidArgumentException
777
-     * @throws InvalidDataTypeException
778
-     * @throws InvalidInterfaceException
779
-     */
780
-    public static function reset($timezone = '')
781
-    {
782
-        if (static::$_instance instanceof EEM_Base) {
783
-            // let's try to NOT swap out the current instance for a new one
784
-            // because if someone has a reference to it, we can't remove their reference
785
-            // so it's best to keep using the same reference, but change the original object
786
-            // reset all its properties to their original values as defined in the class
787
-            $r                 = new ReflectionClass(get_class(static::$_instance));
788
-            $static_properties = $r->getStaticProperties();
789
-            foreach ($r->getDefaultProperties() as $property => $value) {
790
-                // don't set instance to null like it was originally,
791
-                // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
793
-                    static::$_instance->{$property} = $value;
794
-                }
795
-            }
796
-            EEH_DTT_Helper::resetDefaultTimezoneString();
797
-            // and then directly call its constructor again, like we would if we were creating a new one
798
-            static::$_instance->__construct(
799
-                $timezone,
800
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
-            );
802
-            return static::instance();
803
-        }
804
-        return null;
805
-    }
806
-
807
-
808
-    /**
809
-     * @return LoaderInterface
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     */
814
-    private static function getLoader()
815
-    {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
817
-            EEM_Base::$loader = LoaderFactory::getLoader();
818
-        }
819
-        return EEM_Base::$loader;
820
-    }
821
-
822
-
823
-    /**
824
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
-     *
826
-     * @param boolean $translated return localized strings or JUST the array.
827
-     * @return array
828
-     * @throws EE_Error
829
-     * @throws InvalidArgumentException
830
-     * @throws InvalidDataTypeException
831
-     * @throws InvalidInterfaceException
832
-     * @throws ReflectionException
833
-     */
834
-    public function status_array($translated = false)
835
-    {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
837
-            return [];
838
-        }
839
-        $model_name   = $this->get_this_model_name();
840
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
-        $status_array = [];
843
-        foreach ($stati as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
845
-        }
846
-        return $translated
847
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
-            : $status_array;
849
-    }
850
-
851
-
852
-    /**
853
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
-     *
855
-     * @param array $query_params             see github link below for more info
856
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
-     *                                        EEM_Transaction::instance()->get_all( array( array(
861
-     *                                        'OR'=>array(
862
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
-     *                                        )
865
-     *                                        ),
866
-     *                                        'limit'=>10,
867
-     *                                        'group_by'=>'TXN_ID'
868
-     *                                        ));
869
-     *                                        get all the answers to the question titled "shirt size" for event with id
870
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
-     *                                        'Question.QST_display_text'=>'shirt size',
872
-     *                                        'Registration.Event.EVT_ID'=>12
873
-     *                                        ),
874
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
875
-     *                                        ));
876
-     * @throws EE_Error
877
-     * @throws ReflectionException
878
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
-     *                                        or if you have the development copy of EE you can view this at the path:
880
-     *                                        /docs/G--Model-System/model-query-params.md
881
-     */
882
-    public function get_all($query_params = [])
883
-    {
884
-        if (
885
-            isset($query_params['limit'])
886
-            && ! isset($query_params['group_by'])
887
-        ) {
888
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
-        }
890
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
-    }
892
-
893
-
894
-    /**
895
-     * Modifies the query parameters so we only get back model objects
896
-     * that "belong" to the current user
897
-     *
898
-     * @param array $query_params see github link below for more info
899
-     * @return array
900
-     * @throws ReflectionException
901
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     */
903
-    public function alter_query_params_to_only_include_mine($query_params = [])
904
-    {
905
-        $wp_user_field_name = $this->wp_user_field_name();
906
-        if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
-        }
909
-        return $query_params;
910
-    }
911
-
912
-
913
-    /**
914
-     * Returns the name of the field's name that points to the WP_User table
915
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
-     * foreign key to the WP_User table)
917
-     *
918
-     * @return string|boolean string on success, boolean false when there is no
919
-     * foreign key to the WP_User table
920
-     * @throws ReflectionException
921
-     */
922
-    public function wp_user_field_name()
923
-    {
924
-        try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
926
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
-                $last_model_name              = end($models_to_follow_to_wp_users);
928
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
-            } else {
931
-                $model_with_fk_to_wp_users = $this;
932
-                $model_chain_to_wp_user    = '';
933
-            }
934
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
936
-        } catch (EE_Error $e) {
937
-            return false;
938
-        }
939
-    }
940
-
941
-
942
-    /**
943
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
944
-     * (or transiently-related model) has a foreign key to the wp_users table;
945
-     * useful for finding if model objects of this type are 'owned' by the current user.
946
-     * This is an empty string when the foreign key is on this model and when it isn't,
947
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
948
-     * (or transiently-related model)
949
-     *
950
-     * @return string
951
-     */
952
-    public function model_chain_to_wp_user()
953
-    {
954
-        return $this->_model_chain_to_wp_user;
955
-    }
956
-
957
-
958
-    /**
959
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
-     * like how registrations don't have a foreign key to wp_users, but the
961
-     * events they are for are), or is unrelated to wp users.
962
-     * generally available
963
-     *
964
-     * @return boolean
965
-     */
966
-    public function is_owned()
967
-    {
968
-        if ($this->model_chain_to_wp_user()) {
969
-            return true;
970
-        }
971
-        try {
972
-            $this->get_foreign_key_to('WP_User');
973
-            return true;
974
-        } catch (EE_Error $e) {
975
-            return false;
976
-        }
977
-    }
978
-
979
-
980
-    /**
981
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
-     * the model)
984
-     *
985
-     * @param array  $query_params
986
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
-     *                                  fields on the model, and the models we joined to in the query. However, you can
989
-     *                                  override this and set the select to "*", or a specific column name, like
990
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
-     *                                  the aliases used to refer to this selection, and values are to be
993
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws ReflectionException
999
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
-     */
1001
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
-    {
1003
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
-        $select_expressions       = $columns_to_select === null
1006
-            ? $this->_construct_default_select_sql($model_query_info)
1007
-            : '';
1008
-        if ($this->_custom_selections instanceof CustomSelects) {
1009
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
-            $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1012
-                : $custom_expressions;
1013
-        }
1014
-
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
-     * method of including extra select information.
1024
-     *
1025
-     * @param array             $query_params
1026
-     * @param null|array|string $columns_to_select
1027
-     * @return null|CustomSelects
1028
-     * @throws InvalidArgumentException
1029
-     */
1030
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
-    {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
-            return null;
1034
-        }
1035
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
-        return new CustomSelects($selects);
1038
-    }
1039
-
1040
-
1041
-    /**
1042
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1043
-     * but you can use the model query params to more easily
1044
-     * take care of joins, field preparation etc.
1045
-     *
1046
-     * @param array  $query_params
1047
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1050
-     *                                  override this and set the select to "*", or a specific column name, like
1051
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
-     *                                  the aliases used to refer to this selection, and values are to be
1054
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
-     * @throws EE_Error
1058
-     * @throws ReflectionException
1059
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
-     */
1061
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
-    {
1063
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * For creating a custom select statement
1069
-     *
1070
-     * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
-     *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
-     *                                        selection SQL, and 1=>is the datatype
1073
-     * @return string
1074
-     * @throws EE_Error
1075
-     */
1076
-    private function _construct_select_from_input($columns_to_select)
1077
-    {
1078
-        if (is_array($columns_to_select)) {
1079
-            $select_sql_array = [];
1080
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype,
1089
-                            $alias
1090
-                        )
1091
-                    );
1092
-                }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
-                    throw new EE_Error(
1095
-                        sprintf(
1096
-                            esc_html__(
1097
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
-                                'event_espresso'
1099
-                            ),
1100
-                            $selection_and_datatype[1],
1101
-                            $selection_and_datatype[0],
1102
-                            $alias,
1103
-                            implode(', ', $this->_valid_wpdb_data_types)
1104
-                        )
1105
-                    );
1106
-                }
1107
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
-            }
1109
-            $columns_to_select_string = implode(', ', $select_sql_array);
1110
-        } else {
1111
-            $columns_to_select_string = $columns_to_select;
1112
-        }
1113
-        return $columns_to_select_string;
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
-     *
1120
-     * @return string
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function primary_key_name()
1124
-    {
1125
-        return $this->get_primary_key_field()->get_name();
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
-     * If there is no primary key on this model, $id is treated as primary key string
1132
-     *
1133
-     * @param mixed $id int or string, depending on the type of the model's primary key
1134
-     * @return EE_Base_Class
1135
-     * @throws EE_Error
1136
-     * @throws ReflectionException
1137
-     */
1138
-    public function get_one_by_ID($id)
1139
-    {
1140
-        if ($this->get_from_entity_map($id)) {
1141
-            return $this->get_from_entity_map($id);
1142
-        }
1143
-        return $this->get_one(
1144
-            $this->alter_query_params_to_restrict_by_ID(
1145
-                $id,
1146
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
-            )
1148
-        );
1149
-    }
1150
-
1151
-
1152
-    /**
1153
-     * Alters query parameters to only get items with this ID are returned.
1154
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1155
-     * or could just be a simple primary key ID
1156
-     *
1157
-     * @param int   $id
1158
-     * @param array $query_params see github link below for more info
1159
-     * @return array of normal query params,
1160
-     * @throws EE_Error
1161
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1162
-     */
1163
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1164
-    {
1165
-        if (! isset($query_params[0])) {
1166
-            $query_params[0] = [];
1167
-        }
1168
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1169
-        if ($conditions_from_id === null) {
1170
-            $query_params[0][ $this->primary_key_name() ] = $id;
1171
-        } else {
1172
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1173
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1174
-        }
1175
-        return $query_params;
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1181
-     * array. If no item is found, null is returned.
1182
-     *
1183
-     * @param array $query_params like EEM_Base's $query_params variable.
1184
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1185
-     * @throws EE_Error
1186
-     * @throws ReflectionException
1187
-     */
1188
-    public function get_one($query_params = [])
1189
-    {
1190
-        if (! is_array($query_params)) {
1191
-            EE_Error::doing_it_wrong(
1192
-                'EEM_Base::get_one',
1193
-                sprintf(
1194
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1195
-                    gettype($query_params)
1196
-                ),
1197
-                '4.6.0'
1198
-            );
1199
-            $query_params = [];
1200
-        }
1201
-        $query_params['limit'] = 1;
1202
-        $items                 = $this->get_all($query_params);
1203
-        if (empty($items)) {
1204
-            return null;
1205
-        }
1206
-        return array_shift($items);
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     * Returns the next x number of items in sequence from the given value as
1212
-     * found in the database matching the given query conditions.
1213
-     *
1214
-     * @param mixed $current_field_value    Value used for the reference point.
1215
-     * @param null  $field_to_order_by      What field is used for the
1216
-     *                                      reference point.
1217
-     * @param int   $limit                  How many to return.
1218
-     * @param array $query_params           Extra conditions on the query.
1219
-     * @param null  $columns_to_select      If left null, then an array of
1220
-     *                                      EE_Base_Class objects is returned,
1221
-     *                                      otherwise you can indicate just the
1222
-     *                                      columns you want returned.
1223
-     * @return EE_Base_Class[]|array
1224
-     * @throws EE_Error
1225
-     * @throws ReflectionException
1226
-     */
1227
-    public function next_x(
1228
-        $current_field_value,
1229
-        $field_to_order_by = null,
1230
-        $limit = 1,
1231
-        $query_params = [],
1232
-        $columns_to_select = null
1233
-    ) {
1234
-        return $this->_get_consecutive(
1235
-            $current_field_value,
1236
-            '>',
1237
-            $field_to_order_by,
1238
-            $limit,
1239
-            $query_params,
1240
-            $columns_to_select
1241
-        );
1242
-    }
1243
-
1244
-
1245
-    /**
1246
-     * Returns the previous x number of items in sequence from the given value
1247
-     * as found in the database matching the given query conditions.
1248
-     *
1249
-     * @param mixed $current_field_value    Value used for the reference point.
1250
-     * @param null  $field_to_order_by      What field is used for the
1251
-     *                                      reference point.
1252
-     * @param int   $limit                  How many to return.
1253
-     * @param array $query_params           Extra conditions on the query.
1254
-     * @param null  $columns_to_select      If left null, then an array of
1255
-     *                                      EE_Base_Class objects is returned,
1256
-     *                                      otherwise you can indicate just the
1257
-     *                                      columns you want returned.
1258
-     * @return EE_Base_Class[]|array
1259
-     * @throws EE_Error
1260
-     * @throws ReflectionException
1261
-     */
1262
-    public function previous_x(
1263
-        $current_field_value,
1264
-        $field_to_order_by = null,
1265
-        $limit = 1,
1266
-        $query_params = [],
1267
-        $columns_to_select = null
1268
-    ) {
1269
-        return $this->_get_consecutive(
1270
-            $current_field_value,
1271
-            '<',
1272
-            $field_to_order_by,
1273
-            $limit,
1274
-            $query_params,
1275
-            $columns_to_select
1276
-        );
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * Returns the next item in sequence from the given value as found in the
1282
-     * database matching the given query conditions.
1283
-     *
1284
-     * @param mixed $current_field_value    Value used for the reference point.
1285
-     * @param null  $field_to_order_by      What field is used for the
1286
-     *                                      reference point.
1287
-     * @param array $query_params           Extra conditions on the query.
1288
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1289
-     *                                      object is returned, otherwise you
1290
-     *                                      can indicate just the columns you
1291
-     *                                      want and a single array indexed by
1292
-     *                                      the columns will be returned.
1293
-     * @return EE_Base_Class|null|array()
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function next(
1298
-        $current_field_value,
1299
-        $field_to_order_by = null,
1300
-        $query_params = [],
1301
-        $columns_to_select = null
1302
-    ) {
1303
-        $results = $this->_get_consecutive(
1304
-            $current_field_value,
1305
-            '>',
1306
-            $field_to_order_by,
1307
-            1,
1308
-            $query_params,
1309
-            $columns_to_select
1310
-        );
1311
-        return empty($results) ? null : reset($results);
1312
-    }
1313
-
1314
-
1315
-    /**
1316
-     * Returns the previous item in sequence from the given value as found in
1317
-     * the database matching the given query conditions.
1318
-     *
1319
-     * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1321
-     *                                      reference point.
1322
-     * @param array $query_params           Extra conditions on the query.
1323
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
-     *                                      object is returned, otherwise you
1325
-     *                                      can indicate just the columns you
1326
-     *                                      want and a single array indexed by
1327
-     *                                      the columns will be returned.
1328
-     * @return EE_Base_Class|null|array()
1329
-     * @throws EE_Error
1330
-     * @throws ReflectionException
1331
-     */
1332
-    public function previous(
1333
-        $current_field_value,
1334
-        $field_to_order_by = null,
1335
-        $query_params = [],
1336
-        $columns_to_select = null
1337
-    ) {
1338
-        $results = $this->_get_consecutive(
1339
-            $current_field_value,
1340
-            '<',
1341
-            $field_to_order_by,
1342
-            1,
1343
-            $query_params,
1344
-            $columns_to_select
1345
-        );
1346
-        return empty($results) ? null : reset($results);
1347
-    }
1348
-
1349
-
1350
-    /**
1351
-     * Returns the a consecutive number of items in sequence from the given
1352
-     * value as found in the database matching the given query conditions.
1353
-     *
1354
-     * @param mixed  $current_field_value   Value used for the reference point.
1355
-     * @param string $operand               What operand is used for the sequence.
1356
-     * @param string $field_to_order_by     What field is used for the reference point.
1357
-     * @param int    $limit                 How many to return.
1358
-     * @param array  $query_params          Extra conditions on the query.
1359
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1360
-     *                                      otherwise you can indicate just the columns you want returned.
1361
-     * @return EE_Base_Class[]|array
1362
-     * @throws EE_Error
1363
-     * @throws ReflectionException
1364
-     */
1365
-    protected function _get_consecutive(
1366
-        $current_field_value,
1367
-        $operand = '>',
1368
-        $field_to_order_by = null,
1369
-        $limit = 1,
1370
-        $query_params = [],
1371
-        $columns_to_select = null
1372
-    ) {
1373
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1374
-        if (empty($field_to_order_by)) {
1375
-            if ($this->has_primary_key_field()) {
1376
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1377
-            } else {
1378
-                if (WP_DEBUG) {
1379
-                    throw new EE_Error(
1380
-                        esc_html__(
1381
-                            '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).',
1382
-                            'event_espresso'
1383
-                        )
1384
-                    );
1385
-                }
1386
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1387
-                return [];
1388
-            }
1389
-        }
1390
-        if (! is_array($query_params)) {
1391
-            EE_Error::doing_it_wrong(
1392
-                'EEM_Base::_get_consecutive',
1393
-                sprintf(
1394
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1395
-                    gettype($query_params)
1396
-                ),
1397
-                '4.6.0'
1398
-            );
1399
-            $query_params = [];
1400
-        }
1401
-        // let's add the where query param for consecutive look up.
1402
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1403
-        $query_params['limit']                 = $limit;
1404
-        // set direction
1405
-        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1406
-        $query_params['order_by'] = $operand === '>'
1407
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1408
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1409
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1410
-        if (empty($columns_to_select)) {
1411
-            return $this->get_all($query_params);
1412
-        }
1413
-        // getting just the fields
1414
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1415
-    }
1416
-
1417
-
1418
-    /**
1419
-     * This sets the _timezone property after model object has been instantiated.
1420
-     *
1421
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1422
-     */
1423
-    public function set_timezone($timezone = '')
1424
-    {
1425
-        static $set_in_progress = false;
1426
-        // if incoming timezone string is empty, then use the existing
1427
-        $valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1428
-            ? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1429
-            : $this->_timezone;
1430
-        // do NOT set the timezone if we are already in the process of setting the timezone
1431
-        // OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1432
-        // OR the existing timezone is already set and the validated value is the same as the existing timezone
1433
-        if (
1434
-            $set_in_progress
1435
-            || (
1436
-                ! empty($this->_timezone)
1437
-                && (
1438
-                    empty($timezone) || $valid_timezone === $this->_timezone
1439
-                )
1440
-            )
1441
-        ) {
1442
-            return;
1443
-        }
1444
-        $set_in_progress = true;
1445
-        $this->_timezone = $valid_timezone ? $valid_timezone : EEH_DTT_Helper::get_valid_timezone_string();
1446
-        // note we need to loop through relations and set the timezone on those objects as well.
1447
-        foreach ($this->_model_relations as $relation) {
1448
-            $relation->set_timezone($this->_timezone);
1449
-        }
1450
-        // and finally we do the same for any datetime fields
1451
-        foreach ($this->_fields as $field) {
1452
-            if ($field instanceof EE_Datetime_Field) {
1453
-                $field->set_timezone($this->_timezone);
1454
-            }
1455
-        }
1456
-        $set_in_progress = false;
1457
-    }
1458
-
1459
-
1460
-    /**
1461
-     * This just returns whatever is set for the current timezone.
1462
-     *
1463
-     * @access public
1464
-     * @return string
1465
-     */
1466
-    public function get_timezone()
1467
-    {
1468
-        if (empty($this->_timezone)) {
1469
-            $this->set_timezone();
1470
-        }
1471
-        return $this->_timezone;
1472
-    }
1473
-
1474
-
1475
-    /**
1476
-     * This returns the date formats set for the given field name and also ensures that
1477
-     * $this->_timezone property is set correctly.
1478
-     *
1479
-     * @param string $field_name The name of the field the formats are being retrieved for.
1480
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1481
-     * @return array formats in an array with the date format first, and the time format last.
1482
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1483
-     * @since 4.6.x
1484
-     */
1485
-    public function get_formats_for($field_name, $pretty = false)
1486
-    {
1487
-        $field_settings = $this->field_settings_for($field_name);
1488
-        // if not a valid EE_Datetime_Field then throw error
1489
-        if (! $field_settings instanceof EE_Datetime_Field) {
1490
-            throw new EE_Error(
1491
-                sprintf(
1492
-                    esc_html__(
1493
-                        '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.',
1494
-                        'event_espresso'
1495
-                    ),
1496
-                    $field_name
1497
-                )
1498
-            );
1499
-        }
1500
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1501
-        $field_timezone = $field_settings->get_timezone();
1502
-        if (empty($this->_timezone && $field_timezone)) {
1503
-            $this->set_timezone();
1504
-        } else {
1505
-            // or vice versa if the field TZ isn't set
1506
-            $model_timezone = $this->get_timezone();
1507
-            $field_settings->set_timezone($model_timezone);
1508
-        }
1509
-
1510
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1511
-    }
1512
-
1513
-
1514
-    /**
1515
-     * This returns the current time in a format setup for a query on this model.
1516
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1517
-     * it will return:
1518
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1519
-     *  NOW
1520
-     *  - or a unix timestamp (equivalent to time())
1521
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1522
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1523
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1524
-     *
1525
-     * @param string $field_name       The field the current time is needed for.
1526
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1527
-     *                                 formatted string matching the set format for the field in the set timezone will
1528
-     *                                 be returned.
1529
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1530
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1531
-     *                                 exception is triggered.
1532
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1533
-     * @throws Exception
1534
-     * @since 4.6.x
1535
-     */
1536
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1537
-    {
1538
-        $formats  = $this->get_formats_for($field_name);
1539
-        $DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1540
-        if ($timestamp) {
1541
-            return $DateTime->format('U');
1542
-        }
1543
-        // not returning timestamp, so return formatted string in timezone.
1544
-        switch ($what) {
1545
-            case 'time':
1546
-                return $DateTime->format($formats[1]);
1547
-            case 'date':
1548
-                return $DateTime->format($formats[0]);
1549
-            default:
1550
-                return $DateTime->format(implode(' ', $formats));
1551
-        }
1552
-    }
1553
-
1554
-
1555
-    /**
1556
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1557
-     * for the model are.  Returns a DateTime object.
1558
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1559
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1560
-     * ignored.
1561
-     *
1562
-     * @param string $field_name    The field being setup.
1563
-     * @param string $timestring    The date time string being used.
1564
-     * @param string $format        The format for the time string.
1565
-     * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1566
-     *                              the blog.  If this is not the case, then it can be specified here.
1567
-     *                              If incoming format is 'U', this is ignored.
1568
-     * @return DbSafeDateTime
1569
-     * @throws EE_Error
1570
-     * @throws Exception
1571
-     */
1572
-    public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1573
-    {
1574
-        // just using this to ensure the timezone is set correctly internally
1575
-        $this->get_formats_for($field_name);
1576
-        $timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1577
-        $db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1578
-        EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1579
-        return $db_safe_datetime;
1580
-    }
1581
-
1582
-
1583
-    /**
1584
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1585
-     *
1586
-     * @return EE_Table_Base[]
1587
-     */
1588
-    public function get_tables()
1589
-    {
1590
-        return $this->_tables;
1591
-    }
1592
-
1593
-
1594
-    /**
1595
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1596
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1597
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1598
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1599
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1600
-     * model object with EVT_ID = 1
1601
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1602
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1603
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1604
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1605
-     * are not specified)
1606
-     *
1607
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1608
-     *                                         columns!), values are strings, integers, floats, and maybe arrays if
1609
-     *                                         they
1610
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1611
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1612
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1613
-     *                                         ID=34, we'd use this method as follows:
1614
-     *                                         EEM_Transaction::instance()->update(
1615
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1616
-     *                                         array(array('TXN_ID'=>34)));
1617
-     * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1618
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1619
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1620
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1621
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1622
-     *                                         TRUE, it is assumed that you've already called
1623
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1624
-     *                                         malicious javascript. However, if
1625
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1626
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1627
-     *                                         and every other field, before insertion. We provide this parameter
1628
-     *                                         because model objects perform their prepare_for_set function on all
1629
-     *                                         their values, and so don't need to be called again (and in many cases,
1630
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1631
-     *                                         prepare_for_set method...)
1632
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1633
-     *                                         in this model's entity map according to $fields_n_values that match
1634
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1635
-     *                                         by setting this to FALSE, but be aware that model objects being used
1636
-     *                                         could get out-of-sync with the database
1637
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1638
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1639
-     *                                         bad)
1640
-     * @throws EE_Error
1641
-     * @throws ReflectionException
1642
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1643
-     */
1644
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1645
-    {
1646
-        if (! is_array($query_params)) {
1647
-            EE_Error::doing_it_wrong(
1648
-                'EEM_Base::update',
1649
-                sprintf(
1650
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1651
-                    gettype($query_params)
1652
-                ),
1653
-                '4.6.0'
1654
-            );
1655
-            $query_params = [];
1656
-        }
1657
-        /**
1658
-         * Action called before a model update call has been made.
1659
-         *
1660
-         * @param EEM_Base $model
1661
-         * @param array    $fields_n_values the updated fields and their new values
1662
-         * @param array    $query_params
1663
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1664
-         */
1665
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1666
-        /**
1667
-         * Filters the fields about to be updated given the query parameters. You can provide the
1668
-         * $query_params to $this->get_all() to find exactly which records will be updated
1669
-         *
1670
-         * @param array    $fields_n_values fields and their new values
1671
-         * @param EEM_Base $model           the model being queried
1672
-         * @param array    $query_params
1673
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1674
-         */
1675
-        $fields_n_values = (array) apply_filters(
1676
-            'FHEE__EEM_Base__update__fields_n_values',
1677
-            $fields_n_values,
1678
-            $this,
1679
-            $query_params
1680
-        );
1681
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1682
-        // to do that, for each table, verify that it's PK isn't null.
1683
-        $tables = $this->get_tables();
1684
-        // 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
1685
-        // NOTE: we should make this code more efficient by NOT querying twice
1686
-        // before the real update, but that needs to first go through ALPHA testing
1687
-        // as it's dangerous. says Mike August 8 2014
1688
-        // we want to make sure the default_where strategy is ignored
1689
-        $this->_ignore_where_strategy = true;
1690
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1691
-        foreach ($wpdb_select_results as $wpdb_result) {
1692
-            // type cast stdClass as array
1693
-            $wpdb_result = (array) $wpdb_result;
1694
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1695
-            if ($this->has_primary_key_field()) {
1696
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1697
-            } else {
1698
-                // 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)
1699
-                $main_table_pk_value = null;
1700
-            }
1701
-            // 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
1702
-            // 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
1703
-            if (count($tables) > 1) {
1704
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1705
-                // in that table, and so we'll want to insert one
1706
-                foreach ($tables as $table_obj) {
1707
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1708
-                    // if there is no private key for this table on the results, it means there's no entry
1709
-                    // in this table, right? so insert a row in the current table, using any fields available
1710
-                    if (
1711
-                    ! (array_key_exists($this_table_pk_column, $wpdb_result)
1712
-                       && $wpdb_result[ $this_table_pk_column ])
1713
-                    ) {
1714
-                        $success = $this->_insert_into_specific_table(
1715
-                            $table_obj,
1716
-                            $fields_n_values,
1717
-                            $main_table_pk_value
1718
-                        );
1719
-                        // if we died here, report the error
1720
-                        if (! $success) {
1721
-                            return false;
1722
-                        }
1723
-                    }
1724
-                }
1725
-            }
1726
-            // let's make sure default_where strategy is followed now
1727
-            $this->_ignore_where_strategy = false;
1728
-        }
1729
-        // if we want to keep model objects in sync, AND
1730
-        // if this wasn't called from a model object (to update itself)
1731
-        // then we want to make sure we keep all the existing
1732
-        // model objects in sync with the db
1733
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1734
-            if ($this->has_primary_key_field()) {
1735
-                $model_objs_affected_ids = $this->get_col($query_params);
1736
-            } else {
1737
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1738
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1739
-                $model_objs_affected_ids     = [];
1740
-                foreach ($models_affected_key_columns as $row) {
1741
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1742
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1743
-                }
1744
-            }
1745
-            if (! $model_objs_affected_ids) {
1746
-                // wait wait wait- if nothing was affected let's stop here
1747
-                return 0;
1748
-            }
1749
-            foreach ($model_objs_affected_ids as $id) {
1750
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1751
-                if ($model_obj_in_entity_map) {
1752
-                    foreach ($fields_n_values as $field => $new_value) {
1753
-                        $model_obj_in_entity_map->set($field, $new_value);
1754
-                    }
1755
-                }
1756
-            }
1757
-            // if there is a primary key on this model, we can now do a slight optimization
1758
-            if ($this->has_primary_key_field()) {
1759
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1760
-                $query_params = [
1761
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1762
-                    'limit'                    => count($model_objs_affected_ids),
1763
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1764
-                ];
1765
-            }
1766
-        }
1767
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1769
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1770
-                            . $model_query_info->get_where_sql();
1771
-        // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1772
-        $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1773
-        /**
1774
-         * Action called after a model update call has been made.
1775
-         *
1776
-         * @param EEM_Base $model
1777
-         * @param array    $fields_n_values the updated fields and their new values
1778
-         * @param array    $query_params
1779
-         * @param int      $rows_affected
1780
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1781
-         */
1782
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1783
-        return $rows_affected;// how many supposedly got updated
1784
-    }
1785
-
1786
-
1787
-    /**
1788
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1789
-     * are teh values of the field specified (or by default the primary key field)
1790
-     * that matched the query params. Note that you should pass the name of the
1791
-     * model FIELD, not the database table's column name.
1792
-     *
1793
-     * @param array  $query_params
1794
-     * @param string $field_to_select
1795
-     * @return array just like $wpdb->get_col()
1796
-     * @throws EE_Error
1797
-     * @throws ReflectionException
1798
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1799
-     */
1800
-    public function get_col($query_params = [], $field_to_select = null)
1801
-    {
1802
-        if ($field_to_select) {
1803
-            $field = $this->field_settings_for($field_to_select);
1804
-        } elseif ($this->has_primary_key_field()) {
1805
-            $field = $this->get_primary_key_field();
1806
-        } else {
1807
-            $field_settings = $this->field_settings();
1808
-            // no primary key, just grab the first column
1809
-            $field = reset($field_settings);
1810
-        }
1811
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1812
-        $select_expressions = $field->get_qualified_column();
1813
-        $SQL                =
1814
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1815
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1816
-    }
1817
-
1818
-
1819
-    /**
1820
-     * Returns a single column value for a single row from the database
1821
-     *
1822
-     * @param array  $query_params
1823
-     * @param string $field_to_select
1824
-     * @return string
1825
-     * @throws EE_Error
1826
-     * @throws ReflectionException
1827
-     * @see EEM_Base::get_col()
1828
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1829
-     */
1830
-    public function get_var($query_params = [], $field_to_select = null)
1831
-    {
1832
-        $query_params['limit'] = 1;
1833
-        $col                   = $this->get_col($query_params, $field_to_select);
1834
-        if (! empty($col)) {
1835
-            return reset($col);
1836
-        }
1837
-        return null;
1838
-    }
1839
-
1840
-
1841
-    /**
1842
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1843
-     * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1844
-     * injection, but currently no further filtering is done
1845
-     *
1846
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1847
-     *                               be updated to in the DB
1848
-     * @return string of SQL
1849
-     * @throws EE_Error
1850
-     * @global      $wpdb
1851
-     */
1852
-    public function _construct_update_sql($fields_n_values)
1853
-    {
1854
-        global $wpdb;
1855
-        $cols_n_values = [];
1856
-        foreach ($fields_n_values as $field_name => $value) {
1857
-            $field_obj = $this->field_settings_for($field_name);
1858
-            // if the value is NULL, we want to assign the value to that.
1859
-            // wpdb->prepare doesn't really handle that properly
1860
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1861
-            $value_sql       = $prepared_value === null
1862
-                ? 'NULL'
1863
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1864
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1865
-        }
1866
-        return implode(",", $cols_n_values);
1867
-    }
1868
-
1869
-
1870
-    /**
1871
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1872
-     * Performs a HARD delete, meaning the database row should always be removed,
1873
-     * not just have a flag field on it switched
1874
-     * Wrapper for EEM_Base::delete_permanently()
1875
-     *
1876
-     * @param mixed   $id
1877
-     * @param boolean $allow_blocking
1878
-     * @return int the number of rows deleted
1879
-     * @throws EE_Error
1880
-     * @throws ReflectionException
1881
-     */
1882
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1883
-    {
1884
-        return $this->delete_permanently(
1885
-            [
1886
-                [$this->get_primary_key_field()->get_name() => $id],
1887
-                'limit' => 1,
1888
-            ],
1889
-            $allow_blocking
1890
-        );
1891
-    }
1892
-
1893
-
1894
-    /**
1895
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1896
-     * Wrapper for EEM_Base::delete()
1897
-     *
1898
-     * @param mixed   $id
1899
-     * @param boolean $allow_blocking
1900
-     * @return int the number of rows deleted
1901
-     * @throws EE_Error
1902
-     * @throws ReflectionException
1903
-     */
1904
-    public function delete_by_ID($id, $allow_blocking = true)
1905
-    {
1906
-        return $this->delete(
1907
-            [
1908
-                [$this->get_primary_key_field()->get_name() => $id],
1909
-                'limit' => 1,
1910
-            ],
1911
-            $allow_blocking
1912
-        );
1913
-    }
1914
-
1915
-
1916
-    /**
1917
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1918
-     * meaning if the model has a field that indicates its been "trashed" or
1919
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1920
-     *
1921
-     * @param array   $query_params
1922
-     * @param boolean $allow_blocking
1923
-     * @return int how many rows got deleted
1924
-     * @throws EE_Error
1925
-     * @throws ReflectionException
1926
-     * @see EEM_Base::delete_permanently
1927
-     */
1928
-    public function delete($query_params, $allow_blocking = true)
1929
-    {
1930
-        return $this->delete_permanently($query_params, $allow_blocking);
1931
-    }
1932
-
1933
-
1934
-    /**
1935
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1936
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1937
-     * as archived, not actually deleted
1938
-     *
1939
-     * @param array   $query_params
1940
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1941
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1942
-     *                                deletes regardless of other objects which may depend on it. Its generally
1943
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1944
-     *                                DB
1945
-     * @return int how many rows got deleted
1946
-     * @throws EE_Error
1947
-     * @throws ReflectionException
1948
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1949
-     */
1950
-    public function delete_permanently($query_params, $allow_blocking = true)
1951
-    {
1952
-        /**
1953
-         * Action called just before performing a real deletion query. You can use the
1954
-         * model and its $query_params to find exactly which items will be deleted
1955
-         *
1956
-         * @param EEM_Base $model
1957
-         * @param array    $query_params
1958
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1959
-         *                                 to block (prevent) this deletion
1960
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1961
-         */
1962
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1963
-        // some MySQL databases may be running safe mode, which may restrict
1964
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1965
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1966
-        // to delete them
1967
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1968
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1969
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1970
-            $columns_and_ids_for_deleting
1971
-        );
1972
-        /**
1973
-         * Allows client code to act on the items being deleted before the query is actually executed.
1974
-         *
1975
-         * @param EEM_Base $this                            The model instance being acted on.
1976
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1977
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1978
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1979
-         *                                                  derived from the incoming query parameters.
1980
-         * @see details on the structure of this array in the phpdocs
1981
-         *                                                  for the `_get_ids_for_delete_method`
1982
-         *
1983
-         */
1984
-        do_action(
1985
-            'AHEE__EEM_Base__delete__before_query',
1986
-            $this,
1987
-            $query_params,
1988
-            $allow_blocking,
1989
-            $columns_and_ids_for_deleting
1990
-        );
1991
-        if ($deletion_where_query_part) {
1992
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1993
-            $table_aliases    = implode(', ', array_keys($this->_tables));
1994
-            $SQL              = "DELETE " . $table_aliases
1995
-                                . " FROM " . $model_query_info->get_full_join_sql()
1996
-                                . " WHERE " . $deletion_where_query_part;
1997
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1998
-        } else {
1999
-            $rows_deleted = 0;
2000
-        }
2001
-
2002
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2003
-        // there was no error with the delete query.
2004
-        if (
2005
-            $this->has_primary_key_field()
2006
-            && $rows_deleted !== false
2007
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2008
-        ) {
2009
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2010
-            foreach ($ids_for_removal as $id) {
2011
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2012
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2013
-                }
2014
-            }
2015
-
2016
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2017
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2018
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2019
-            // (although it is possible).
2020
-            // Note this can be skipped by using the provided filter and returning false.
2021
-            if (
2022
-            apply_filters(
2023
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2024
-                ! $this instanceof EEM_Extra_Meta,
2025
-                $this
2026
-            )
2027
-            ) {
2028
-                EEM_Extra_Meta::instance()->delete_permanently(
2029
-                    [
2030
-                        0 => [
2031
-                            'EXM_type' => $this->get_this_model_name(),
2032
-                            'OBJ_ID'   => [
2033
-                                'IN',
2034
-                                $ids_for_removal,
2035
-                            ],
2036
-                        ],
2037
-                    ]
2038
-                );
2039
-            }
2040
-        }
2041
-
2042
-        /**
2043
-         * Action called just after performing a real deletion query. Although at this point the
2044
-         * items should have been deleted
2045
-         *
2046
-         * @param EEM_Base $model
2047
-         * @param array    $query_params
2048
-         * @param int      $rows_deleted
2049
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2050
-         */
2051
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2052
-        return $rows_deleted;// how many supposedly got deleted
2053
-    }
2054
-
2055
-
2056
-    /**
2057
-     * Checks all the relations that throw error messages when there are blocking related objects
2058
-     * for related model objects. If there are any related model objects on those relations,
2059
-     * adds an EE_Error, and return true
2060
-     *
2061
-     * @param EE_Base_Class|int $this_model_obj_or_id
2062
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2063
-     *                                                 should be ignored when determining whether there are related
2064
-     *                                                 model objects which block this model object's deletion. Useful
2065
-     *                                                 if you know A is related to B and are considering deleting A,
2066
-     *                                                 but want to see if A has any other objects blocking its deletion
2067
-     *                                                 before removing the relation between A and B
2068
-     * @return boolean
2069
-     * @throws EE_Error
2070
-     * @throws ReflectionException
2071
-     */
2072
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2073
-    {
2074
-        // first, if $ignore_this_model_obj was supplied, get its model
2075
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2076
-            $ignored_model = $ignore_this_model_obj->get_model();
2077
-        } else {
2078
-            $ignored_model = null;
2079
-        }
2080
-        // now check all the relations of $this_model_obj_or_id and see if there
2081
-        // are any related model objects blocking it?
2082
-        $is_blocked = false;
2083
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2084
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2085
-                // if $ignore_this_model_obj was supplied, then for the query
2086
-                // on that model needs to be told to ignore $ignore_this_model_obj
2087
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2088
-                    $related_model_objects = $relation_obj->get_all_related(
2089
-                        $this_model_obj_or_id,
2090
-                        [
2091
-                            [
2092
-                                $ignored_model->get_primary_key_field()->get_name() => [
2093
-                                    '!=',
2094
-                                    $ignore_this_model_obj->ID(),
2095
-                                ],
2096
-                            ],
2097
-                        ]
2098
-                    );
2099
-                } else {
2100
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2101
-                }
2102
-                if ($related_model_objects) {
2103
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2104
-                    $is_blocked = true;
2105
-                }
2106
-            }
2107
-        }
2108
-        return $is_blocked;
2109
-    }
2110
-
2111
-
2112
-    /**
2113
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2114
-     *
2115
-     * @param array $row_results_for_deleting
2116
-     * @param bool  $allow_blocking
2117
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2118
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2119
-     *                              dimension array where the key is the fully qualified primary key column and the
2120
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2121
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2122
-     *                              be a two dimensional array where each element is a group of columns and values that
2123
-     *                              get deleted. Example: array(
2124
-     *                              0 => array(
2125
-     *                              'Term_Relationship.object_id' => 1
2126
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2127
-     *                              ),
2128
-     *                              1 => array(
2129
-     *                              'Term_Relationship.object_id' => 1
2130
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2131
-     *                              )
2132
-     *                              )
2133
-     * @throws EE_Error
2134
-     * @throws ReflectionException
2135
-     */
2136
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2137
-    {
2138
-        $ids_to_delete_indexed_by_column = [];
2139
-        if ($this->has_primary_key_field()) {
2140
-            $primary_table                   = $this->_get_main_table();
2141
-            $ids_to_delete_indexed_by_column = $query = [];
2142
-            foreach ($row_results_for_deleting as $item_to_delete) {
2143
-                // before we mark this item for deletion,
2144
-                // make sure there's no related entities blocking its deletion (if we're checking)
2145
-                if (
2146
-                    $allow_blocking
2147
-                    && $this->delete_is_blocked_by_related_models(
2148
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2149
-                    )
2150
-                ) {
2151
-                    continue;
2152
-                }
2153
-                // primary table deletes
2154
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2155
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2156
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2157
-                }
2158
-            }
2159
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2160
-            $fields = $this->get_combined_primary_key_fields();
2161
-            foreach ($row_results_for_deleting as $item_to_delete) {
2162
-                $ids_to_delete_indexed_by_column_for_row = [];
2163
-                foreach ($fields as $cpk_field) {
2164
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2165
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2166
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2167
-                    }
2168
-                }
2169
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2170
-            }
2171
-        } else {
2172
-            // so there's no primary key and no combined key...
2173
-            // sorry, can't help you
2174
-            throw new EE_Error(
2175
-                sprintf(
2176
-                    esc_html__(
2177
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2178
-                        "event_espresso"
2179
-                    ),
2180
-                    get_class($this)
2181
-                )
2182
-            );
2183
-        }
2184
-        return $ids_to_delete_indexed_by_column;
2185
-    }
2186
-
2187
-
2188
-    /**
2189
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2190
-     * the corresponding query_part for the query performing the delete.
2191
-     *
2192
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2193
-     * @return string
2194
-     * @throws EE_Error
2195
-     */
2196
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2197
-    {
2198
-        $query_part = '';
2199
-        if (empty($ids_to_delete_indexed_by_column)) {
2200
-            return $query_part;
2201
-        } elseif ($this->has_primary_key_field()) {
2202
-            $query = [];
2203
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2204
-                // make sure we have unique $ids
2205
-                $ids     = array_unique($ids);
2206
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2207
-            }
2208
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2209
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2210
-            $ways_to_identify_a_row = [];
2211
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2212
-                $values_for_each_combined_primary_key_for_a_row = [];
2213
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2214
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2215
-                }
2216
-                $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2217
-                $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2218
-            }
2219
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2220
-        }
2221
-        return $query_part;
2222
-    }
2223
-
2224
-
2225
-    /**
2226
-     * Gets the model field by the fully qualified name
2227
-     *
2228
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2229
-     * @return EE_Model_Field_Base
2230
-     * @throws EE_Error
2231
-     */
2232
-    public function get_field_by_column($qualified_column_name)
2233
-    {
2234
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2235
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2236
-                return $field_obj;
2237
-            }
2238
-        }
2239
-        throw new EE_Error(
2240
-            sprintf(
2241
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2242
-                $this->get_this_model_name(),
2243
-                $qualified_column_name
2244
-            )
2245
-        );
2246
-    }
2247
-
2248
-
2249
-    /**
2250
-     * Count all the rows that match criteria the model query params.
2251
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2252
-     * column
2253
-     *
2254
-     * @param array  $query_params
2255
-     * @param string $field_to_count field on model to count by (not column name)
2256
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2257
-     *                               that by the setting $distinct to TRUE;
2258
-     * @return int
2259
-     * @throws EE_Error
2260
-     * @throws ReflectionException
2261
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2262
-     */
2263
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2264
-    {
2265
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2266
-        if ($field_to_count) {
2267
-            $field_obj       = $this->field_settings_for($field_to_count);
2268
-            $column_to_count = $field_obj->get_qualified_column();
2269
-        } elseif ($this->has_primary_key_field()) {
2270
-            $pk_field_obj    = $this->get_primary_key_field();
2271
-            $column_to_count = $pk_field_obj->get_qualified_column();
2272
-        } else {
2273
-            // there's no primary key
2274
-            // if we're counting distinct items, and there's no primary key,
2275
-            // we need to list out the columns for distinction;
2276
-            // otherwise we can just use star
2277
-            if ($distinct) {
2278
-                $columns_to_use = [];
2279
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2280
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2281
-                }
2282
-                $column_to_count = implode(',', $columns_to_use);
2283
-            } else {
2284
-                $column_to_count = '*';
2285
-            }
2286
-        }
2287
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2288
-        $SQL             =
2289
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2291
-    }
2292
-
2293
-
2294
-    /**
2295
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2296
-     *
2297
-     * @param array  $query_params
2298
-     * @param string $field_to_sum name of field (array key in $_fields array)
2299
-     * @return float
2300
-     * @throws EE_Error
2301
-     * @throws ReflectionException
2302
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2303
-     */
2304
-    public function sum($query_params, $field_to_sum = null)
2305
-    {
2306
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2307
-        if ($field_to_sum) {
2308
-            $field_obj = $this->field_settings_for($field_to_sum);
2309
-        } else {
2310
-            $field_obj = $this->get_primary_key_field();
2311
-        }
2312
-        $column_to_count = $field_obj->get_qualified_column();
2313
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2314
-                           . $this->_construct_2nd_half_of_select_query($model_query_info);
2315
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2316
-        $data_type       = $field_obj->get_wpdb_data_type();
2317
-        if ($data_type === '%d' || $data_type === '%s') {
2318
-            return (float) $return_value;
2319
-        }
2320
-        // must be %f
2321
-        return (float) $return_value;
2322
-    }
2323
-
2324
-
2325
-    /**
2326
-     * Just calls the specified method on $wpdb with the given arguments
2327
-     * Consolidates a little extra error handling code
2328
-     *
2329
-     * @param string $wpdb_method
2330
-     * @param array  $arguments_to_provide
2331
-     * @return mixed
2332
-     * @throws EE_Error
2333
-     * @global wpdb  $wpdb
2334
-     */
2335
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2336
-    {
2337
-        // if we're in maintenance mode level 2, DON'T run any queries
2338
-        // because level 2 indicates the database needs updating and
2339
-        // is probably out of sync with the code
2340
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2341
-            throw new EE_Error(
2342
-                sprintf(
2343
-                    esc_html__(
2344
-                        "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.",
2345
-                        "event_espresso"
2346
-                    )
2347
-                )
2348
-            );
2349
-        }
2350
-        global $wpdb;
2351
-        if (! method_exists($wpdb, $wpdb_method)) {
2352
-            throw new EE_Error(
2353
-                sprintf(
2354
-                    esc_html__(
2355
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2356
-                        'event_espresso'
2357
-                    ),
2358
-                    $wpdb_method
2359
-                )
2360
-            );
2361
-        }
2362
-        $old_show_errors_value = $wpdb->show_errors;
2363
-        if (WP_DEBUG) {
2364
-            $wpdb->show_errors(false);
2365
-        }
2366
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2367
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2368
-        if (WP_DEBUG) {
2369
-            $wpdb->show_errors($old_show_errors_value);
2370
-            if (! empty($wpdb->last_error)) {
2371
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2372
-            }
2373
-            if ($result === false) {
2374
-                throw new EE_Error(
2375
-                    sprintf(
2376
-                        esc_html__(
2377
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2378
-                            'event_espresso'
2379
-                        ),
2380
-                        $wpdb_method,
2381
-                        var_export($arguments_to_provide, true)
2382
-                    )
2383
-                );
2384
-            }
2385
-        } elseif ($result === false) {
2386
-            EE_Error::add_error(
2387
-                sprintf(
2388
-                    esc_html__(
2389
-                        '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"',
2390
-                        'event_espresso'
2391
-                    ),
2392
-                    $wpdb_method,
2393
-                    var_export($arguments_to_provide, true),
2394
-                    $wpdb->last_error
2395
-                ),
2396
-                __FILE__,
2397
-                __FUNCTION__,
2398
-                __LINE__
2399
-            );
2400
-        }
2401
-        return $result;
2402
-    }
2403
-
2404
-
2405
-    /**
2406
-     * Attempts to run the indicated WPDB method with the provided arguments,
2407
-     * and if there's an error tries to verify the DB is correct. Uses
2408
-     * the static property EEM_Base::$_db_verification_level to determine whether
2409
-     * we should try to fix the EE core db, the addons, or just give up
2410
-     *
2411
-     * @param string $wpdb_method
2412
-     * @param array  $arguments_to_provide
2413
-     * @return mixed
2414
-     * @throws EE_Error
2415
-     */
2416
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2417
-    {
2418
-        global $wpdb;
2419
-        $wpdb->last_error = null;
2420
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2421
-        // was there an error running the query? but we don't care on new activations
2422
-        // (we're going to setup the DB anyway on new activations)
2423
-        if (
2424
-            ($result === false || ! empty($wpdb->last_error))
2425
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2426
-        ) {
2427
-            switch (EEM_Base::$_db_verification_level) {
2428
-                case EEM_Base::db_verified_none:
2429
-                    // let's double-check core's DB
2430
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2431
-                    break;
2432
-                case EEM_Base::db_verified_core:
2433
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2434
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2435
-                    break;
2436
-                case EEM_Base::db_verified_addons:
2437
-                    // ummmm... you in trouble
2438
-                    return $result;
2439
-            }
2440
-            if (! empty($error_message)) {
2441
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2442
-                trigger_error($error_message);
2443
-            }
2444
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2445
-        }
2446
-        return $result;
2447
-    }
2448
-
2449
-
2450
-    /**
2451
-     * Verifies the EE core database is up-to-date and records that we've done it on
2452
-     * EEM_Base::$_db_verification_level
2453
-     *
2454
-     * @param string $wpdb_method
2455
-     * @param array  $arguments_to_provide
2456
-     * @return string
2457
-     * @throws EE_Error
2458
-     */
2459
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2460
-    {
2461
-        global $wpdb;
2462
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2463
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2464
-        $error_message                    = sprintf(
2465
-            esc_html__(
2466
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2467
-                'event_espresso'
2468
-            ),
2469
-            $wpdb->last_error,
2470
-            $wpdb_method,
2471
-            wp_json_encode($arguments_to_provide)
2472
-        );
2473
-        EE_System::instance()->initialize_db_if_no_migrations_required();
2474
-        return $error_message;
2475
-    }
2476
-
2477
-
2478
-    /**
2479
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2480
-     * EEM_Base::$_db_verification_level
2481
-     *
2482
-     * @param $wpdb_method
2483
-     * @param $arguments_to_provide
2484
-     * @return string
2485
-     * @throws EE_Error
2486
-     */
2487
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2488
-    {
2489
-        global $wpdb;
2490
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2491
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2492
-        $error_message                    = sprintf(
2493
-            esc_html__(
2494
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2495
-                'event_espresso'
2496
-            ),
2497
-            $wpdb->last_error,
2498
-            $wpdb_method,
2499
-            wp_json_encode($arguments_to_provide)
2500
-        );
2501
-        EE_System::instance()->initialize_addons();
2502
-        return $error_message;
2503
-    }
2504
-
2505
-
2506
-    /**
2507
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2508
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2509
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2510
-     * ..."
2511
-     *
2512
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2513
-     * @return string
2514
-     */
2515
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2516
-    {
2517
-        return " FROM " . $model_query_info->get_full_join_sql() .
2518
-               $model_query_info->get_where_sql() .
2519
-               $model_query_info->get_group_by_sql() .
2520
-               $model_query_info->get_having_sql() .
2521
-               $model_query_info->get_order_by_sql() .
2522
-               $model_query_info->get_limit_sql();
2523
-    }
2524
-
2525
-
2526
-    /**
2527
-     * Set to easily debug the next X queries ran from this model.
2528
-     *
2529
-     * @param int $count
2530
-     */
2531
-    public function show_next_x_db_queries($count = 1)
2532
-    {
2533
-        $this->_show_next_x_db_queries = $count;
2534
-    }
2535
-
2536
-
2537
-    /**
2538
-     * @param $sql_query
2539
-     */
2540
-    public function show_db_query_if_previously_requested($sql_query)
2541
-    {
2542
-        if ($this->_show_next_x_db_queries > 0) {
2543
-            echo $sql_query;
2544
-            $this->_show_next_x_db_queries--;
2545
-        }
2546
-    }
2547
-
2548
-
2549
-    /**
2550
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2551
-     * There are the 3 cases:
2552
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2553
-     * $otherModelObject has no ID, it is first saved.
2554
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2555
-     * has no ID, it is first saved.
2556
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2557
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2558
-     * join table
2559
-     *
2560
-     * @param EE_Base_Class                     /int $thisModelObject
2561
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2562
-     * @param string $relationName                     , key in EEM_Base::_relations
2563
-     *                                                 an attendee to a group, you also want to specify which role they
2564
-     *                                                 will have in that group. So you would use this parameter to
2565
-     *                                                 specify array('role-column-name'=>'role-id')
2566
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2567
-     *                                                 to for relation to methods that allow you to further specify
2568
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2569
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2570
-     *                                                 because these will be inserted in any new rows created as well.
2571
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2572
-     * @throws EE_Error
2573
-     */
2574
-    public function add_relationship_to(
2575
-        $id_or_obj,
2576
-        $other_model_id_or_obj,
2577
-        $relationName,
2578
-        $extra_join_model_fields_n_values = []
2579
-    ) {
2580
-        $relation_obj = $this->related_settings_for($relationName);
2581
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2582
-    }
2583
-
2584
-
2585
-    /**
2586
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2587
-     * There are the 3 cases:
2588
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2589
-     * error
2590
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2591
-     * an error
2592
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2593
-     *
2594
-     * @param EE_Base_Class /int $id_or_obj
2595
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2596
-     * @param string $relationName key in EEM_Base::_relations
2597
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2598
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2599
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2600
-     *                             because these will be inserted in any new rows created as well.
2601
-     * @return boolean of success
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2605
-    {
2606
-        $relation_obj = $this->related_settings_for($relationName);
2607
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2608
-    }
2609
-
2610
-
2611
-    /**
2612
-     * @param mixed  $id_or_obj
2613
-     * @param string $relationName
2614
-     * @param array  $where_query_params
2615
-     * @param EE_Base_Class[] objects to which relations were removed
2616
-     * @return EE_Base_Class[]
2617
-     * @throws EE_Error
2618
-     */
2619
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2620
-    {
2621
-        $relation_obj = $this->related_settings_for($relationName);
2622
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * Gets all the related items of the specified $model_name, using $query_params.
2628
-     * Note: by default, we remove the "default query params"
2629
-     * because we want to get even deleted items etc.
2630
-     *
2631
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2632
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2633
-     * @param array  $query_params see github link below for more info
2634
-     * @return EE_Base_Class[]
2635
-     * @throws EE_Error
2636
-     * @throws ReflectionException
2637
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
-     */
2639
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2640
-    {
2641
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2642
-        $relation_settings = $this->related_settings_for($model_name);
2643
-        return $relation_settings->get_all_related($model_obj, $query_params);
2644
-    }
2645
-
2646
-
2647
-    /**
2648
-     * Deletes all the model objects across the relation indicated by $model_name
2649
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2650
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2651
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2652
-     *
2653
-     * @param EE_Base_Class|int|string $id_or_obj
2654
-     * @param string                   $model_name
2655
-     * @param array                    $query_params
2656
-     * @return int how many deleted
2657
-     * @throws EE_Error
2658
-     * @throws ReflectionException
2659
-     */
2660
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2661
-    {
2662
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2663
-        $relation_settings = $this->related_settings_for($model_name);
2664
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2665
-    }
2666
-
2667
-
2668
-    /**
2669
-     * Hard deletes all the model objects across the relation indicated by $model_name
2670
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2671
-     * the model objects can't be hard deleted because of blocking related model objects,
2672
-     * just does a soft-delete on them instead.
2673
-     *
2674
-     * @param EE_Base_Class|int|string $id_or_obj
2675
-     * @param string                   $model_name
2676
-     * @param array                    $query_params
2677
-     * @return int how many deleted
2678
-     * @throws EE_Error
2679
-     * @throws ReflectionException
2680
-     */
2681
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2682
-    {
2683
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2684
-        $relation_settings = $this->related_settings_for($model_name);
2685
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2686
-    }
2687
-
2688
-
2689
-    /**
2690
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2691
-     * unless otherwise specified in the $query_params
2692
-     *
2693
-     * @param int             /EE_Base_Class $id_or_obj
2694
-     * @param string $model_name     like 'Event', or 'Registration'
2695
-     * @param array  $query_params
2696
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2697
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2698
-     *                               that by the setting $distinct to TRUE;
2699
-     * @return int
2700
-     * @throws EE_Error
2701
-     * @throws ReflectionException
2702
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2703
-     */
2704
-    public function count_related(
2705
-        $id_or_obj,
2706
-        $model_name,
2707
-        $query_params = [],
2708
-        $field_to_count = null,
2709
-        $distinct = false
2710
-    ) {
2711
-        $related_model = $this->get_related_model_obj($model_name);
2712
-        // we're just going to use the query params on the related model's normal get_all query,
2713
-        // except add a condition to say to match the current mod
2714
-        if (! isset($query_params['default_where_conditions'])) {
2715
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2716
-        }
2717
-        $this_model_name                                                 = $this->get_this_model_name();
2718
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2719
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2720
-        return $related_model->count($query_params, $field_to_count, $distinct);
2721
-    }
2722
-
2723
-
2724
-    /**
2725
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2726
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2727
-     *
2728
-     * @param int           /EE_Base_Class $id_or_obj
2729
-     * @param string $model_name   like 'Event', or 'Registration'
2730
-     * @param array  $query_params
2731
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2732
-     * @return float
2733
-     * @throws EE_Error
2734
-     * @throws ReflectionException
2735
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
-     */
2737
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2738
-    {
2739
-        $related_model = $this->get_related_model_obj($model_name);
2740
-        if (! is_array($query_params)) {
2741
-            EE_Error::doing_it_wrong(
2742
-                'EEM_Base::sum_related',
2743
-                sprintf(
2744
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2745
-                    gettype($query_params)
2746
-                ),
2747
-                '4.6.0'
2748
-            );
2749
-            $query_params = [];
2750
-        }
2751
-        // we're just going to use the query params on the related model's normal get_all query,
2752
-        // except add a condition to say to match the current mod
2753
-        if (! isset($query_params['default_where_conditions'])) {
2754
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2755
-        }
2756
-        $this_model_name                                                 = $this->get_this_model_name();
2757
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2758
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2759
-        return $related_model->sum($query_params, $field_to_sum);
2760
-    }
2761
-
2762
-
2763
-    /**
2764
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2765
-     * $modelObject
2766
-     *
2767
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2768
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2769
-     * @param array               $query_params     see github link below for more info
2770
-     * @return EE_Base_Class
2771
-     * @throws EE_Error
2772
-     * @throws ReflectionException
2773
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2774
-     */
2775
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2776
-    {
2777
-        $query_params['limit'] = 1;
2778
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2779
-        if ($results) {
2780
-            return array_shift($results);
2781
-        }
2782
-        return null;
2783
-    }
2784
-
2785
-
2786
-    /**
2787
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2788
-     *
2789
-     * @return string
2790
-     */
2791
-    public function get_this_model_name()
2792
-    {
2793
-        return str_replace("EEM_", "", get_class($this));
2794
-    }
2795
-
2796
-
2797
-    /**
2798
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2799
-     *
2800
-     * @return EE_Any_Foreign_Model_Name_Field
2801
-     * @throws EE_Error
2802
-     */
2803
-    public function get_field_containing_related_model_name()
2804
-    {
2805
-        foreach ($this->field_settings(true) as $field) {
2806
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2807
-                $field_with_model_name = $field;
2808
-            }
2809
-        }
2810
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2811
-            throw new EE_Error(
2812
-                sprintf(
2813
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2814
-                    $this->get_this_model_name()
2815
-                )
2816
-            );
2817
-        }
2818
-        return $field_with_model_name;
2819
-    }
2820
-
2821
-
2822
-    /**
2823
-     * Inserts a new entry into the database, for each table.
2824
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2825
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2826
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2827
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2828
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2829
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2830
-     *
2831
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2832
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2833
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2834
-     *                              of EEM_Base)
2835
-     * @return int|string new primary key on main table that got inserted
2836
-     * @throws EE_Error
2837
-     * @throws ReflectionException
2838
-     */
2839
-    public function insert($field_n_values)
2840
-    {
2841
-        /**
2842
-         * Filters the fields and their values before inserting an item using the models
2843
-         *
2844
-         * @param array    $fields_n_values keys are the fields and values are their new values
2845
-         * @param EEM_Base $model           the model used
2846
-         */
2847
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2848
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2849
-            $main_table = $this->_get_main_table();
2850
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2851
-            if ($new_id !== false) {
2852
-                foreach ($this->_get_other_tables() as $other_table) {
2853
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2854
-                }
2855
-            }
2856
-            /**
2857
-             * Done just after attempting to insert a new model object
2858
-             *
2859
-             * @param EEM_Base $model           used
2860
-             * @param array    $fields_n_values fields and their values
2861
-             * @param int|string the              ID of the newly-inserted model object
2862
-             */
2863
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2864
-            return $new_id;
2865
-        }
2866
-        return false;
2867
-    }
2868
-
2869
-
2870
-    /**
2871
-     * Checks that the result would satisfy the unique indexes on this model
2872
-     *
2873
-     * @param array  $field_n_values
2874
-     * @param string $action
2875
-     * @return boolean
2876
-     * @throws EE_Error
2877
-     * @throws ReflectionException
2878
-     */
2879
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2880
-    {
2881
-        foreach ($this->unique_indexes() as $index_name => $index) {
2882
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2883
-            if ($this->exists([$uniqueness_where_params])) {
2884
-                EE_Error::add_error(
2885
-                    sprintf(
2886
-                        esc_html__(
2887
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2888
-                            "event_espresso"
2889
-                        ),
2890
-                        $action,
2891
-                        $this->_get_class_name(),
2892
-                        $index_name,
2893
-                        implode(",", $index->field_names()),
2894
-                        http_build_query($uniqueness_where_params)
2895
-                    ),
2896
-                    __FILE__,
2897
-                    __FUNCTION__,
2898
-                    __LINE__
2899
-                );
2900
-                return false;
2901
-            }
2902
-        }
2903
-        return true;
2904
-    }
2905
-
2906
-
2907
-    /**
2908
-     * Checks the database for an item that conflicts (ie, if this item were
2909
-     * saved to the DB would break some uniqueness requirement, like a primary key
2910
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2911
-     * can be either an EE_Base_Class or an array of fields n values
2912
-     *
2913
-     * @param EE_Base_Class|array $obj_or_fields_array
2914
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2915
-     *                                                 when looking for conflicts
2916
-     *                                                 (ie, if false, we ignore the model object's primary key
2917
-     *                                                 when finding "conflicts". If true, it's also considered).
2918
-     *                                                 Only works for INT primary key,
2919
-     *                                                 STRING primary keys cannot be ignored
2920
-     * @return EE_Base_Class|array
2921
-     * @throws EE_Error
2922
-     * @throws ReflectionException
2923
-     */
2924
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2925
-    {
2926
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2927
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2928
-        } elseif (is_array($obj_or_fields_array)) {
2929
-            $fields_n_values = $obj_or_fields_array;
2930
-        } else {
2931
-            throw new EE_Error(
2932
-                sprintf(
2933
-                    esc_html__(
2934
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2935
-                        "event_espresso"
2936
-                    ),
2937
-                    get_class($this),
2938
-                    $obj_or_fields_array
2939
-                )
2940
-            );
2941
-        }
2942
-        $query_params = [];
2943
-        if (
2944
-            $this->has_primary_key_field()
2945
-            && ($include_primary_key
2946
-                || $this->get_primary_key_field()
2947
-                   instanceof
2948
-                   EE_Primary_Key_String_Field)
2949
-            && isset($fields_n_values[ $this->primary_key_name() ])
2950
-        ) {
2951
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2952
-        }
2953
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2954
-            $uniqueness_where_params                              =
2955
-                array_intersect_key($fields_n_values, $unique_index->fields());
2956
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2957
-        }
2958
-        // if there is nothing to base this search on, then we shouldn't find anything
2959
-        if (empty($query_params)) {
2960
-            return [];
2961
-        }
2962
-        return $this->get_one($query_params);
2963
-    }
2964
-
2965
-
2966
-    /**
2967
-     * Like count, but is optimized and returns a boolean instead of an int
2968
-     *
2969
-     * @param array $query_params
2970
-     * @return boolean
2971
-     * @throws EE_Error
2972
-     * @throws ReflectionException
2973
-     */
2974
-    public function exists($query_params)
2975
-    {
2976
-        $query_params['limit'] = 1;
2977
-        return $this->count($query_params) > 0;
2978
-    }
2979
-
2980
-
2981
-    /**
2982
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2983
-     *
2984
-     * @param int|string $id
2985
-     * @return boolean
2986
-     * @throws EE_Error
2987
-     * @throws ReflectionException
2988
-     */
2989
-    public function exists_by_ID($id)
2990
-    {
2991
-        return $this->exists(
2992
-            [
2993
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2994
-                [
2995
-                    $this->primary_key_name() => $id,
2996
-                ],
2997
-            ]
2998
-        );
2999
-    }
3000
-
3001
-
3002
-    /**
3003
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3004
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3005
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3006
-     * on the main table)
3007
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3008
-     * cases where we want to call it directly rather than via insert().
3009
-     *
3010
-     * @access   protected
3011
-     * @param EE_Table_Base $table
3012
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3013
-     *                                       float
3014
-     * @param int           $new_id          for now we assume only int keys
3015
-     * @return int ID of new row inserted, or FALSE on failure
3016
-     * @throws EE_Error
3017
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3018
-     */
3019
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3020
-    {
3021
-        global $wpdb;
3022
-        $insertion_col_n_values = [];
3023
-        $format_for_insertion   = [];
3024
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3025
-        foreach ($fields_on_table as $field_name => $field_obj) {
3026
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3027
-            if ($field_obj->is_auto_increment()) {
3028
-                continue;
3029
-            }
3030
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3031
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3032
-            if ($prepared_value !== null) {
3033
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3034
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3035
-            }
3036
-        }
3037
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3038
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3039
-            // so add the fk to the main table as a column
3040
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3041
-            $format_for_insertion[]                              =
3042
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3043
-        }
3044
-        // insert the new entry
3045
-        $result = $this->_do_wpdb_query(
3046
-            'insert',
3047
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3048
-        );
3049
-        if ($result === false) {
3050
-            return false;
3051
-        }
3052
-        // ok, now what do we return for the ID of the newly-inserted thing?
3053
-        if ($this->has_primary_key_field()) {
3054
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3055
-                return $wpdb->insert_id;
3056
-            }
3057
-            // it's not an auto-increment primary key, so
3058
-            // it must have been supplied
3059
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3060
-        }
3061
-        // we can't return a  primary key because there is none. instead return
3062
-        // a unique string indicating this model
3063
-        return $this->get_index_primary_key_string($fields_n_values);
3064
-    }
3065
-
3066
-
3067
-    /**
3068
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3069
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3070
-     * and there is no default, we pass it along. WPDB will take care of it)
3071
-     *
3072
-     * @param EE_Model_Field_Base $field_obj
3073
-     * @param array               $fields_n_values
3074
-     * @return mixed string|int|float depending on what the table column will be expecting
3075
-     * @throws EE_Error
3076
-     */
3077
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3078
-    {
3079
-        // if this field doesn't allow nullable, don't allow it
3080
-        if (
3081
-            ! $field_obj->is_nullable()
3082
-            && (
3083
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3084
-                || $fields_n_values[ $field_obj->get_name() ] === null
3085
-            )
3086
-        ) {
3087
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3088
-        }
3089
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3090
-            ? $fields_n_values[ $field_obj->get_name() ]
3091
-            : null;
3092
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3098
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3099
-     * the field's prepare_for_set() method.
3100
-     *
3101
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3102
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3103
-     *                                   top of file)
3104
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3105
-     *                                   $value is a custom selection
3106
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3107
-     */
3108
-    private function _prepare_value_for_use_in_db($value, $field)
3109
-    {
3110
-        if ($field && $field instanceof EE_Model_Field_Base) {
3111
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3112
-            switch ($this->_values_already_prepared_by_model_object) {
3113
-                /** @noinspection PhpMissingBreakStatementInspection */
3114
-                case self::not_prepared_by_model_object:
3115
-                    $value = $field->prepare_for_set($value);
3116
-                // purposefully left out "return"
3117
-                case self::prepared_by_model_object:
3118
-                    /** @noinspection SuspiciousAssignmentsInspection */
3119
-                    $value = $field->prepare_for_use_in_db($value);
3120
-                case self::prepared_for_use_in_db:
3121
-                    // leave the value alone
3122
-            }
3123
-            return $value;
3124
-            // phpcs:enable
3125
-        }
3126
-        return $value;
3127
-    }
3128
-
3129
-
3130
-    /**
3131
-     * Returns the main table on this model
3132
-     *
3133
-     * @return EE_Primary_Table
3134
-     * @throws EE_Error
3135
-     */
3136
-    protected function _get_main_table()
3137
-    {
3138
-        foreach ($this->_tables as $table) {
3139
-            if ($table instanceof EE_Primary_Table) {
3140
-                return $table;
3141
-            }
3142
-        }
3143
-        throw new EE_Error(
3144
-            sprintf(
3145
-                esc_html__(
3146
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3147
-                    'event_espresso'
3148
-                ),
3149
-                get_class($this)
3150
-            )
3151
-        );
3152
-    }
3153
-
3154
-
3155
-    /**
3156
-     * table
3157
-     * returns EE_Primary_Table table name
3158
-     *
3159
-     * @return string
3160
-     * @throws EE_Error
3161
-     */
3162
-    public function table()
3163
-    {
3164
-        return $this->_get_main_table()->get_table_name();
3165
-    }
3166
-
3167
-
3168
-    /**
3169
-     * table
3170
-     * returns first EE_Secondary_Table table name
3171
-     *
3172
-     * @return string
3173
-     */
3174
-    public function second_table()
3175
-    {
3176
-        // grab second table from tables array
3177
-        $second_table = end($this->_tables);
3178
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3179
-    }
3180
-
3181
-
3182
-    /**
3183
-     * get_table_obj_by_alias
3184
-     * returns table name given it's alias
3185
-     *
3186
-     * @param string $table_alias
3187
-     * @return EE_Primary_Table | EE_Secondary_Table
3188
-     */
3189
-    public function get_table_obj_by_alias($table_alias = '')
3190
-    {
3191
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3192
-    }
3193
-
3194
-
3195
-    /**
3196
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3197
-     *
3198
-     * @return EE_Secondary_Table[]
3199
-     */
3200
-    protected function _get_other_tables()
3201
-    {
3202
-        $other_tables = [];
3203
-        foreach ($this->_tables as $table_alias => $table) {
3204
-            if ($table instanceof EE_Secondary_Table) {
3205
-                $other_tables[ $table_alias ] = $table;
3206
-            }
3207
-        }
3208
-        return $other_tables;
3209
-    }
3210
-
3211
-
3212
-    /**
3213
-     * Finds all the fields that correspond to the given table
3214
-     *
3215
-     * @param string $table_alias , array key in EEM_Base::_tables
3216
-     * @return EE_Model_Field_Base[]
3217
-     */
3218
-    public function _get_fields_for_table($table_alias)
3219
-    {
3220
-        return $this->_fields[ $table_alias ];
3221
-    }
3222
-
3223
-
3224
-    /**
3225
-     * Recurses through all the where parameters, and finds all the related models we'll need
3226
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3227
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3228
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3229
-     * related Registration, Transaction, and Payment models.
3230
-     *
3231
-     * @param array $query_params see github link below for more info
3232
-     * @return EE_Model_Query_Info_Carrier
3233
-     * @throws EE_Error
3234
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3235
-     */
3236
-    public function _extract_related_models_from_query($query_params)
3237
-    {
3238
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3239
-        if (array_key_exists(0, $query_params)) {
3240
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3241
-        }
3242
-        if (array_key_exists('group_by', $query_params)) {
3243
-            if (is_array($query_params['group_by'])) {
3244
-                $this->_extract_related_models_from_sub_params_array_values(
3245
-                    $query_params['group_by'],
3246
-                    $query_info_carrier,
3247
-                    'group_by'
3248
-                );
3249
-            } elseif (! empty($query_params['group_by'])) {
3250
-                $this->_extract_related_model_info_from_query_param(
3251
-                    $query_params['group_by'],
3252
-                    $query_info_carrier,
3253
-                    'group_by'
3254
-                );
3255
-            }
3256
-        }
3257
-        if (array_key_exists('having', $query_params)) {
3258
-            $this->_extract_related_models_from_sub_params_array_keys(
3259
-                $query_params[0],
3260
-                $query_info_carrier,
3261
-                'having'
3262
-            );
3263
-        }
3264
-        if (array_key_exists('order_by', $query_params)) {
3265
-            if (is_array($query_params['order_by'])) {
3266
-                $this->_extract_related_models_from_sub_params_array_keys(
3267
-                    $query_params['order_by'],
3268
-                    $query_info_carrier,
3269
-                    'order_by'
3270
-                );
3271
-            } elseif (! empty($query_params['order_by'])) {
3272
-                $this->_extract_related_model_info_from_query_param(
3273
-                    $query_params['order_by'],
3274
-                    $query_info_carrier,
3275
-                    'order_by'
3276
-                );
3277
-            }
3278
-        }
3279
-        if (array_key_exists('force_join', $query_params)) {
3280
-            $this->_extract_related_models_from_sub_params_array_values(
3281
-                $query_params['force_join'],
3282
-                $query_info_carrier,
3283
-                'force_join'
3284
-            );
3285
-        }
3286
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3287
-        return $query_info_carrier;
3288
-    }
3289
-
3290
-
3291
-    /**
3292
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3293
-     *
3294
-     * @param array                       $sub_query_params
3295
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3296
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3297
-     * @return EE_Model_Query_Info_Carrier
3298
-     * @throws EE_Error
3299
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3300
-     */
3301
-    private function _extract_related_models_from_sub_params_array_keys(
3302
-        $sub_query_params,
3303
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3304
-        $query_param_type
3305
-    ) {
3306
-        if (! empty($sub_query_params)) {
3307
-            $sub_query_params = (array) $sub_query_params;
3308
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3309
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3310
-                $this->_extract_related_model_info_from_query_param(
3311
-                    $param,
3312
-                    $model_query_info_carrier,
3313
-                    $query_param_type
3314
-                );
3315
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3316
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3317
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3318
-                // of array('Registration.TXN_ID'=>23)
3319
-                $query_param_sans_stars =
3320
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3321
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3322
-                    if (! is_array($possibly_array_of_params)) {
3323
-                        throw new EE_Error(
3324
-                            sprintf(
3325
-                                esc_html__(
3326
-                                    "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'))",
3327
-                                    "event_espresso"
3328
-                                ),
3329
-                                $param,
3330
-                                $possibly_array_of_params
3331
-                            )
3332
-                        );
3333
-                    }
3334
-                    $this->_extract_related_models_from_sub_params_array_keys(
3335
-                        $possibly_array_of_params,
3336
-                        $model_query_info_carrier,
3337
-                        $query_param_type
3338
-                    );
3339
-                } elseif (
3340
-                    $query_param_type === 0 // ie WHERE
3341
-                    && is_array($possibly_array_of_params)
3342
-                    && isset($possibly_array_of_params[2])
3343
-                    && $possibly_array_of_params[2] == true
3344
-                ) {
3345
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3346
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3347
-                    // from which we should extract query parameters!
3348
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3349
-                        throw new EE_Error(
3350
-                            sprintf(
3351
-                                esc_html__(
3352
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3353
-                                    "event_espresso"
3354
-                                ),
3355
-                                $query_param_type,
3356
-                                implode(",", $possibly_array_of_params)
3357
-                            )
3358
-                        );
3359
-                    }
3360
-                    $this->_extract_related_model_info_from_query_param(
3361
-                        $possibly_array_of_params[1],
3362
-                        $model_query_info_carrier,
3363
-                        $query_param_type
3364
-                    );
3365
-                }
3366
-            }
3367
-        }
3368
-        return $model_query_info_carrier;
3369
-    }
3370
-
3371
-
3372
-    /**
3373
-     * For extracting related models from forced_joins, where the array values contain the info about what
3374
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3375
-     *
3376
-     * @param array                       $sub_query_params
3377
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3378
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3379
-     * @return EE_Model_Query_Info_Carrier
3380
-     * @throws EE_Error
3381
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3382
-     */
3383
-    private function _extract_related_models_from_sub_params_array_values(
3384
-        $sub_query_params,
3385
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3386
-        $query_param_type
3387
-    ) {
3388
-        if (! empty($sub_query_params)) {
3389
-            if (! is_array($sub_query_params)) {
3390
-                throw new EE_Error(
3391
-                    sprintf(
3392
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3393
-                        $sub_query_params
3394
-                    )
3395
-                );
3396
-            }
3397
-            foreach ($sub_query_params as $param) {
3398
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3399
-                $this->_extract_related_model_info_from_query_param(
3400
-                    $param,
3401
-                    $model_query_info_carrier,
3402
-                    $query_param_type
3403
-                );
3404
-            }
3405
-        }
3406
-        return $model_query_info_carrier;
3407
-    }
3408
-
3409
-
3410
-    /**
3411
-     * Extract all the query parts from  model query params
3412
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3413
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3414
-     * but use them in a different order. Eg, we need to know what models we are querying
3415
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3416
-     * other models before we can finalize the where clause SQL.
3417
-     *
3418
-     * @param array $query_params see github link below for more info
3419
-     * @return EE_Model_Query_Info_Carrier
3420
-     * @throws EE_Error
3421
-     * @throws ModelConfigurationException
3422
-     * @throws ReflectionException
3423
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3424
-     */
3425
-    public function _create_model_query_info_carrier($query_params)
3426
-    {
3427
-        if (! is_array($query_params)) {
3428
-            EE_Error::doing_it_wrong(
3429
-                'EEM_Base::_create_model_query_info_carrier',
3430
-                sprintf(
3431
-                    esc_html__(
3432
-                        '$query_params should be an array, you passed a variable of type %s',
3433
-                        'event_espresso'
3434
-                    ),
3435
-                    gettype($query_params)
3436
-                ),
3437
-                '4.6.0'
3438
-            );
3439
-            $query_params = [];
3440
-        }
3441
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3442
-        // first check if we should alter the query to account for caps or not
3443
-        // because the caps might require us to do extra joins
3444
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3445
-            $query_params[0] = array_replace_recursive(
3446
-                $query_params[0],
3447
-                $this->caps_where_conditions(
3448
-                    $query_params['caps']
3449
-                )
3450
-            );
3451
-        }
3452
-
3453
-        // check if we should alter the query to remove data related to protected
3454
-        // custom post types
3455
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3456
-            $where_param_key_for_password = $this->modelChainAndPassword();
3457
-            // only include if related to a cpt where no password has been set
3458
-            $query_params[0]['OR*nopassword'] = [
3459
-                $where_param_key_for_password       => '',
3460
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3461
-            ];
3462
-        }
3463
-        $query_object = $this->_extract_related_models_from_query($query_params);
3464
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3465
-        foreach ($query_params[0] as $key => $value) {
3466
-            if (is_int($key)) {
3467
-                throw new EE_Error(
3468
-                    sprintf(
3469
-                        esc_html__(
3470
-                            "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.",
3471
-                            "event_espresso"
3472
-                        ),
3473
-                        $key,
3474
-                        var_export($value, true),
3475
-                        var_export($query_params, true),
3476
-                        get_class($this)
3477
-                    )
3478
-                );
3479
-            }
3480
-        }
3481
-        if (
3482
-            array_key_exists('default_where_conditions', $query_params)
3483
-            && ! empty($query_params['default_where_conditions'])
3484
-        ) {
3485
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3486
-        } else {
3487
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3488
-        }
3489
-        $query_params[0] = array_merge(
3490
-            $this->_get_default_where_conditions_for_models_in_query(
3491
-                $query_object,
3492
-                $use_default_where_conditions,
3493
-                $query_params[0]
3494
-            ),
3495
-            $query_params[0]
3496
-        );
3497
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3498
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3499
-        // So we need to setup a subquery and use that for the main join.
3500
-        // Note for now this only works on the primary table for the model.
3501
-        // So for instance, you could set the limit array like this:
3502
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3503
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3504
-            $query_object->set_main_model_join_sql(
3505
-                $this->_construct_limit_join_select(
3506
-                    $query_params['on_join_limit'][0],
3507
-                    $query_params['on_join_limit'][1]
3508
-                )
3509
-            );
3510
-        }
3511
-        // set limit
3512
-        if (array_key_exists('limit', $query_params)) {
3513
-            if (is_array($query_params['limit'])) {
3514
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3515
-                    $e = sprintf(
3516
-                        esc_html__(
3517
-                            "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)",
3518
-                            "event_espresso"
3519
-                        ),
3520
-                        http_build_query($query_params['limit'])
3521
-                    );
3522
-                    throw new EE_Error($e . "|" . $e);
3523
-                }
3524
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3525
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3526
-            } elseif (! empty($query_params['limit'])) {
3527
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3528
-            }
3529
-        }
3530
-        // set order by
3531
-        if (array_key_exists('order_by', $query_params)) {
3532
-            if (is_array($query_params['order_by'])) {
3533
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3534
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3535
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3536
-                if (array_key_exists('order', $query_params)) {
3537
-                    throw new EE_Error(
3538
-                        sprintf(
3539
-                            esc_html__(
3540
-                                "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 ",
3541
-                                "event_espresso"
3542
-                            ),
3543
-                            get_class($this),
3544
-                            implode(", ", array_keys($query_params['order_by'])),
3545
-                            implode(", ", $query_params['order_by']),
3546
-                            $query_params['order']
3547
-                        )
3548
-                    );
3549
-                }
3550
-                $this->_extract_related_models_from_sub_params_array_keys(
3551
-                    $query_params['order_by'],
3552
-                    $query_object,
3553
-                    'order_by'
3554
-                );
3555
-                // assume it's an array of fields to order by
3556
-                $order_array = [];
3557
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3558
-                    $order         = $this->_extract_order($order);
3559
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3560
-                }
3561
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3562
-            } elseif (! empty($query_params['order_by'])) {
3563
-                $this->_extract_related_model_info_from_query_param(
3564
-                    $query_params['order_by'],
3565
-                    $query_object,
3566
-                    'order',
3567
-                    $query_params['order_by']
3568
-                );
3569
-                $order = isset($query_params['order'])
3570
-                    ? $this->_extract_order($query_params['order'])
3571
-                    : 'DESC';
3572
-                $query_object->set_order_by_sql(
3573
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3574
-                );
3575
-            }
3576
-        }
3577
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3578
-        if (
3579
-            ! array_key_exists('order_by', $query_params)
3580
-            && array_key_exists('order', $query_params)
3581
-            && ! empty($query_params['order'])
3582
-        ) {
3583
-            $pk_field = $this->get_primary_key_field();
3584
-            $order    = $this->_extract_order($query_params['order']);
3585
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3586
-        }
3587
-        // set group by
3588
-        if (array_key_exists('group_by', $query_params)) {
3589
-            if (is_array($query_params['group_by'])) {
3590
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3591
-                $group_by_array = [];
3592
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3593
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3594
-                }
3595
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3596
-            } elseif (! empty($query_params['group_by'])) {
3597
-                $query_object->set_group_by_sql(
3598
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3599
-                );
3600
-            }
3601
-        }
3602
-        // set having
3603
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3604
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3605
-        }
3606
-        // now, just verify they didn't pass anything wack
3607
-        foreach ($query_params as $query_key => $query_value) {
3608
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3609
-                throw new EE_Error(
3610
-                    sprintf(
3611
-                        esc_html__(
3612
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3613
-                            'event_espresso'
3614
-                        ),
3615
-                        $query_key,
3616
-                        get_class($this),
3617
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3618
-                        implode(',', $this->_allowed_query_params)
3619
-                    )
3620
-                );
3621
-            }
3622
-        }
3623
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3624
-        if (empty($main_model_join_sql)) {
3625
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3626
-        }
3627
-        return $query_object;
3628
-    }
3629
-
3630
-
3631
-    /**
3632
-     * Gets the where conditions that should be imposed on the query based on the
3633
-     * context (eg reading frontend, backend, edit or delete).
3634
-     *
3635
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3636
-     * @return array
3637
-     * @throws EE_Error
3638
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3639
-     */
3640
-    public function caps_where_conditions($context = self::caps_read)
3641
-    {
3642
-        EEM_Base::verify_is_valid_cap_context($context);
3643
-        $cap_where_conditions = [];
3644
-        $cap_restrictions     = $this->caps_missing($context);
3645
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3646
-            $cap_where_conditions = array_replace_recursive(
3647
-                $cap_where_conditions,
3648
-                $restriction_if_no_cap->get_default_where_conditions()
3649
-            );
3650
-        }
3651
-        return apply_filters(
3652
-            'FHEE__EEM_Base__caps_where_conditions__return',
3653
-            $cap_where_conditions,
3654
-            $this,
3655
-            $context,
3656
-            $cap_restrictions
3657
-        );
3658
-    }
3659
-
3660
-
3661
-    /**
3662
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3663
-     * otherwise throws an exception
3664
-     *
3665
-     * @param string $should_be_order_string
3666
-     * @return string either ASC, asc, DESC or desc
3667
-     * @throws EE_Error
3668
-     */
3669
-    private function _extract_order($should_be_order_string)
3670
-    {
3671
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3672
-            return $should_be_order_string;
3673
-        }
3674
-        throw new EE_Error(
3675
-            sprintf(
3676
-                esc_html__(
3677
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3678
-                    "event_espresso"
3679
-                ),
3680
-                get_class($this),
3681
-                $should_be_order_string
3682
-            )
3683
-        );
3684
-    }
3685
-
3686
-
3687
-    /**
3688
-     * Looks at all the models which are included in this query, and asks each
3689
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3690
-     * so they can be merged
3691
-     *
3692
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3693
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3694
-     *                                                                  'none' means NO default where conditions will
3695
-     *                                                                  be used AT ALL during this query.
3696
-     *                                                                  'other_models_only' means default where
3697
-     *                                                                  conditions from other models will be used, but
3698
-     *                                                                  not for this primary model. 'all', the default,
3699
-     *                                                                  means default where conditions will apply as
3700
-     *                                                                  normal
3701
-     * @param array                       $where_query_params
3702
-     * @return array
3703
-     * @throws EE_Error
3704
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3705
-     */
3706
-    private function _get_default_where_conditions_for_models_in_query(
3707
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3708
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3709
-        $where_query_params = []
3710
-    ) {
3711
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3712
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3713
-            throw new EE_Error(
3714
-                sprintf(
3715
-                    esc_html__(
3716
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3717
-                        "event_espresso"
3718
-                    ),
3719
-                    $use_default_where_conditions,
3720
-                    implode(", ", $allowed_used_default_where_conditions_values)
3721
-                )
3722
-            );
3723
-        }
3724
-        $universal_query_params = [];
3725
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3726
-            $universal_query_params = $this->_get_default_where_conditions();
3727
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3728
-            $universal_query_params = $this->_get_minimum_where_conditions();
3729
-        }
3730
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3731
-            $related_model = $this->get_related_model_obj($model_name);
3732
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3733
-                $related_model_universal_where_params =
3734
-                    $related_model->_get_default_where_conditions($model_relation_path);
3735
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3736
-                $related_model_universal_where_params =
3737
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3738
-            } else {
3739
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3740
-                continue;
3741
-            }
3742
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3743
-                $related_model_universal_where_params,
3744
-                $where_query_params,
3745
-                $related_model,
3746
-                $model_relation_path
3747
-            );
3748
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3749
-                $universal_query_params,
3750
-                $overrides
3751
-            );
3752
-        }
3753
-        return $universal_query_params;
3754
-    }
3755
-
3756
-
3757
-    /**
3758
-     * Determines whether or not we should use default where conditions for the model in question
3759
-     * (this model, or other related models).
3760
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3761
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3762
-     * We should use default where conditions on related models when they requested to use default where conditions
3763
-     * on all models, or specifically just on other related models
3764
-     *
3765
-     * @param      $default_where_conditions_value
3766
-     * @param bool $for_this_model false means this is for OTHER related models
3767
-     * @return bool
3768
-     */
3769
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3770
-    {
3771
-        return (
3772
-                   $for_this_model
3773
-                   && in_array(
3774
-                       $default_where_conditions_value,
3775
-                       [
3776
-                           EEM_Base::default_where_conditions_all,
3777
-                           EEM_Base::default_where_conditions_this_only,
3778
-                           EEM_Base::default_where_conditions_minimum_others,
3779
-                       ],
3780
-                       true
3781
-                   )
3782
-               )
3783
-               || (
3784
-                   ! $for_this_model
3785
-                   && in_array(
3786
-                       $default_where_conditions_value,
3787
-                       [
3788
-                           EEM_Base::default_where_conditions_all,
3789
-                           EEM_Base::default_where_conditions_others_only,
3790
-                       ],
3791
-                       true
3792
-                   )
3793
-               );
3794
-    }
3795
-
3796
-
3797
-    /**
3798
-     * Determines whether or not we should use default minimum conditions for the model in question
3799
-     * (this model, or other related models).
3800
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3801
-     * where conditions.
3802
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3803
-     * on this model or others
3804
-     *
3805
-     * @param      $default_where_conditions_value
3806
-     * @param bool $for_this_model false means this is for OTHER related models
3807
-     * @return bool
3808
-     */
3809
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3810
-    {
3811
-        return (
3812
-                   $for_this_model
3813
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3814
-               )
3815
-               || (
3816
-                   ! $for_this_model
3817
-                   && in_array(
3818
-                       $default_where_conditions_value,
3819
-                       [
3820
-                           EEM_Base::default_where_conditions_minimum_others,
3821
-                           EEM_Base::default_where_conditions_minimum_all,
3822
-                       ],
3823
-                       true
3824
-                   )
3825
-               );
3826
-    }
3827
-
3828
-
3829
-    /**
3830
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3831
-     * then we also add a special where condition which allows for that model's primary key
3832
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3833
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3834
-     *
3835
-     * @param array    $default_where_conditions
3836
-     * @param array    $provided_where_conditions
3837
-     * @param EEM_Base $model
3838
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3839
-     * @return array
3840
-     * @throws EE_Error
3841
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3842
-     */
3843
-    private function _override_defaults_or_make_null_friendly(
3844
-        $default_where_conditions,
3845
-        $provided_where_conditions,
3846
-        $model,
3847
-        $model_relation_path
3848
-    ) {
3849
-        $null_friendly_where_conditions = [];
3850
-        $none_overridden                = true;
3851
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3852
-        foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3854
-                $none_overridden = false;
3855
-            } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
-            }
3858
-        }
3859
-        if ($none_overridden && $default_where_conditions) {
3860
-            if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
-                                                                                   . "."
3863
-                                                                                   . $model->primary_key_name() ] =
3864
-                    ['IS NULL'];
3865
-            }/*else{
40
+	/**
41
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
+	 */
43
+	const caps_read       = 'read';
44
+
45
+	const caps_read_admin = 'read_admin';
46
+
47
+	const caps_edit       = 'edit';
48
+
49
+	const caps_delete     = 'delete';
50
+
51
+
52
+	/**
53
+	 * constant used to show EEM_Base has not yet verified the db on this http request
54
+	 */
55
+	const db_verified_none = 0;
56
+
57
+	/**
58
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
59
+	 * but not the addons' dbs
60
+	 */
61
+	const db_verified_core = 1;
62
+
63
+	/**
64
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
+	 * the EE core db too)
66
+	 */
67
+	const db_verified_addons = 2;
68
+
69
+	/**
70
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
73
+	 */
74
+	const default_where_conditions_all = 'all';
75
+
76
+	/**
77
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
+	 *        models which share tables with other models, this can return data for the wrong model.
82
+	 */
83
+	const default_where_conditions_this_only = 'this_model_only';
84
+
85
+	/**
86
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
+	 */
90
+	const default_where_conditions_others_only = 'other_models_only';
91
+
92
+	/**
93
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
96
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
+	 *        (regardless of whether those events and venues are trashed)
98
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
+	 *        events.
100
+	 */
101
+	const default_where_conditions_minimum_all = 'minimum';
102
+
103
+	/**
104
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
+	 *        not)
108
+	 */
109
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
+
111
+	/**
112
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
+	 *        it's possible it will return table entries for other models. You should use
115
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
116
+	 */
117
+	const default_where_conditions_none = 'none';
118
+
119
+	/**
120
+	 * when $_values_already_prepared_by_model_object equals this, we assume
121
+	 * the data is just like form input that needs to have the model fields'
122
+	 * prepare_for_set and prepare_for_use_in_db called on it
123
+	 */
124
+	const not_prepared_by_model_object = 0;
125
+
126
+	/**
127
+	 * when $_values_already_prepared_by_model_object equals this, we
128
+	 * assume this value is coming from a model object and doesn't need to have
129
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
130
+	 */
131
+	const prepared_by_model_object = 1;
132
+
133
+	/**
134
+	 * when $_values_already_prepared_by_model_object equals this, we assume
135
+	 * the values are already to be used in the database (ie no processing is done
136
+	 * on them by the model's fields)
137
+	 */
138
+	const prepared_for_use_in_db = 2;
139
+
140
+	/**
141
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
144
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
+	 *
146
+	 * @var boolean
147
+	 */
148
+	private $_values_already_prepared_by_model_object = 0;
149
+
150
+
151
+	/**
152
+	 * @var string
153
+	 */
154
+	protected $singular_item = 'Item';
155
+
156
+	/**
157
+	 * @var string
158
+	 */
159
+	protected $plural_item = 'Items';
160
+
161
+	/**
162
+	 * array of EE_Table objects for defining which tables comprise this model.
163
+	 *
164
+	 * @type EE_Table_Base[] $_tables
165
+	 */
166
+	protected $_tables;
167
+
168
+	/**
169
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
+	 *
173
+	 * @var EE_Model_Field_Base[][] $_fields
174
+	 */
175
+	protected $_fields;
176
+
177
+	/**
178
+	 * array of different kinds of relations
179
+	 *
180
+	 * @var EE_Model_Relation_Base[] $_model_relations
181
+	 */
182
+	protected $_model_relations;
183
+
184
+	/**
185
+	 * @var EE_Index[] $_indexes
186
+	 */
187
+	protected $_indexes = [];
188
+
189
+	/**
190
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
191
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
+	 * by setting the same columns as used in these queries in the query yourself.
193
+	 *
194
+	 * @var EE_Default_Where_Conditions
195
+	 */
196
+	protected $_default_where_conditions_strategy;
197
+
198
+	/**
199
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
+	 * This is particularly useful when you want something between 'none' and 'default'
201
+	 *
202
+	 * @var EE_Default_Where_Conditions
203
+	 */
204
+	protected $_minimum_where_conditions_strategy;
205
+
206
+	/**
207
+	 * String describing how to find the "owner" of this model's objects.
208
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
+	 * But when there isn't, this indicates which related model, or transiently-related model,
210
+	 * has the foreign key to the wp_users table.
211
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
+	 * related to events, and events have a foreign key to wp_users.
213
+	 * On EEM_Transaction, this would be 'Transaction.Event'
214
+	 *
215
+	 * @var string
216
+	 */
217
+	protected $_model_chain_to_wp_user = '';
218
+
219
+	/**
220
+	 * String describing how to find the model with a password controlling access to this model. This property has the
221
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
+	 * This value is the path of models to follow to arrive at the model with the password field.
223
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
+	 * model with a password that should affect reading this on the front-end.
225
+	 * Eg this is an empty string for the Event model because it has a password.
226
+	 * This is null for the Registration model, because its event's password has no bearing on whether
227
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
+	 * should hide tickets for datetimes for events that have a password set.
230
+	 *
231
+	 * @var string |null
232
+	 */
233
+	protected $model_chain_to_password = null;
234
+
235
+	/**
236
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
+	 * don't need it (particularly CPT models)
238
+	 *
239
+	 * @var bool
240
+	 */
241
+	protected $_ignore_where_strategy = false;
242
+
243
+	/**
244
+	 * String used in caps relating to this model. Eg, if the caps relating to this
245
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
+	 *
247
+	 * @var string. If null it hasn't been initialized yet. If false then we
248
+	 * have indicated capabilities don't apply to this
249
+	 */
250
+	protected $_caps_slug = null;
251
+
252
+	/**
253
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
+	 * and next-level keys are capability names, and values are a
255
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
257
+	 * and then each capability in the corresponding sub-array that they're missing
258
+	 * adds the where conditions onto the query.
259
+	 *
260
+	 * @var array
261
+	 */
262
+	protected $_cap_restrictions = [
263
+		self::caps_read       => [],
264
+		self::caps_read_admin => [],
265
+		self::caps_edit       => [],
266
+		self::caps_delete     => [],
267
+	];
268
+
269
+	/**
270
+	 * Array defining which cap restriction generators to use to create default
271
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
272
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
+	 * automatically set this to false (not just null).
275
+	 *
276
+	 * @var EE_Restriction_Generator_Base[]
277
+	 */
278
+	protected $_cap_restriction_generators = [];
279
+
280
+	/**
281
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
+	 * maps to 'read' because when looking for relevant permissions we're going to use
284
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
285
+	 *
286
+	 * @var array
287
+	 */
288
+	protected $_cap_contexts_to_cap_action_map = [
289
+		self::caps_read       => 'read',
290
+		self::caps_read_admin => 'read',
291
+		self::caps_edit       => 'edit',
292
+		self::caps_delete     => 'delete',
293
+	];
294
+
295
+	/**
296
+	 * Timezone
297
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
+	 * EE_Datetime_Field data type will have access to it.
301
+	 *
302
+	 * @var string
303
+	 */
304
+	protected $_timezone;
305
+
306
+
307
+	/**
308
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
+	 * multisite.
310
+	 *
311
+	 * @var int
312
+	 */
313
+	protected static $_model_query_blog_id;
314
+
315
+	/**
316
+	 * A copy of _fields, except the array keys are the model names pointed to by
317
+	 * the field
318
+	 *
319
+	 * @var EE_Model_Field_Base[]
320
+	 */
321
+	private $_cache_foreign_key_to_fields = [];
322
+
323
+	/**
324
+	 * Cached list of all the fields on the model, indexed by their name
325
+	 *
326
+	 * @var EE_Model_Field_Base[]
327
+	 */
328
+	private $_cached_fields = null;
329
+
330
+	/**
331
+	 * Cached list of all the fields on the model, except those that are
332
+	 * marked as only pertinent to the database
333
+	 *
334
+	 * @var EE_Model_Field_Base[]
335
+	 */
336
+	private $_cached_fields_non_db_only = null;
337
+
338
+	/**
339
+	 * A cached reference to the primary key for quick lookup
340
+	 *
341
+	 * @var EE_Model_Field_Base
342
+	 */
343
+	private $_primary_key_field = null;
344
+
345
+	/**
346
+	 * Flag indicating whether this model has a primary key or not
347
+	 *
348
+	 * @var boolean
349
+	 */
350
+	protected $_has_primary_key_field = null;
351
+
352
+	/**
353
+	 * array in the format:  [ FK alias => full PK ]
354
+	 * where keys are local column name aliases for foreign keys
355
+	 * and values are the fully qualified column name for the primary key they represent
356
+	 *  ex:
357
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
+	 *
359
+	 * @var array $foreign_key_aliases
360
+	 */
361
+	protected $foreign_key_aliases = [];
362
+
363
+	/**
364
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
365
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
+	 * This should be true for models that deal with data that should exist independent of EE.
367
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
369
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
371
+	 *
372
+	 * @var boolean
373
+	 */
374
+	protected $_wp_core_model = false;
375
+
376
+	/**
377
+	 * @var bool stores whether this model has a password field or not.
378
+	 * null until initialized by hasPasswordField()
379
+	 */
380
+	protected $has_password_field;
381
+
382
+	/**
383
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
+	 */
385
+	protected $password_field;
386
+
387
+	/**
388
+	 *    List of valid operators that can be used for querying.
389
+	 * The keys are all operators we'll accept, the values are the real SQL
390
+	 * operators used
391
+	 *
392
+	 * @var array
393
+	 */
394
+	protected $_valid_operators = [
395
+		'='           => '=',
396
+		'<='          => '<=',
397
+		'<'           => '<',
398
+		'>='          => '>=',
399
+		'>'           => '>',
400
+		'!='          => '!=',
401
+		'LIKE'        => 'LIKE',
402
+		'like'        => 'LIKE',
403
+		'NOT_LIKE'    => 'NOT LIKE',
404
+		'not_like'    => 'NOT LIKE',
405
+		'NOT LIKE'    => 'NOT LIKE',
406
+		'not like'    => 'NOT LIKE',
407
+		'IN'          => 'IN',
408
+		'in'          => 'IN',
409
+		'NOT_IN'      => 'NOT IN',
410
+		'not_in'      => 'NOT IN',
411
+		'NOT IN'      => 'NOT IN',
412
+		'not in'      => 'NOT IN',
413
+		'between'     => 'BETWEEN',
414
+		'BETWEEN'     => 'BETWEEN',
415
+		'IS_NOT_NULL' => 'IS NOT NULL',
416
+		'is_not_null' => 'IS NOT NULL',
417
+		'IS NOT NULL' => 'IS NOT NULL',
418
+		'is not null' => 'IS NOT NULL',
419
+		'IS_NULL'     => 'IS NULL',
420
+		'is_null'     => 'IS NULL',
421
+		'IS NULL'     => 'IS NULL',
422
+		'is null'     => 'IS NULL',
423
+		'REGEXP'      => 'REGEXP',
424
+		'regexp'      => 'REGEXP',
425
+		'NOT_REGEXP'  => 'NOT REGEXP',
426
+		'not_regexp'  => 'NOT REGEXP',
427
+		'NOT REGEXP'  => 'NOT REGEXP',
428
+		'not regexp'  => 'NOT REGEXP',
429
+	];
430
+
431
+	/**
432
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
+	 *
434
+	 * @var array
435
+	 */
436
+	protected $_in_style_operators = ['IN', 'NOT IN'];
437
+
438
+	/**
439
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
+	 * '12-31-2012'"
441
+	 *
442
+	 * @var array
443
+	 */
444
+	protected $_between_style_operators = ['BETWEEN'];
445
+
446
+	/**
447
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
+
453
+	/**
454
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
+	 * on a join table.
456
+	 *
457
+	 * @var array
458
+	 */
459
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
+
461
+	/**
462
+	 * Allowed values for $query_params['order'] for ordering in queries
463
+	 *
464
+	 * @var array
465
+	 */
466
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
+
468
+	/**
469
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
471
+	 *
472
+	 * @var array
473
+	 */
474
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
+
476
+	/**
477
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
479
+	 *
480
+	 * @var array
481
+	 */
482
+	private $_allowed_query_params = [
483
+		0,
484
+		'limit',
485
+		'order_by',
486
+		'group_by',
487
+		'having',
488
+		'force_join',
489
+		'order',
490
+		'on_join_limit',
491
+		'default_where_conditions',
492
+		'caps',
493
+		'extra_selects',
494
+		'exclude_protected',
495
+	];
496
+
497
+	/**
498
+	 * All the data types that can be used in $wpdb->prepare statements.
499
+	 *
500
+	 * @var array
501
+	 */
502
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
+
504
+	/**
505
+	 * @var EE_Registry $EE
506
+	 */
507
+	protected $EE = null;
508
+
509
+
510
+	/**
511
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
+	 *
513
+	 * @var int
514
+	 */
515
+	protected $_show_next_x_db_queries = 0;
516
+
517
+	/**
518
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
+	 * WHERE, GROUP_BY, etc.
521
+	 *
522
+	 * @var CustomSelects
523
+	 */
524
+	protected $_custom_selections = [];
525
+
526
+	/**
527
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
+	 * caches every model object we've fetched from the DB on this request
529
+	 *
530
+	 * @var array
531
+	 */
532
+	protected $_entity_map;
533
+
534
+	/**
535
+	 * @var LoaderInterface $loader
536
+	 */
537
+	private static $loader;
538
+
539
+	/**
540
+	 * indicates whether an EEM_Base child has already re-verified the DB
541
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
542
+	 * looking like EEM_Base::db_verified_*
543
+	 *
544
+	 * @var int - 0 = none, 1 = core, 2 = addons
545
+	 */
546
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
547
+
548
+
549
+	/**
550
+	 * About all child constructors:
551
+	 * they should define the _tables, _fields and _model_relations arrays.
552
+	 * Should ALWAYS be called after child constructor.
553
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
554
+	 * finalizes constructing all the object's attributes.
555
+	 * Generally, rather than requiring a child to code
556
+	 * $this->_tables = array(
557
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
+	 *        ...);
559
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
+	 * each EE_Table has a function to set the table's alias after the constructor, using
561
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
+	 * do something similar.
563
+	 *
564
+	 * @param string $timezone
565
+	 * @throws EE_Error
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				/** @var $table_obj EE_Secondary_Table */
599
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
+			}
601
+		}
602
+		/**
603
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
+		 * EE_Register_Model_Extension
605
+		 *
606
+		 * @param EE_Model_Field_Base[] $_fields
607
+		 */
608
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
+		$this->_invalidate_field_caches();
610
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
611
+			if (! array_key_exists($table_alias, $this->_tables)) {
612
+				throw new EE_Error(
613
+					sprintf(
614
+						esc_html__(
615
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
+							'event_espresso'
617
+						),
618
+						$table_alias,
619
+						implode(",", $this->_fields)
620
+					)
621
+				);
622
+			}
623
+			foreach ($fields_for_table as $field_name => $field_obj) {
624
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
+				// primary key field base has a slightly different _construct_finalize
626
+				/** @var $field_obj EE_Model_Field_Base */
627
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
+			}
629
+		}
630
+		// everything is related to Extra_Meta
631
+		if (get_class($this) !== 'EEM_Extra_Meta') {
632
+			// make extra meta related to everything, but don't block deleting things just
633
+			// because they have related extra meta info. For now just orphan those extra meta
634
+			// in the future we should automatically delete them
635
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
+		}
637
+		// and change logs
638
+		if (get_class($this) !== 'EEM_Change_Log') {
639
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
+		}
641
+		/**
642
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
+		 * EE_Register_Model_Extension
644
+		 *
645
+		 * @param EE_Model_Relation_Base[] $_model_relations
646
+		 */
647
+		$this->_model_relations = (array) apply_filters(
648
+			'FHEE__' . get_class($this) . '__construct__model_relations',
649
+			$this->_model_relations
650
+		);
651
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
652
+			/** @var $relation_obj EE_Model_Relation_Base */
653
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
+		}
655
+		foreach ($this->_indexes as $index_name => $index_obj) {
656
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
+		}
658
+		$this->set_timezone($timezone);
659
+		// finalize default where condition strategy, or set default
660
+		if (! $this->_default_where_conditions_strategy) {
661
+			// nothing was set during child constructor, so set default
662
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
+		}
664
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
665
+		if (! $this->_minimum_where_conditions_strategy) {
666
+			// nothing was set during child constructor, so set default
667
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
+		}
669
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
671
+		// to indicate to NOT set it, set it to the logical default
672
+		if ($this->_caps_slug === null) {
673
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
+		}
675
+		// initialize the standard cap restriction generators if none were specified by the child constructor
676
+		if ($this->_cap_restriction_generators !== false) {
677
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
+						new EE_Restriction_Generator_Protected(),
682
+						$cap_context,
683
+						$this
684
+					);
685
+				}
686
+			}
687
+		}
688
+		// if there are cap restriction generators, use them to make the default cap restrictions
689
+		if ($this->_cap_restriction_generators !== false) {
690
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
+				if (! $generator_object) {
692
+					continue;
693
+				}
694
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
+					throw new EE_Error(
696
+						sprintf(
697
+							esc_html__(
698
+								'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.',
699
+								'event_espresso'
700
+							),
701
+							$context,
702
+							$this->get_this_model_name()
703
+						)
704
+					);
705
+				}
706
+				$action = $this->cap_action_for_context($context);
707
+				if (! $generator_object->construction_finalized()) {
708
+					$generator_object->_construct_finalize($this, $action);
709
+				}
710
+			}
711
+		}
712
+		do_action('AHEE__' . get_class($this) . '__construct__end');
713
+	}
714
+
715
+
716
+	/**
717
+	 * Used to set the $_model_query_blog_id static property.
718
+	 *
719
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
+	 *                      value for get_current_blog_id() will be used.
721
+	 */
722
+	public static function set_model_query_blog_id($blog_id = 0)
723
+	{
724
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
725
+	}
726
+
727
+
728
+	/**
729
+	 * Returns whatever is set as the internal $model_query_blog_id.
730
+	 *
731
+	 * @return int
732
+	 */
733
+	public static function get_model_query_blog_id()
734
+	{
735
+		return EEM_Base::$_model_query_blog_id;
736
+	}
737
+
738
+
739
+	/**
740
+	 * This function is a singleton method used to instantiate the Espresso_model object
741
+	 *
742
+	 * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
+	 *                                (and any incoming timezone data that gets saved).
744
+	 *                                Note this just sends the timezone info to the date time model field objects.
745
+	 *                                Default is NULL
746
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
+	 * @return EEM_Base (as in the concrete child class)
748
+	 * @throws EE_Error
749
+	 * @throws InvalidArgumentException
750
+	 * @throws InvalidDataTypeException
751
+	 * @throws InvalidInterfaceException
752
+	 */
753
+	public static function instance($timezone = '')
754
+	{
755
+		// check if instance of Espresso_model already exists
756
+		if (! static::$_instance instanceof static) {
757
+			// instantiate Espresso_model
758
+			static::$_instance = new static(
759
+				$timezone,
760
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
+			);
762
+		}
763
+		// Espresso model object
764
+		return static::$_instance;
765
+	}
766
+
767
+
768
+	/**
769
+	 * resets the model and returns it
770
+	 *
771
+	 * @param string $timezone
772
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
+	 * all its properties reset; if it wasn't instantiated, returns null)
774
+	 * @throws EE_Error
775
+	 * @throws ReflectionException
776
+	 * @throws InvalidArgumentException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws InvalidInterfaceException
779
+	 */
780
+	public static function reset($timezone = '')
781
+	{
782
+		if (static::$_instance instanceof EEM_Base) {
783
+			// let's try to NOT swap out the current instance for a new one
784
+			// because if someone has a reference to it, we can't remove their reference
785
+			// so it's best to keep using the same reference, but change the original object
786
+			// reset all its properties to their original values as defined in the class
787
+			$r                 = new ReflectionClass(get_class(static::$_instance));
788
+			$static_properties = $r->getStaticProperties();
789
+			foreach ($r->getDefaultProperties() as $property => $value) {
790
+				// don't set instance to null like it was originally,
791
+				// but it's static anyways, and we're ignoring static properties (for now at least)
792
+				if (! isset($static_properties[ $property ])) {
793
+					static::$_instance->{$property} = $value;
794
+				}
795
+			}
796
+			EEH_DTT_Helper::resetDefaultTimezoneString();
797
+			// and then directly call its constructor again, like we would if we were creating a new one
798
+			static::$_instance->__construct(
799
+				$timezone,
800
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
+			);
802
+			return static::instance();
803
+		}
804
+		return null;
805
+	}
806
+
807
+
808
+	/**
809
+	 * @return LoaderInterface
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 */
814
+	private static function getLoader()
815
+	{
816
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
817
+			EEM_Base::$loader = LoaderFactory::getLoader();
818
+		}
819
+		return EEM_Base::$loader;
820
+	}
821
+
822
+
823
+	/**
824
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
+	 *
826
+	 * @param boolean $translated return localized strings or JUST the array.
827
+	 * @return array
828
+	 * @throws EE_Error
829
+	 * @throws InvalidArgumentException
830
+	 * @throws InvalidDataTypeException
831
+	 * @throws InvalidInterfaceException
832
+	 * @throws ReflectionException
833
+	 */
834
+	public function status_array($translated = false)
835
+	{
836
+		if (! array_key_exists('Status', $this->_model_relations)) {
837
+			return [];
838
+		}
839
+		$model_name   = $this->get_this_model_name();
840
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
+		$status_array = [];
843
+		foreach ($stati as $status) {
844
+			$status_array[ $status->ID() ] = $status->get('STS_code');
845
+		}
846
+		return $translated
847
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
+			: $status_array;
849
+	}
850
+
851
+
852
+	/**
853
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
+	 *
855
+	 * @param array $query_params             see github link below for more info
856
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
861
+	 *                                        'OR'=>array(
862
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
+	 *                                        )
865
+	 *                                        ),
866
+	 *                                        'limit'=>10,
867
+	 *                                        'group_by'=>'TXN_ID'
868
+	 *                                        ));
869
+	 *                                        get all the answers to the question titled "shirt size" for event with id
870
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
+	 *                                        'Question.QST_display_text'=>'shirt size',
872
+	 *                                        'Registration.Event.EVT_ID'=>12
873
+	 *                                        ),
874
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
875
+	 *                                        ));
876
+	 * @throws EE_Error
877
+	 * @throws ReflectionException
878
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
+	 *                                        or if you have the development copy of EE you can view this at the path:
880
+	 *                                        /docs/G--Model-System/model-query-params.md
881
+	 */
882
+	public function get_all($query_params = [])
883
+	{
884
+		if (
885
+			isset($query_params['limit'])
886
+			&& ! isset($query_params['group_by'])
887
+		) {
888
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
+		}
890
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
+	}
892
+
893
+
894
+	/**
895
+	 * Modifies the query parameters so we only get back model objects
896
+	 * that "belong" to the current user
897
+	 *
898
+	 * @param array $query_params see github link below for more info
899
+	 * @return array
900
+	 * @throws ReflectionException
901
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 */
903
+	public function alter_query_params_to_only_include_mine($query_params = [])
904
+	{
905
+		$wp_user_field_name = $this->wp_user_field_name();
906
+		if ($wp_user_field_name) {
907
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
+		}
909
+		return $query_params;
910
+	}
911
+
912
+
913
+	/**
914
+	 * Returns the name of the field's name that points to the WP_User table
915
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
+	 * foreign key to the WP_User table)
917
+	 *
918
+	 * @return string|boolean string on success, boolean false when there is no
919
+	 * foreign key to the WP_User table
920
+	 * @throws ReflectionException
921
+	 */
922
+	public function wp_user_field_name()
923
+	{
924
+		try {
925
+			if (! empty($this->_model_chain_to_wp_user)) {
926
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
+				$last_model_name              = end($models_to_follow_to_wp_users);
928
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
+			} else {
931
+				$model_with_fk_to_wp_users = $this;
932
+				$model_chain_to_wp_user    = '';
933
+			}
934
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
936
+		} catch (EE_Error $e) {
937
+			return false;
938
+		}
939
+	}
940
+
941
+
942
+	/**
943
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
944
+	 * (or transiently-related model) has a foreign key to the wp_users table;
945
+	 * useful for finding if model objects of this type are 'owned' by the current user.
946
+	 * This is an empty string when the foreign key is on this model and when it isn't,
947
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
948
+	 * (or transiently-related model)
949
+	 *
950
+	 * @return string
951
+	 */
952
+	public function model_chain_to_wp_user()
953
+	{
954
+		return $this->_model_chain_to_wp_user;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
+	 * like how registrations don't have a foreign key to wp_users, but the
961
+	 * events they are for are), or is unrelated to wp users.
962
+	 * generally available
963
+	 *
964
+	 * @return boolean
965
+	 */
966
+	public function is_owned()
967
+	{
968
+		if ($this->model_chain_to_wp_user()) {
969
+			return true;
970
+		}
971
+		try {
972
+			$this->get_foreign_key_to('WP_User');
973
+			return true;
974
+		} catch (EE_Error $e) {
975
+			return false;
976
+		}
977
+	}
978
+
979
+
980
+	/**
981
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
+	 * the model)
984
+	 *
985
+	 * @param array  $query_params
986
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
989
+	 *                                  override this and set the select to "*", or a specific column name, like
990
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
+	 *                                  the aliases used to refer to this selection, and values are to be
993
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws ReflectionException
999
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
+	 */
1001
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
+	{
1003
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
+		$select_expressions       = $columns_to_select === null
1006
+			? $this->_construct_default_select_sql($model_query_info)
1007
+			: '';
1008
+		if ($this->_custom_selections instanceof CustomSelects) {
1009
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
+			$select_expressions .= $select_expressions
1011
+				? ', ' . $custom_expressions
1012
+				: $custom_expressions;
1013
+		}
1014
+
1015
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
+	 * method of including extra select information.
1024
+	 *
1025
+	 * @param array             $query_params
1026
+	 * @param null|array|string $columns_to_select
1027
+	 * @return null|CustomSelects
1028
+	 * @throws InvalidArgumentException
1029
+	 */
1030
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
+	{
1032
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
+			return null;
1034
+		}
1035
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
+		return new CustomSelects($selects);
1038
+	}
1039
+
1040
+
1041
+	/**
1042
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1043
+	 * but you can use the model query params to more easily
1044
+	 * take care of joins, field preparation etc.
1045
+	 *
1046
+	 * @param array  $query_params
1047
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1050
+	 *                                  override this and set the select to "*", or a specific column name, like
1051
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
+	 *                                  the aliases used to refer to this selection, and values are to be
1054
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
+	 * @throws EE_Error
1058
+	 * @throws ReflectionException
1059
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
+	 */
1061
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
+	{
1063
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * For creating a custom select statement
1069
+	 *
1070
+	 * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
+	 *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
+	 *                                        selection SQL, and 1=>is the datatype
1073
+	 * @return string
1074
+	 * @throws EE_Error
1075
+	 */
1076
+	private function _construct_select_from_input($columns_to_select)
1077
+	{
1078
+		if (is_array($columns_to_select)) {
1079
+			$select_sql_array = [];
1080
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype,
1089
+							$alias
1090
+						)
1091
+					);
1092
+				}
1093
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
+					throw new EE_Error(
1095
+						sprintf(
1096
+							esc_html__(
1097
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
+								'event_espresso'
1099
+							),
1100
+							$selection_and_datatype[1],
1101
+							$selection_and_datatype[0],
1102
+							$alias,
1103
+							implode(', ', $this->_valid_wpdb_data_types)
1104
+						)
1105
+					);
1106
+				}
1107
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
+			}
1109
+			$columns_to_select_string = implode(', ', $select_sql_array);
1110
+		} else {
1111
+			$columns_to_select_string = $columns_to_select;
1112
+		}
1113
+		return $columns_to_select_string;
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
+	 *
1120
+	 * @return string
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function primary_key_name()
1124
+	{
1125
+		return $this->get_primary_key_field()->get_name();
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
+	 * If there is no primary key on this model, $id is treated as primary key string
1132
+	 *
1133
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1134
+	 * @return EE_Base_Class
1135
+	 * @throws EE_Error
1136
+	 * @throws ReflectionException
1137
+	 */
1138
+	public function get_one_by_ID($id)
1139
+	{
1140
+		if ($this->get_from_entity_map($id)) {
1141
+			return $this->get_from_entity_map($id);
1142
+		}
1143
+		return $this->get_one(
1144
+			$this->alter_query_params_to_restrict_by_ID(
1145
+				$id,
1146
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
+			)
1148
+		);
1149
+	}
1150
+
1151
+
1152
+	/**
1153
+	 * Alters query parameters to only get items with this ID are returned.
1154
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1155
+	 * or could just be a simple primary key ID
1156
+	 *
1157
+	 * @param int   $id
1158
+	 * @param array $query_params see github link below for more info
1159
+	 * @return array of normal query params,
1160
+	 * @throws EE_Error
1161
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1162
+	 */
1163
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1164
+	{
1165
+		if (! isset($query_params[0])) {
1166
+			$query_params[0] = [];
1167
+		}
1168
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1169
+		if ($conditions_from_id === null) {
1170
+			$query_params[0][ $this->primary_key_name() ] = $id;
1171
+		} else {
1172
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1173
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1174
+		}
1175
+		return $query_params;
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1181
+	 * array. If no item is found, null is returned.
1182
+	 *
1183
+	 * @param array $query_params like EEM_Base's $query_params variable.
1184
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1185
+	 * @throws EE_Error
1186
+	 * @throws ReflectionException
1187
+	 */
1188
+	public function get_one($query_params = [])
1189
+	{
1190
+		if (! is_array($query_params)) {
1191
+			EE_Error::doing_it_wrong(
1192
+				'EEM_Base::get_one',
1193
+				sprintf(
1194
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1195
+					gettype($query_params)
1196
+				),
1197
+				'4.6.0'
1198
+			);
1199
+			$query_params = [];
1200
+		}
1201
+		$query_params['limit'] = 1;
1202
+		$items                 = $this->get_all($query_params);
1203
+		if (empty($items)) {
1204
+			return null;
1205
+		}
1206
+		return array_shift($items);
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 * Returns the next x number of items in sequence from the given value as
1212
+	 * found in the database matching the given query conditions.
1213
+	 *
1214
+	 * @param mixed $current_field_value    Value used for the reference point.
1215
+	 * @param null  $field_to_order_by      What field is used for the
1216
+	 *                                      reference point.
1217
+	 * @param int   $limit                  How many to return.
1218
+	 * @param array $query_params           Extra conditions on the query.
1219
+	 * @param null  $columns_to_select      If left null, then an array of
1220
+	 *                                      EE_Base_Class objects is returned,
1221
+	 *                                      otherwise you can indicate just the
1222
+	 *                                      columns you want returned.
1223
+	 * @return EE_Base_Class[]|array
1224
+	 * @throws EE_Error
1225
+	 * @throws ReflectionException
1226
+	 */
1227
+	public function next_x(
1228
+		$current_field_value,
1229
+		$field_to_order_by = null,
1230
+		$limit = 1,
1231
+		$query_params = [],
1232
+		$columns_to_select = null
1233
+	) {
1234
+		return $this->_get_consecutive(
1235
+			$current_field_value,
1236
+			'>',
1237
+			$field_to_order_by,
1238
+			$limit,
1239
+			$query_params,
1240
+			$columns_to_select
1241
+		);
1242
+	}
1243
+
1244
+
1245
+	/**
1246
+	 * Returns the previous x number of items in sequence from the given value
1247
+	 * as found in the database matching the given query conditions.
1248
+	 *
1249
+	 * @param mixed $current_field_value    Value used for the reference point.
1250
+	 * @param null  $field_to_order_by      What field is used for the
1251
+	 *                                      reference point.
1252
+	 * @param int   $limit                  How many to return.
1253
+	 * @param array $query_params           Extra conditions on the query.
1254
+	 * @param null  $columns_to_select      If left null, then an array of
1255
+	 *                                      EE_Base_Class objects is returned,
1256
+	 *                                      otherwise you can indicate just the
1257
+	 *                                      columns you want returned.
1258
+	 * @return EE_Base_Class[]|array
1259
+	 * @throws EE_Error
1260
+	 * @throws ReflectionException
1261
+	 */
1262
+	public function previous_x(
1263
+		$current_field_value,
1264
+		$field_to_order_by = null,
1265
+		$limit = 1,
1266
+		$query_params = [],
1267
+		$columns_to_select = null
1268
+	) {
1269
+		return $this->_get_consecutive(
1270
+			$current_field_value,
1271
+			'<',
1272
+			$field_to_order_by,
1273
+			$limit,
1274
+			$query_params,
1275
+			$columns_to_select
1276
+		);
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * Returns the next item in sequence from the given value as found in the
1282
+	 * database matching the given query conditions.
1283
+	 *
1284
+	 * @param mixed $current_field_value    Value used for the reference point.
1285
+	 * @param null  $field_to_order_by      What field is used for the
1286
+	 *                                      reference point.
1287
+	 * @param array $query_params           Extra conditions on the query.
1288
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1289
+	 *                                      object is returned, otherwise you
1290
+	 *                                      can indicate just the columns you
1291
+	 *                                      want and a single array indexed by
1292
+	 *                                      the columns will be returned.
1293
+	 * @return EE_Base_Class|null|array()
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function next(
1298
+		$current_field_value,
1299
+		$field_to_order_by = null,
1300
+		$query_params = [],
1301
+		$columns_to_select = null
1302
+	) {
1303
+		$results = $this->_get_consecutive(
1304
+			$current_field_value,
1305
+			'>',
1306
+			$field_to_order_by,
1307
+			1,
1308
+			$query_params,
1309
+			$columns_to_select
1310
+		);
1311
+		return empty($results) ? null : reset($results);
1312
+	}
1313
+
1314
+
1315
+	/**
1316
+	 * Returns the previous item in sequence from the given value as found in
1317
+	 * the database matching the given query conditions.
1318
+	 *
1319
+	 * @param mixed $current_field_value    Value used for the reference point.
1320
+	 * @param null  $field_to_order_by      What field is used for the
1321
+	 *                                      reference point.
1322
+	 * @param array $query_params           Extra conditions on the query.
1323
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
+	 *                                      object is returned, otherwise you
1325
+	 *                                      can indicate just the columns you
1326
+	 *                                      want and a single array indexed by
1327
+	 *                                      the columns will be returned.
1328
+	 * @return EE_Base_Class|null|array()
1329
+	 * @throws EE_Error
1330
+	 * @throws ReflectionException
1331
+	 */
1332
+	public function previous(
1333
+		$current_field_value,
1334
+		$field_to_order_by = null,
1335
+		$query_params = [],
1336
+		$columns_to_select = null
1337
+	) {
1338
+		$results = $this->_get_consecutive(
1339
+			$current_field_value,
1340
+			'<',
1341
+			$field_to_order_by,
1342
+			1,
1343
+			$query_params,
1344
+			$columns_to_select
1345
+		);
1346
+		return empty($results) ? null : reset($results);
1347
+	}
1348
+
1349
+
1350
+	/**
1351
+	 * Returns the a consecutive number of items in sequence from the given
1352
+	 * value as found in the database matching the given query conditions.
1353
+	 *
1354
+	 * @param mixed  $current_field_value   Value used for the reference point.
1355
+	 * @param string $operand               What operand is used for the sequence.
1356
+	 * @param string $field_to_order_by     What field is used for the reference point.
1357
+	 * @param int    $limit                 How many to return.
1358
+	 * @param array  $query_params          Extra conditions on the query.
1359
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1360
+	 *                                      otherwise you can indicate just the columns you want returned.
1361
+	 * @return EE_Base_Class[]|array
1362
+	 * @throws EE_Error
1363
+	 * @throws ReflectionException
1364
+	 */
1365
+	protected function _get_consecutive(
1366
+		$current_field_value,
1367
+		$operand = '>',
1368
+		$field_to_order_by = null,
1369
+		$limit = 1,
1370
+		$query_params = [],
1371
+		$columns_to_select = null
1372
+	) {
1373
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1374
+		if (empty($field_to_order_by)) {
1375
+			if ($this->has_primary_key_field()) {
1376
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1377
+			} else {
1378
+				if (WP_DEBUG) {
1379
+					throw new EE_Error(
1380
+						esc_html__(
1381
+							'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).',
1382
+							'event_espresso'
1383
+						)
1384
+					);
1385
+				}
1386
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1387
+				return [];
1388
+			}
1389
+		}
1390
+		if (! is_array($query_params)) {
1391
+			EE_Error::doing_it_wrong(
1392
+				'EEM_Base::_get_consecutive',
1393
+				sprintf(
1394
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1395
+					gettype($query_params)
1396
+				),
1397
+				'4.6.0'
1398
+			);
1399
+			$query_params = [];
1400
+		}
1401
+		// let's add the where query param for consecutive look up.
1402
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1403
+		$query_params['limit']                 = $limit;
1404
+		// set direction
1405
+		$incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1406
+		$query_params['order_by'] = $operand === '>'
1407
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1408
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1409
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1410
+		if (empty($columns_to_select)) {
1411
+			return $this->get_all($query_params);
1412
+		}
1413
+		// getting just the fields
1414
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1415
+	}
1416
+
1417
+
1418
+	/**
1419
+	 * This sets the _timezone property after model object has been instantiated.
1420
+	 *
1421
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1422
+	 */
1423
+	public function set_timezone($timezone = '')
1424
+	{
1425
+		static $set_in_progress = false;
1426
+		// if incoming timezone string is empty, then use the existing
1427
+		$valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1428
+			? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1429
+			: $this->_timezone;
1430
+		// do NOT set the timezone if we are already in the process of setting the timezone
1431
+		// OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1432
+		// OR the existing timezone is already set and the validated value is the same as the existing timezone
1433
+		if (
1434
+			$set_in_progress
1435
+			|| (
1436
+				! empty($this->_timezone)
1437
+				&& (
1438
+					empty($timezone) || $valid_timezone === $this->_timezone
1439
+				)
1440
+			)
1441
+		) {
1442
+			return;
1443
+		}
1444
+		$set_in_progress = true;
1445
+		$this->_timezone = $valid_timezone ? $valid_timezone : EEH_DTT_Helper::get_valid_timezone_string();
1446
+		// note we need to loop through relations and set the timezone on those objects as well.
1447
+		foreach ($this->_model_relations as $relation) {
1448
+			$relation->set_timezone($this->_timezone);
1449
+		}
1450
+		// and finally we do the same for any datetime fields
1451
+		foreach ($this->_fields as $field) {
1452
+			if ($field instanceof EE_Datetime_Field) {
1453
+				$field->set_timezone($this->_timezone);
1454
+			}
1455
+		}
1456
+		$set_in_progress = false;
1457
+	}
1458
+
1459
+
1460
+	/**
1461
+	 * This just returns whatever is set for the current timezone.
1462
+	 *
1463
+	 * @access public
1464
+	 * @return string
1465
+	 */
1466
+	public function get_timezone()
1467
+	{
1468
+		if (empty($this->_timezone)) {
1469
+			$this->set_timezone();
1470
+		}
1471
+		return $this->_timezone;
1472
+	}
1473
+
1474
+
1475
+	/**
1476
+	 * This returns the date formats set for the given field name and also ensures that
1477
+	 * $this->_timezone property is set correctly.
1478
+	 *
1479
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1480
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1481
+	 * @return array formats in an array with the date format first, and the time format last.
1482
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1483
+	 * @since 4.6.x
1484
+	 */
1485
+	public function get_formats_for($field_name, $pretty = false)
1486
+	{
1487
+		$field_settings = $this->field_settings_for($field_name);
1488
+		// if not a valid EE_Datetime_Field then throw error
1489
+		if (! $field_settings instanceof EE_Datetime_Field) {
1490
+			throw new EE_Error(
1491
+				sprintf(
1492
+					esc_html__(
1493
+						'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.',
1494
+						'event_espresso'
1495
+					),
1496
+					$field_name
1497
+				)
1498
+			);
1499
+		}
1500
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1501
+		$field_timezone = $field_settings->get_timezone();
1502
+		if (empty($this->_timezone && $field_timezone)) {
1503
+			$this->set_timezone();
1504
+		} else {
1505
+			// or vice versa if the field TZ isn't set
1506
+			$model_timezone = $this->get_timezone();
1507
+			$field_settings->set_timezone($model_timezone);
1508
+		}
1509
+
1510
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1511
+	}
1512
+
1513
+
1514
+	/**
1515
+	 * This returns the current time in a format setup for a query on this model.
1516
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1517
+	 * it will return:
1518
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1519
+	 *  NOW
1520
+	 *  - or a unix timestamp (equivalent to time())
1521
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1522
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1523
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1524
+	 *
1525
+	 * @param string $field_name       The field the current time is needed for.
1526
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1527
+	 *                                 formatted string matching the set format for the field in the set timezone will
1528
+	 *                                 be returned.
1529
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1530
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1531
+	 *                                 exception is triggered.
1532
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1533
+	 * @throws Exception
1534
+	 * @since 4.6.x
1535
+	 */
1536
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1537
+	{
1538
+		$formats  = $this->get_formats_for($field_name);
1539
+		$DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1540
+		if ($timestamp) {
1541
+			return $DateTime->format('U');
1542
+		}
1543
+		// not returning timestamp, so return formatted string in timezone.
1544
+		switch ($what) {
1545
+			case 'time':
1546
+				return $DateTime->format($formats[1]);
1547
+			case 'date':
1548
+				return $DateTime->format($formats[0]);
1549
+			default:
1550
+				return $DateTime->format(implode(' ', $formats));
1551
+		}
1552
+	}
1553
+
1554
+
1555
+	/**
1556
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1557
+	 * for the model are.  Returns a DateTime object.
1558
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1559
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1560
+	 * ignored.
1561
+	 *
1562
+	 * @param string $field_name    The field being setup.
1563
+	 * @param string $timestring    The date time string being used.
1564
+	 * @param string $format        The format for the time string.
1565
+	 * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1566
+	 *                              the blog.  If this is not the case, then it can be specified here.
1567
+	 *                              If incoming format is 'U', this is ignored.
1568
+	 * @return DbSafeDateTime
1569
+	 * @throws EE_Error
1570
+	 * @throws Exception
1571
+	 */
1572
+	public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1573
+	{
1574
+		// just using this to ensure the timezone is set correctly internally
1575
+		$this->get_formats_for($field_name);
1576
+		$timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1577
+		$db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1578
+		EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1579
+		return $db_safe_datetime;
1580
+	}
1581
+
1582
+
1583
+	/**
1584
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1585
+	 *
1586
+	 * @return EE_Table_Base[]
1587
+	 */
1588
+	public function get_tables()
1589
+	{
1590
+		return $this->_tables;
1591
+	}
1592
+
1593
+
1594
+	/**
1595
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1596
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1597
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1598
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1599
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1600
+	 * model object with EVT_ID = 1
1601
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1602
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1603
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1604
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1605
+	 * are not specified)
1606
+	 *
1607
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1608
+	 *                                         columns!), values are strings, integers, floats, and maybe arrays if
1609
+	 *                                         they
1610
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1611
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1612
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1613
+	 *                                         ID=34, we'd use this method as follows:
1614
+	 *                                         EEM_Transaction::instance()->update(
1615
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1616
+	 *                                         array(array('TXN_ID'=>34)));
1617
+	 * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1618
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1619
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1620
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1621
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1622
+	 *                                         TRUE, it is assumed that you've already called
1623
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1624
+	 *                                         malicious javascript. However, if
1625
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1626
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1627
+	 *                                         and every other field, before insertion. We provide this parameter
1628
+	 *                                         because model objects perform their prepare_for_set function on all
1629
+	 *                                         their values, and so don't need to be called again (and in many cases,
1630
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1631
+	 *                                         prepare_for_set method...)
1632
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1633
+	 *                                         in this model's entity map according to $fields_n_values that match
1634
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1635
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1636
+	 *                                         could get out-of-sync with the database
1637
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1638
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1639
+	 *                                         bad)
1640
+	 * @throws EE_Error
1641
+	 * @throws ReflectionException
1642
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1643
+	 */
1644
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1645
+	{
1646
+		if (! is_array($query_params)) {
1647
+			EE_Error::doing_it_wrong(
1648
+				'EEM_Base::update',
1649
+				sprintf(
1650
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1651
+					gettype($query_params)
1652
+				),
1653
+				'4.6.0'
1654
+			);
1655
+			$query_params = [];
1656
+		}
1657
+		/**
1658
+		 * Action called before a model update call has been made.
1659
+		 *
1660
+		 * @param EEM_Base $model
1661
+		 * @param array    $fields_n_values the updated fields and their new values
1662
+		 * @param array    $query_params
1663
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1664
+		 */
1665
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1666
+		/**
1667
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1668
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1669
+		 *
1670
+		 * @param array    $fields_n_values fields and their new values
1671
+		 * @param EEM_Base $model           the model being queried
1672
+		 * @param array    $query_params
1673
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1674
+		 */
1675
+		$fields_n_values = (array) apply_filters(
1676
+			'FHEE__EEM_Base__update__fields_n_values',
1677
+			$fields_n_values,
1678
+			$this,
1679
+			$query_params
1680
+		);
1681
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1682
+		// to do that, for each table, verify that it's PK isn't null.
1683
+		$tables = $this->get_tables();
1684
+		// 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
1685
+		// NOTE: we should make this code more efficient by NOT querying twice
1686
+		// before the real update, but that needs to first go through ALPHA testing
1687
+		// as it's dangerous. says Mike August 8 2014
1688
+		// we want to make sure the default_where strategy is ignored
1689
+		$this->_ignore_where_strategy = true;
1690
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1691
+		foreach ($wpdb_select_results as $wpdb_result) {
1692
+			// type cast stdClass as array
1693
+			$wpdb_result = (array) $wpdb_result;
1694
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1695
+			if ($this->has_primary_key_field()) {
1696
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1697
+			} else {
1698
+				// 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)
1699
+				$main_table_pk_value = null;
1700
+			}
1701
+			// 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
1702
+			// 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
1703
+			if (count($tables) > 1) {
1704
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1705
+				// in that table, and so we'll want to insert one
1706
+				foreach ($tables as $table_obj) {
1707
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1708
+					// if there is no private key for this table on the results, it means there's no entry
1709
+					// in this table, right? so insert a row in the current table, using any fields available
1710
+					if (
1711
+					! (array_key_exists($this_table_pk_column, $wpdb_result)
1712
+					   && $wpdb_result[ $this_table_pk_column ])
1713
+					) {
1714
+						$success = $this->_insert_into_specific_table(
1715
+							$table_obj,
1716
+							$fields_n_values,
1717
+							$main_table_pk_value
1718
+						);
1719
+						// if we died here, report the error
1720
+						if (! $success) {
1721
+							return false;
1722
+						}
1723
+					}
1724
+				}
1725
+			}
1726
+			// let's make sure default_where strategy is followed now
1727
+			$this->_ignore_where_strategy = false;
1728
+		}
1729
+		// if we want to keep model objects in sync, AND
1730
+		// if this wasn't called from a model object (to update itself)
1731
+		// then we want to make sure we keep all the existing
1732
+		// model objects in sync with the db
1733
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1734
+			if ($this->has_primary_key_field()) {
1735
+				$model_objs_affected_ids = $this->get_col($query_params);
1736
+			} else {
1737
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1738
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1739
+				$model_objs_affected_ids     = [];
1740
+				foreach ($models_affected_key_columns as $row) {
1741
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1742
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1743
+				}
1744
+			}
1745
+			if (! $model_objs_affected_ids) {
1746
+				// wait wait wait- if nothing was affected let's stop here
1747
+				return 0;
1748
+			}
1749
+			foreach ($model_objs_affected_ids as $id) {
1750
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1751
+				if ($model_obj_in_entity_map) {
1752
+					foreach ($fields_n_values as $field => $new_value) {
1753
+						$model_obj_in_entity_map->set($field, $new_value);
1754
+					}
1755
+				}
1756
+			}
1757
+			// if there is a primary key on this model, we can now do a slight optimization
1758
+			if ($this->has_primary_key_field()) {
1759
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1760
+				$query_params = [
1761
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1762
+					'limit'                    => count($model_objs_affected_ids),
1763
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1764
+				];
1765
+			}
1766
+		}
1767
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
+		$SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1769
+							. " SET " . $this->_construct_update_sql($fields_n_values)
1770
+							. $model_query_info->get_where_sql();
1771
+		// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1772
+		$rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1773
+		/**
1774
+		 * Action called after a model update call has been made.
1775
+		 *
1776
+		 * @param EEM_Base $model
1777
+		 * @param array    $fields_n_values the updated fields and their new values
1778
+		 * @param array    $query_params
1779
+		 * @param int      $rows_affected
1780
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1781
+		 */
1782
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1783
+		return $rows_affected;// how many supposedly got updated
1784
+	}
1785
+
1786
+
1787
+	/**
1788
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1789
+	 * are teh values of the field specified (or by default the primary key field)
1790
+	 * that matched the query params. Note that you should pass the name of the
1791
+	 * model FIELD, not the database table's column name.
1792
+	 *
1793
+	 * @param array  $query_params
1794
+	 * @param string $field_to_select
1795
+	 * @return array just like $wpdb->get_col()
1796
+	 * @throws EE_Error
1797
+	 * @throws ReflectionException
1798
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1799
+	 */
1800
+	public function get_col($query_params = [], $field_to_select = null)
1801
+	{
1802
+		if ($field_to_select) {
1803
+			$field = $this->field_settings_for($field_to_select);
1804
+		} elseif ($this->has_primary_key_field()) {
1805
+			$field = $this->get_primary_key_field();
1806
+		} else {
1807
+			$field_settings = $this->field_settings();
1808
+			// no primary key, just grab the first column
1809
+			$field = reset($field_settings);
1810
+		}
1811
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1812
+		$select_expressions = $field->get_qualified_column();
1813
+		$SQL                =
1814
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1815
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1816
+	}
1817
+
1818
+
1819
+	/**
1820
+	 * Returns a single column value for a single row from the database
1821
+	 *
1822
+	 * @param array  $query_params
1823
+	 * @param string $field_to_select
1824
+	 * @return string
1825
+	 * @throws EE_Error
1826
+	 * @throws ReflectionException
1827
+	 * @see EEM_Base::get_col()
1828
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1829
+	 */
1830
+	public function get_var($query_params = [], $field_to_select = null)
1831
+	{
1832
+		$query_params['limit'] = 1;
1833
+		$col                   = $this->get_col($query_params, $field_to_select);
1834
+		if (! empty($col)) {
1835
+			return reset($col);
1836
+		}
1837
+		return null;
1838
+	}
1839
+
1840
+
1841
+	/**
1842
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1843
+	 * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1844
+	 * injection, but currently no further filtering is done
1845
+	 *
1846
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1847
+	 *                               be updated to in the DB
1848
+	 * @return string of SQL
1849
+	 * @throws EE_Error
1850
+	 * @global      $wpdb
1851
+	 */
1852
+	public function _construct_update_sql($fields_n_values)
1853
+	{
1854
+		global $wpdb;
1855
+		$cols_n_values = [];
1856
+		foreach ($fields_n_values as $field_name => $value) {
1857
+			$field_obj = $this->field_settings_for($field_name);
1858
+			// if the value is NULL, we want to assign the value to that.
1859
+			// wpdb->prepare doesn't really handle that properly
1860
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1861
+			$value_sql       = $prepared_value === null
1862
+				? 'NULL'
1863
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1864
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1865
+		}
1866
+		return implode(",", $cols_n_values);
1867
+	}
1868
+
1869
+
1870
+	/**
1871
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1872
+	 * Performs a HARD delete, meaning the database row should always be removed,
1873
+	 * not just have a flag field on it switched
1874
+	 * Wrapper for EEM_Base::delete_permanently()
1875
+	 *
1876
+	 * @param mixed   $id
1877
+	 * @param boolean $allow_blocking
1878
+	 * @return int the number of rows deleted
1879
+	 * @throws EE_Error
1880
+	 * @throws ReflectionException
1881
+	 */
1882
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1883
+	{
1884
+		return $this->delete_permanently(
1885
+			[
1886
+				[$this->get_primary_key_field()->get_name() => $id],
1887
+				'limit' => 1,
1888
+			],
1889
+			$allow_blocking
1890
+		);
1891
+	}
1892
+
1893
+
1894
+	/**
1895
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1896
+	 * Wrapper for EEM_Base::delete()
1897
+	 *
1898
+	 * @param mixed   $id
1899
+	 * @param boolean $allow_blocking
1900
+	 * @return int the number of rows deleted
1901
+	 * @throws EE_Error
1902
+	 * @throws ReflectionException
1903
+	 */
1904
+	public function delete_by_ID($id, $allow_blocking = true)
1905
+	{
1906
+		return $this->delete(
1907
+			[
1908
+				[$this->get_primary_key_field()->get_name() => $id],
1909
+				'limit' => 1,
1910
+			],
1911
+			$allow_blocking
1912
+		);
1913
+	}
1914
+
1915
+
1916
+	/**
1917
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1918
+	 * meaning if the model has a field that indicates its been "trashed" or
1919
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1920
+	 *
1921
+	 * @param array   $query_params
1922
+	 * @param boolean $allow_blocking
1923
+	 * @return int how many rows got deleted
1924
+	 * @throws EE_Error
1925
+	 * @throws ReflectionException
1926
+	 * @see EEM_Base::delete_permanently
1927
+	 */
1928
+	public function delete($query_params, $allow_blocking = true)
1929
+	{
1930
+		return $this->delete_permanently($query_params, $allow_blocking);
1931
+	}
1932
+
1933
+
1934
+	/**
1935
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1936
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1937
+	 * as archived, not actually deleted
1938
+	 *
1939
+	 * @param array   $query_params
1940
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1941
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1942
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1943
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1944
+	 *                                DB
1945
+	 * @return int how many rows got deleted
1946
+	 * @throws EE_Error
1947
+	 * @throws ReflectionException
1948
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1949
+	 */
1950
+	public function delete_permanently($query_params, $allow_blocking = true)
1951
+	{
1952
+		/**
1953
+		 * Action called just before performing a real deletion query. You can use the
1954
+		 * model and its $query_params to find exactly which items will be deleted
1955
+		 *
1956
+		 * @param EEM_Base $model
1957
+		 * @param array    $query_params
1958
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1959
+		 *                                 to block (prevent) this deletion
1960
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1961
+		 */
1962
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1963
+		// some MySQL databases may be running safe mode, which may restrict
1964
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1965
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1966
+		// to delete them
1967
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1968
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1969
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1970
+			$columns_and_ids_for_deleting
1971
+		);
1972
+		/**
1973
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1974
+		 *
1975
+		 * @param EEM_Base $this                            The model instance being acted on.
1976
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1977
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1978
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1979
+		 *                                                  derived from the incoming query parameters.
1980
+		 * @see details on the structure of this array in the phpdocs
1981
+		 *                                                  for the `_get_ids_for_delete_method`
1982
+		 *
1983
+		 */
1984
+		do_action(
1985
+			'AHEE__EEM_Base__delete__before_query',
1986
+			$this,
1987
+			$query_params,
1988
+			$allow_blocking,
1989
+			$columns_and_ids_for_deleting
1990
+		);
1991
+		if ($deletion_where_query_part) {
1992
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1993
+			$table_aliases    = implode(', ', array_keys($this->_tables));
1994
+			$SQL              = "DELETE " . $table_aliases
1995
+								. " FROM " . $model_query_info->get_full_join_sql()
1996
+								. " WHERE " . $deletion_where_query_part;
1997
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1998
+		} else {
1999
+			$rows_deleted = 0;
2000
+		}
2001
+
2002
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2003
+		// there was no error with the delete query.
2004
+		if (
2005
+			$this->has_primary_key_field()
2006
+			&& $rows_deleted !== false
2007
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2008
+		) {
2009
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2010
+			foreach ($ids_for_removal as $id) {
2011
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2012
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2013
+				}
2014
+			}
2015
+
2016
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2017
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2018
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2019
+			// (although it is possible).
2020
+			// Note this can be skipped by using the provided filter and returning false.
2021
+			if (
2022
+			apply_filters(
2023
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2024
+				! $this instanceof EEM_Extra_Meta,
2025
+				$this
2026
+			)
2027
+			) {
2028
+				EEM_Extra_Meta::instance()->delete_permanently(
2029
+					[
2030
+						0 => [
2031
+							'EXM_type' => $this->get_this_model_name(),
2032
+							'OBJ_ID'   => [
2033
+								'IN',
2034
+								$ids_for_removal,
2035
+							],
2036
+						],
2037
+					]
2038
+				);
2039
+			}
2040
+		}
2041
+
2042
+		/**
2043
+		 * Action called just after performing a real deletion query. Although at this point the
2044
+		 * items should have been deleted
2045
+		 *
2046
+		 * @param EEM_Base $model
2047
+		 * @param array    $query_params
2048
+		 * @param int      $rows_deleted
2049
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2050
+		 */
2051
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2052
+		return $rows_deleted;// how many supposedly got deleted
2053
+	}
2054
+
2055
+
2056
+	/**
2057
+	 * Checks all the relations that throw error messages when there are blocking related objects
2058
+	 * for related model objects. If there are any related model objects on those relations,
2059
+	 * adds an EE_Error, and return true
2060
+	 *
2061
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2062
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2063
+	 *                                                 should be ignored when determining whether there are related
2064
+	 *                                                 model objects which block this model object's deletion. Useful
2065
+	 *                                                 if you know A is related to B and are considering deleting A,
2066
+	 *                                                 but want to see if A has any other objects blocking its deletion
2067
+	 *                                                 before removing the relation between A and B
2068
+	 * @return boolean
2069
+	 * @throws EE_Error
2070
+	 * @throws ReflectionException
2071
+	 */
2072
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2073
+	{
2074
+		// first, if $ignore_this_model_obj was supplied, get its model
2075
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2076
+			$ignored_model = $ignore_this_model_obj->get_model();
2077
+		} else {
2078
+			$ignored_model = null;
2079
+		}
2080
+		// now check all the relations of $this_model_obj_or_id and see if there
2081
+		// are any related model objects blocking it?
2082
+		$is_blocked = false;
2083
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2084
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2085
+				// if $ignore_this_model_obj was supplied, then for the query
2086
+				// on that model needs to be told to ignore $ignore_this_model_obj
2087
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2088
+					$related_model_objects = $relation_obj->get_all_related(
2089
+						$this_model_obj_or_id,
2090
+						[
2091
+							[
2092
+								$ignored_model->get_primary_key_field()->get_name() => [
2093
+									'!=',
2094
+									$ignore_this_model_obj->ID(),
2095
+								],
2096
+							],
2097
+						]
2098
+					);
2099
+				} else {
2100
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2101
+				}
2102
+				if ($related_model_objects) {
2103
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2104
+					$is_blocked = true;
2105
+				}
2106
+			}
2107
+		}
2108
+		return $is_blocked;
2109
+	}
2110
+
2111
+
2112
+	/**
2113
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2114
+	 *
2115
+	 * @param array $row_results_for_deleting
2116
+	 * @param bool  $allow_blocking
2117
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2118
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2119
+	 *                              dimension array where the key is the fully qualified primary key column and the
2120
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2121
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2122
+	 *                              be a two dimensional array where each element is a group of columns and values that
2123
+	 *                              get deleted. Example: array(
2124
+	 *                              0 => array(
2125
+	 *                              'Term_Relationship.object_id' => 1
2126
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2127
+	 *                              ),
2128
+	 *                              1 => array(
2129
+	 *                              'Term_Relationship.object_id' => 1
2130
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2131
+	 *                              )
2132
+	 *                              )
2133
+	 * @throws EE_Error
2134
+	 * @throws ReflectionException
2135
+	 */
2136
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2137
+	{
2138
+		$ids_to_delete_indexed_by_column = [];
2139
+		if ($this->has_primary_key_field()) {
2140
+			$primary_table                   = $this->_get_main_table();
2141
+			$ids_to_delete_indexed_by_column = $query = [];
2142
+			foreach ($row_results_for_deleting as $item_to_delete) {
2143
+				// before we mark this item for deletion,
2144
+				// make sure there's no related entities blocking its deletion (if we're checking)
2145
+				if (
2146
+					$allow_blocking
2147
+					&& $this->delete_is_blocked_by_related_models(
2148
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2149
+					)
2150
+				) {
2151
+					continue;
2152
+				}
2153
+				// primary table deletes
2154
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2155
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2156
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2157
+				}
2158
+			}
2159
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2160
+			$fields = $this->get_combined_primary_key_fields();
2161
+			foreach ($row_results_for_deleting as $item_to_delete) {
2162
+				$ids_to_delete_indexed_by_column_for_row = [];
2163
+				foreach ($fields as $cpk_field) {
2164
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2165
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2166
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2167
+					}
2168
+				}
2169
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2170
+			}
2171
+		} else {
2172
+			// so there's no primary key and no combined key...
2173
+			// sorry, can't help you
2174
+			throw new EE_Error(
2175
+				sprintf(
2176
+					esc_html__(
2177
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2178
+						"event_espresso"
2179
+					),
2180
+					get_class($this)
2181
+				)
2182
+			);
2183
+		}
2184
+		return $ids_to_delete_indexed_by_column;
2185
+	}
2186
+
2187
+
2188
+	/**
2189
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2190
+	 * the corresponding query_part for the query performing the delete.
2191
+	 *
2192
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2193
+	 * @return string
2194
+	 * @throws EE_Error
2195
+	 */
2196
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2197
+	{
2198
+		$query_part = '';
2199
+		if (empty($ids_to_delete_indexed_by_column)) {
2200
+			return $query_part;
2201
+		} elseif ($this->has_primary_key_field()) {
2202
+			$query = [];
2203
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2204
+				// make sure we have unique $ids
2205
+				$ids     = array_unique($ids);
2206
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2207
+			}
2208
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2209
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2210
+			$ways_to_identify_a_row = [];
2211
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2212
+				$values_for_each_combined_primary_key_for_a_row = [];
2213
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2214
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2215
+				}
2216
+				$value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2217
+				$ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2218
+			}
2219
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2220
+		}
2221
+		return $query_part;
2222
+	}
2223
+
2224
+
2225
+	/**
2226
+	 * Gets the model field by the fully qualified name
2227
+	 *
2228
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2229
+	 * @return EE_Model_Field_Base
2230
+	 * @throws EE_Error
2231
+	 */
2232
+	public function get_field_by_column($qualified_column_name)
2233
+	{
2234
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2235
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2236
+				return $field_obj;
2237
+			}
2238
+		}
2239
+		throw new EE_Error(
2240
+			sprintf(
2241
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2242
+				$this->get_this_model_name(),
2243
+				$qualified_column_name
2244
+			)
2245
+		);
2246
+	}
2247
+
2248
+
2249
+	/**
2250
+	 * Count all the rows that match criteria the model query params.
2251
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2252
+	 * column
2253
+	 *
2254
+	 * @param array  $query_params
2255
+	 * @param string $field_to_count field on model to count by (not column name)
2256
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2257
+	 *                               that by the setting $distinct to TRUE;
2258
+	 * @return int
2259
+	 * @throws EE_Error
2260
+	 * @throws ReflectionException
2261
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2262
+	 */
2263
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2264
+	{
2265
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2266
+		if ($field_to_count) {
2267
+			$field_obj       = $this->field_settings_for($field_to_count);
2268
+			$column_to_count = $field_obj->get_qualified_column();
2269
+		} elseif ($this->has_primary_key_field()) {
2270
+			$pk_field_obj    = $this->get_primary_key_field();
2271
+			$column_to_count = $pk_field_obj->get_qualified_column();
2272
+		} else {
2273
+			// there's no primary key
2274
+			// if we're counting distinct items, and there's no primary key,
2275
+			// we need to list out the columns for distinction;
2276
+			// otherwise we can just use star
2277
+			if ($distinct) {
2278
+				$columns_to_use = [];
2279
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2280
+					$columns_to_use[] = $field_obj->get_qualified_column();
2281
+				}
2282
+				$column_to_count = implode(',', $columns_to_use);
2283
+			} else {
2284
+				$column_to_count = '*';
2285
+			}
2286
+		}
2287
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2288
+		$SQL             =
2289
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2291
+	}
2292
+
2293
+
2294
+	/**
2295
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2296
+	 *
2297
+	 * @param array  $query_params
2298
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2299
+	 * @return float
2300
+	 * @throws EE_Error
2301
+	 * @throws ReflectionException
2302
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2303
+	 */
2304
+	public function sum($query_params, $field_to_sum = null)
2305
+	{
2306
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2307
+		if ($field_to_sum) {
2308
+			$field_obj = $this->field_settings_for($field_to_sum);
2309
+		} else {
2310
+			$field_obj = $this->get_primary_key_field();
2311
+		}
2312
+		$column_to_count = $field_obj->get_qualified_column();
2313
+		$SQL             = "SELECT SUM(" . $column_to_count . ")"
2314
+						   . $this->_construct_2nd_half_of_select_query($model_query_info);
2315
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2316
+		$data_type       = $field_obj->get_wpdb_data_type();
2317
+		if ($data_type === '%d' || $data_type === '%s') {
2318
+			return (float) $return_value;
2319
+		}
2320
+		// must be %f
2321
+		return (float) $return_value;
2322
+	}
2323
+
2324
+
2325
+	/**
2326
+	 * Just calls the specified method on $wpdb with the given arguments
2327
+	 * Consolidates a little extra error handling code
2328
+	 *
2329
+	 * @param string $wpdb_method
2330
+	 * @param array  $arguments_to_provide
2331
+	 * @return mixed
2332
+	 * @throws EE_Error
2333
+	 * @global wpdb  $wpdb
2334
+	 */
2335
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2336
+	{
2337
+		// if we're in maintenance mode level 2, DON'T run any queries
2338
+		// because level 2 indicates the database needs updating and
2339
+		// is probably out of sync with the code
2340
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2341
+			throw new EE_Error(
2342
+				sprintf(
2343
+					esc_html__(
2344
+						"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.",
2345
+						"event_espresso"
2346
+					)
2347
+				)
2348
+			);
2349
+		}
2350
+		global $wpdb;
2351
+		if (! method_exists($wpdb, $wpdb_method)) {
2352
+			throw new EE_Error(
2353
+				sprintf(
2354
+					esc_html__(
2355
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2356
+						'event_espresso'
2357
+					),
2358
+					$wpdb_method
2359
+				)
2360
+			);
2361
+		}
2362
+		$old_show_errors_value = $wpdb->show_errors;
2363
+		if (WP_DEBUG) {
2364
+			$wpdb->show_errors(false);
2365
+		}
2366
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2367
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2368
+		if (WP_DEBUG) {
2369
+			$wpdb->show_errors($old_show_errors_value);
2370
+			if (! empty($wpdb->last_error)) {
2371
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2372
+			}
2373
+			if ($result === false) {
2374
+				throw new EE_Error(
2375
+					sprintf(
2376
+						esc_html__(
2377
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2378
+							'event_espresso'
2379
+						),
2380
+						$wpdb_method,
2381
+						var_export($arguments_to_provide, true)
2382
+					)
2383
+				);
2384
+			}
2385
+		} elseif ($result === false) {
2386
+			EE_Error::add_error(
2387
+				sprintf(
2388
+					esc_html__(
2389
+						'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"',
2390
+						'event_espresso'
2391
+					),
2392
+					$wpdb_method,
2393
+					var_export($arguments_to_provide, true),
2394
+					$wpdb->last_error
2395
+				),
2396
+				__FILE__,
2397
+				__FUNCTION__,
2398
+				__LINE__
2399
+			);
2400
+		}
2401
+		return $result;
2402
+	}
2403
+
2404
+
2405
+	/**
2406
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2407
+	 * and if there's an error tries to verify the DB is correct. Uses
2408
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2409
+	 * we should try to fix the EE core db, the addons, or just give up
2410
+	 *
2411
+	 * @param string $wpdb_method
2412
+	 * @param array  $arguments_to_provide
2413
+	 * @return mixed
2414
+	 * @throws EE_Error
2415
+	 */
2416
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2417
+	{
2418
+		global $wpdb;
2419
+		$wpdb->last_error = null;
2420
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2421
+		// was there an error running the query? but we don't care on new activations
2422
+		// (we're going to setup the DB anyway on new activations)
2423
+		if (
2424
+			($result === false || ! empty($wpdb->last_error))
2425
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2426
+		) {
2427
+			switch (EEM_Base::$_db_verification_level) {
2428
+				case EEM_Base::db_verified_none:
2429
+					// let's double-check core's DB
2430
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2431
+					break;
2432
+				case EEM_Base::db_verified_core:
2433
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2434
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2435
+					break;
2436
+				case EEM_Base::db_verified_addons:
2437
+					// ummmm... you in trouble
2438
+					return $result;
2439
+			}
2440
+			if (! empty($error_message)) {
2441
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2442
+				trigger_error($error_message);
2443
+			}
2444
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2445
+		}
2446
+		return $result;
2447
+	}
2448
+
2449
+
2450
+	/**
2451
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2452
+	 * EEM_Base::$_db_verification_level
2453
+	 *
2454
+	 * @param string $wpdb_method
2455
+	 * @param array  $arguments_to_provide
2456
+	 * @return string
2457
+	 * @throws EE_Error
2458
+	 */
2459
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2460
+	{
2461
+		global $wpdb;
2462
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2463
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2464
+		$error_message                    = sprintf(
2465
+			esc_html__(
2466
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2467
+				'event_espresso'
2468
+			),
2469
+			$wpdb->last_error,
2470
+			$wpdb_method,
2471
+			wp_json_encode($arguments_to_provide)
2472
+		);
2473
+		EE_System::instance()->initialize_db_if_no_migrations_required();
2474
+		return $error_message;
2475
+	}
2476
+
2477
+
2478
+	/**
2479
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2480
+	 * EEM_Base::$_db_verification_level
2481
+	 *
2482
+	 * @param $wpdb_method
2483
+	 * @param $arguments_to_provide
2484
+	 * @return string
2485
+	 * @throws EE_Error
2486
+	 */
2487
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2488
+	{
2489
+		global $wpdb;
2490
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2491
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2492
+		$error_message                    = sprintf(
2493
+			esc_html__(
2494
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2495
+				'event_espresso'
2496
+			),
2497
+			$wpdb->last_error,
2498
+			$wpdb_method,
2499
+			wp_json_encode($arguments_to_provide)
2500
+		);
2501
+		EE_System::instance()->initialize_addons();
2502
+		return $error_message;
2503
+	}
2504
+
2505
+
2506
+	/**
2507
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2508
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2509
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2510
+	 * ..."
2511
+	 *
2512
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2513
+	 * @return string
2514
+	 */
2515
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2516
+	{
2517
+		return " FROM " . $model_query_info->get_full_join_sql() .
2518
+			   $model_query_info->get_where_sql() .
2519
+			   $model_query_info->get_group_by_sql() .
2520
+			   $model_query_info->get_having_sql() .
2521
+			   $model_query_info->get_order_by_sql() .
2522
+			   $model_query_info->get_limit_sql();
2523
+	}
2524
+
2525
+
2526
+	/**
2527
+	 * Set to easily debug the next X queries ran from this model.
2528
+	 *
2529
+	 * @param int $count
2530
+	 */
2531
+	public function show_next_x_db_queries($count = 1)
2532
+	{
2533
+		$this->_show_next_x_db_queries = $count;
2534
+	}
2535
+
2536
+
2537
+	/**
2538
+	 * @param $sql_query
2539
+	 */
2540
+	public function show_db_query_if_previously_requested($sql_query)
2541
+	{
2542
+		if ($this->_show_next_x_db_queries > 0) {
2543
+			echo $sql_query;
2544
+			$this->_show_next_x_db_queries--;
2545
+		}
2546
+	}
2547
+
2548
+
2549
+	/**
2550
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2551
+	 * There are the 3 cases:
2552
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2553
+	 * $otherModelObject has no ID, it is first saved.
2554
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2555
+	 * has no ID, it is first saved.
2556
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2557
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2558
+	 * join table
2559
+	 *
2560
+	 * @param EE_Base_Class                     /int $thisModelObject
2561
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2562
+	 * @param string $relationName                     , key in EEM_Base::_relations
2563
+	 *                                                 an attendee to a group, you also want to specify which role they
2564
+	 *                                                 will have in that group. So you would use this parameter to
2565
+	 *                                                 specify array('role-column-name'=>'role-id')
2566
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2567
+	 *                                                 to for relation to methods that allow you to further specify
2568
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2569
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2570
+	 *                                                 because these will be inserted in any new rows created as well.
2571
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2572
+	 * @throws EE_Error
2573
+	 */
2574
+	public function add_relationship_to(
2575
+		$id_or_obj,
2576
+		$other_model_id_or_obj,
2577
+		$relationName,
2578
+		$extra_join_model_fields_n_values = []
2579
+	) {
2580
+		$relation_obj = $this->related_settings_for($relationName);
2581
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2582
+	}
2583
+
2584
+
2585
+	/**
2586
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2587
+	 * There are the 3 cases:
2588
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2589
+	 * error
2590
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2591
+	 * an error
2592
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2593
+	 *
2594
+	 * @param EE_Base_Class /int $id_or_obj
2595
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2596
+	 * @param string $relationName key in EEM_Base::_relations
2597
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2598
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2599
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2600
+	 *                             because these will be inserted in any new rows created as well.
2601
+	 * @return boolean of success
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2605
+	{
2606
+		$relation_obj = $this->related_settings_for($relationName);
2607
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2608
+	}
2609
+
2610
+
2611
+	/**
2612
+	 * @param mixed  $id_or_obj
2613
+	 * @param string $relationName
2614
+	 * @param array  $where_query_params
2615
+	 * @param EE_Base_Class[] objects to which relations were removed
2616
+	 * @return EE_Base_Class[]
2617
+	 * @throws EE_Error
2618
+	 */
2619
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2620
+	{
2621
+		$relation_obj = $this->related_settings_for($relationName);
2622
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * Gets all the related items of the specified $model_name, using $query_params.
2628
+	 * Note: by default, we remove the "default query params"
2629
+	 * because we want to get even deleted items etc.
2630
+	 *
2631
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2632
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2633
+	 * @param array  $query_params see github link below for more info
2634
+	 * @return EE_Base_Class[]
2635
+	 * @throws EE_Error
2636
+	 * @throws ReflectionException
2637
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
+	 */
2639
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2640
+	{
2641
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2642
+		$relation_settings = $this->related_settings_for($model_name);
2643
+		return $relation_settings->get_all_related($model_obj, $query_params);
2644
+	}
2645
+
2646
+
2647
+	/**
2648
+	 * Deletes all the model objects across the relation indicated by $model_name
2649
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2650
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2651
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2652
+	 *
2653
+	 * @param EE_Base_Class|int|string $id_or_obj
2654
+	 * @param string                   $model_name
2655
+	 * @param array                    $query_params
2656
+	 * @return int how many deleted
2657
+	 * @throws EE_Error
2658
+	 * @throws ReflectionException
2659
+	 */
2660
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2661
+	{
2662
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2663
+		$relation_settings = $this->related_settings_for($model_name);
2664
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2665
+	}
2666
+
2667
+
2668
+	/**
2669
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2670
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2671
+	 * the model objects can't be hard deleted because of blocking related model objects,
2672
+	 * just does a soft-delete on them instead.
2673
+	 *
2674
+	 * @param EE_Base_Class|int|string $id_or_obj
2675
+	 * @param string                   $model_name
2676
+	 * @param array                    $query_params
2677
+	 * @return int how many deleted
2678
+	 * @throws EE_Error
2679
+	 * @throws ReflectionException
2680
+	 */
2681
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2682
+	{
2683
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2684
+		$relation_settings = $this->related_settings_for($model_name);
2685
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2686
+	}
2687
+
2688
+
2689
+	/**
2690
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2691
+	 * unless otherwise specified in the $query_params
2692
+	 *
2693
+	 * @param int             /EE_Base_Class $id_or_obj
2694
+	 * @param string $model_name     like 'Event', or 'Registration'
2695
+	 * @param array  $query_params
2696
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2697
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2698
+	 *                               that by the setting $distinct to TRUE;
2699
+	 * @return int
2700
+	 * @throws EE_Error
2701
+	 * @throws ReflectionException
2702
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2703
+	 */
2704
+	public function count_related(
2705
+		$id_or_obj,
2706
+		$model_name,
2707
+		$query_params = [],
2708
+		$field_to_count = null,
2709
+		$distinct = false
2710
+	) {
2711
+		$related_model = $this->get_related_model_obj($model_name);
2712
+		// we're just going to use the query params on the related model's normal get_all query,
2713
+		// except add a condition to say to match the current mod
2714
+		if (! isset($query_params['default_where_conditions'])) {
2715
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2716
+		}
2717
+		$this_model_name                                                 = $this->get_this_model_name();
2718
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2719
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2720
+		return $related_model->count($query_params, $field_to_count, $distinct);
2721
+	}
2722
+
2723
+
2724
+	/**
2725
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2726
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2727
+	 *
2728
+	 * @param int           /EE_Base_Class $id_or_obj
2729
+	 * @param string $model_name   like 'Event', or 'Registration'
2730
+	 * @param array  $query_params
2731
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2732
+	 * @return float
2733
+	 * @throws EE_Error
2734
+	 * @throws ReflectionException
2735
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
+	 */
2737
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2738
+	{
2739
+		$related_model = $this->get_related_model_obj($model_name);
2740
+		if (! is_array($query_params)) {
2741
+			EE_Error::doing_it_wrong(
2742
+				'EEM_Base::sum_related',
2743
+				sprintf(
2744
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2745
+					gettype($query_params)
2746
+				),
2747
+				'4.6.0'
2748
+			);
2749
+			$query_params = [];
2750
+		}
2751
+		// we're just going to use the query params on the related model's normal get_all query,
2752
+		// except add a condition to say to match the current mod
2753
+		if (! isset($query_params['default_where_conditions'])) {
2754
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2755
+		}
2756
+		$this_model_name                                                 = $this->get_this_model_name();
2757
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2758
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2759
+		return $related_model->sum($query_params, $field_to_sum);
2760
+	}
2761
+
2762
+
2763
+	/**
2764
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2765
+	 * $modelObject
2766
+	 *
2767
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2768
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2769
+	 * @param array               $query_params     see github link below for more info
2770
+	 * @return EE_Base_Class
2771
+	 * @throws EE_Error
2772
+	 * @throws ReflectionException
2773
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2774
+	 */
2775
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2776
+	{
2777
+		$query_params['limit'] = 1;
2778
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2779
+		if ($results) {
2780
+			return array_shift($results);
2781
+		}
2782
+		return null;
2783
+	}
2784
+
2785
+
2786
+	/**
2787
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2788
+	 *
2789
+	 * @return string
2790
+	 */
2791
+	public function get_this_model_name()
2792
+	{
2793
+		return str_replace("EEM_", "", get_class($this));
2794
+	}
2795
+
2796
+
2797
+	/**
2798
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2799
+	 *
2800
+	 * @return EE_Any_Foreign_Model_Name_Field
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	public function get_field_containing_related_model_name()
2804
+	{
2805
+		foreach ($this->field_settings(true) as $field) {
2806
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2807
+				$field_with_model_name = $field;
2808
+			}
2809
+		}
2810
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2811
+			throw new EE_Error(
2812
+				sprintf(
2813
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2814
+					$this->get_this_model_name()
2815
+				)
2816
+			);
2817
+		}
2818
+		return $field_with_model_name;
2819
+	}
2820
+
2821
+
2822
+	/**
2823
+	 * Inserts a new entry into the database, for each table.
2824
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2825
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2826
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2827
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2828
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2829
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2830
+	 *
2831
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2832
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2833
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2834
+	 *                              of EEM_Base)
2835
+	 * @return int|string new primary key on main table that got inserted
2836
+	 * @throws EE_Error
2837
+	 * @throws ReflectionException
2838
+	 */
2839
+	public function insert($field_n_values)
2840
+	{
2841
+		/**
2842
+		 * Filters the fields and their values before inserting an item using the models
2843
+		 *
2844
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2845
+		 * @param EEM_Base $model           the model used
2846
+		 */
2847
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2848
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2849
+			$main_table = $this->_get_main_table();
2850
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2851
+			if ($new_id !== false) {
2852
+				foreach ($this->_get_other_tables() as $other_table) {
2853
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2854
+				}
2855
+			}
2856
+			/**
2857
+			 * Done just after attempting to insert a new model object
2858
+			 *
2859
+			 * @param EEM_Base $model           used
2860
+			 * @param array    $fields_n_values fields and their values
2861
+			 * @param int|string the              ID of the newly-inserted model object
2862
+			 */
2863
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2864
+			return $new_id;
2865
+		}
2866
+		return false;
2867
+	}
2868
+
2869
+
2870
+	/**
2871
+	 * Checks that the result would satisfy the unique indexes on this model
2872
+	 *
2873
+	 * @param array  $field_n_values
2874
+	 * @param string $action
2875
+	 * @return boolean
2876
+	 * @throws EE_Error
2877
+	 * @throws ReflectionException
2878
+	 */
2879
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2880
+	{
2881
+		foreach ($this->unique_indexes() as $index_name => $index) {
2882
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2883
+			if ($this->exists([$uniqueness_where_params])) {
2884
+				EE_Error::add_error(
2885
+					sprintf(
2886
+						esc_html__(
2887
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2888
+							"event_espresso"
2889
+						),
2890
+						$action,
2891
+						$this->_get_class_name(),
2892
+						$index_name,
2893
+						implode(",", $index->field_names()),
2894
+						http_build_query($uniqueness_where_params)
2895
+					),
2896
+					__FILE__,
2897
+					__FUNCTION__,
2898
+					__LINE__
2899
+				);
2900
+				return false;
2901
+			}
2902
+		}
2903
+		return true;
2904
+	}
2905
+
2906
+
2907
+	/**
2908
+	 * Checks the database for an item that conflicts (ie, if this item were
2909
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2910
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2911
+	 * can be either an EE_Base_Class or an array of fields n values
2912
+	 *
2913
+	 * @param EE_Base_Class|array $obj_or_fields_array
2914
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2915
+	 *                                                 when looking for conflicts
2916
+	 *                                                 (ie, if false, we ignore the model object's primary key
2917
+	 *                                                 when finding "conflicts". If true, it's also considered).
2918
+	 *                                                 Only works for INT primary key,
2919
+	 *                                                 STRING primary keys cannot be ignored
2920
+	 * @return EE_Base_Class|array
2921
+	 * @throws EE_Error
2922
+	 * @throws ReflectionException
2923
+	 */
2924
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2925
+	{
2926
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2927
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2928
+		} elseif (is_array($obj_or_fields_array)) {
2929
+			$fields_n_values = $obj_or_fields_array;
2930
+		} else {
2931
+			throw new EE_Error(
2932
+				sprintf(
2933
+					esc_html__(
2934
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2935
+						"event_espresso"
2936
+					),
2937
+					get_class($this),
2938
+					$obj_or_fields_array
2939
+				)
2940
+			);
2941
+		}
2942
+		$query_params = [];
2943
+		if (
2944
+			$this->has_primary_key_field()
2945
+			&& ($include_primary_key
2946
+				|| $this->get_primary_key_field()
2947
+				   instanceof
2948
+				   EE_Primary_Key_String_Field)
2949
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2950
+		) {
2951
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2952
+		}
2953
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2954
+			$uniqueness_where_params                              =
2955
+				array_intersect_key($fields_n_values, $unique_index->fields());
2956
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2957
+		}
2958
+		// if there is nothing to base this search on, then we shouldn't find anything
2959
+		if (empty($query_params)) {
2960
+			return [];
2961
+		}
2962
+		return $this->get_one($query_params);
2963
+	}
2964
+
2965
+
2966
+	/**
2967
+	 * Like count, but is optimized and returns a boolean instead of an int
2968
+	 *
2969
+	 * @param array $query_params
2970
+	 * @return boolean
2971
+	 * @throws EE_Error
2972
+	 * @throws ReflectionException
2973
+	 */
2974
+	public function exists($query_params)
2975
+	{
2976
+		$query_params['limit'] = 1;
2977
+		return $this->count($query_params) > 0;
2978
+	}
2979
+
2980
+
2981
+	/**
2982
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2983
+	 *
2984
+	 * @param int|string $id
2985
+	 * @return boolean
2986
+	 * @throws EE_Error
2987
+	 * @throws ReflectionException
2988
+	 */
2989
+	public function exists_by_ID($id)
2990
+	{
2991
+		return $this->exists(
2992
+			[
2993
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2994
+				[
2995
+					$this->primary_key_name() => $id,
2996
+				],
2997
+			]
2998
+		);
2999
+	}
3000
+
3001
+
3002
+	/**
3003
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3004
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3005
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3006
+	 * on the main table)
3007
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3008
+	 * cases where we want to call it directly rather than via insert().
3009
+	 *
3010
+	 * @access   protected
3011
+	 * @param EE_Table_Base $table
3012
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3013
+	 *                                       float
3014
+	 * @param int           $new_id          for now we assume only int keys
3015
+	 * @return int ID of new row inserted, or FALSE on failure
3016
+	 * @throws EE_Error
3017
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3018
+	 */
3019
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3020
+	{
3021
+		global $wpdb;
3022
+		$insertion_col_n_values = [];
3023
+		$format_for_insertion   = [];
3024
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3025
+		foreach ($fields_on_table as $field_name => $field_obj) {
3026
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3027
+			if ($field_obj->is_auto_increment()) {
3028
+				continue;
3029
+			}
3030
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3031
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3032
+			if ($prepared_value !== null) {
3033
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3034
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3035
+			}
3036
+		}
3037
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3038
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3039
+			// so add the fk to the main table as a column
3040
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3041
+			$format_for_insertion[]                              =
3042
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3043
+		}
3044
+		// insert the new entry
3045
+		$result = $this->_do_wpdb_query(
3046
+			'insert',
3047
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3048
+		);
3049
+		if ($result === false) {
3050
+			return false;
3051
+		}
3052
+		// ok, now what do we return for the ID of the newly-inserted thing?
3053
+		if ($this->has_primary_key_field()) {
3054
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3055
+				return $wpdb->insert_id;
3056
+			}
3057
+			// it's not an auto-increment primary key, so
3058
+			// it must have been supplied
3059
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3060
+		}
3061
+		// we can't return a  primary key because there is none. instead return
3062
+		// a unique string indicating this model
3063
+		return $this->get_index_primary_key_string($fields_n_values);
3064
+	}
3065
+
3066
+
3067
+	/**
3068
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3069
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3070
+	 * and there is no default, we pass it along. WPDB will take care of it)
3071
+	 *
3072
+	 * @param EE_Model_Field_Base $field_obj
3073
+	 * @param array               $fields_n_values
3074
+	 * @return mixed string|int|float depending on what the table column will be expecting
3075
+	 * @throws EE_Error
3076
+	 */
3077
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3078
+	{
3079
+		// if this field doesn't allow nullable, don't allow it
3080
+		if (
3081
+			! $field_obj->is_nullable()
3082
+			&& (
3083
+				! isset($fields_n_values[ $field_obj->get_name() ])
3084
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3085
+			)
3086
+		) {
3087
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3088
+		}
3089
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3090
+			? $fields_n_values[ $field_obj->get_name() ]
3091
+			: null;
3092
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3098
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3099
+	 * the field's prepare_for_set() method.
3100
+	 *
3101
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3102
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3103
+	 *                                   top of file)
3104
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3105
+	 *                                   $value is a custom selection
3106
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3107
+	 */
3108
+	private function _prepare_value_for_use_in_db($value, $field)
3109
+	{
3110
+		if ($field && $field instanceof EE_Model_Field_Base) {
3111
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3112
+			switch ($this->_values_already_prepared_by_model_object) {
3113
+				/** @noinspection PhpMissingBreakStatementInspection */
3114
+				case self::not_prepared_by_model_object:
3115
+					$value = $field->prepare_for_set($value);
3116
+				// purposefully left out "return"
3117
+				case self::prepared_by_model_object:
3118
+					/** @noinspection SuspiciousAssignmentsInspection */
3119
+					$value = $field->prepare_for_use_in_db($value);
3120
+				case self::prepared_for_use_in_db:
3121
+					// leave the value alone
3122
+			}
3123
+			return $value;
3124
+			// phpcs:enable
3125
+		}
3126
+		return $value;
3127
+	}
3128
+
3129
+
3130
+	/**
3131
+	 * Returns the main table on this model
3132
+	 *
3133
+	 * @return EE_Primary_Table
3134
+	 * @throws EE_Error
3135
+	 */
3136
+	protected function _get_main_table()
3137
+	{
3138
+		foreach ($this->_tables as $table) {
3139
+			if ($table instanceof EE_Primary_Table) {
3140
+				return $table;
3141
+			}
3142
+		}
3143
+		throw new EE_Error(
3144
+			sprintf(
3145
+				esc_html__(
3146
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3147
+					'event_espresso'
3148
+				),
3149
+				get_class($this)
3150
+			)
3151
+		);
3152
+	}
3153
+
3154
+
3155
+	/**
3156
+	 * table
3157
+	 * returns EE_Primary_Table table name
3158
+	 *
3159
+	 * @return string
3160
+	 * @throws EE_Error
3161
+	 */
3162
+	public function table()
3163
+	{
3164
+		return $this->_get_main_table()->get_table_name();
3165
+	}
3166
+
3167
+
3168
+	/**
3169
+	 * table
3170
+	 * returns first EE_Secondary_Table table name
3171
+	 *
3172
+	 * @return string
3173
+	 */
3174
+	public function second_table()
3175
+	{
3176
+		// grab second table from tables array
3177
+		$second_table = end($this->_tables);
3178
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3179
+	}
3180
+
3181
+
3182
+	/**
3183
+	 * get_table_obj_by_alias
3184
+	 * returns table name given it's alias
3185
+	 *
3186
+	 * @param string $table_alias
3187
+	 * @return EE_Primary_Table | EE_Secondary_Table
3188
+	 */
3189
+	public function get_table_obj_by_alias($table_alias = '')
3190
+	{
3191
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3192
+	}
3193
+
3194
+
3195
+	/**
3196
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3197
+	 *
3198
+	 * @return EE_Secondary_Table[]
3199
+	 */
3200
+	protected function _get_other_tables()
3201
+	{
3202
+		$other_tables = [];
3203
+		foreach ($this->_tables as $table_alias => $table) {
3204
+			if ($table instanceof EE_Secondary_Table) {
3205
+				$other_tables[ $table_alias ] = $table;
3206
+			}
3207
+		}
3208
+		return $other_tables;
3209
+	}
3210
+
3211
+
3212
+	/**
3213
+	 * Finds all the fields that correspond to the given table
3214
+	 *
3215
+	 * @param string $table_alias , array key in EEM_Base::_tables
3216
+	 * @return EE_Model_Field_Base[]
3217
+	 */
3218
+	public function _get_fields_for_table($table_alias)
3219
+	{
3220
+		return $this->_fields[ $table_alias ];
3221
+	}
3222
+
3223
+
3224
+	/**
3225
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3226
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3227
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3228
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3229
+	 * related Registration, Transaction, and Payment models.
3230
+	 *
3231
+	 * @param array $query_params see github link below for more info
3232
+	 * @return EE_Model_Query_Info_Carrier
3233
+	 * @throws EE_Error
3234
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3235
+	 */
3236
+	public function _extract_related_models_from_query($query_params)
3237
+	{
3238
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3239
+		if (array_key_exists(0, $query_params)) {
3240
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3241
+		}
3242
+		if (array_key_exists('group_by', $query_params)) {
3243
+			if (is_array($query_params['group_by'])) {
3244
+				$this->_extract_related_models_from_sub_params_array_values(
3245
+					$query_params['group_by'],
3246
+					$query_info_carrier,
3247
+					'group_by'
3248
+				);
3249
+			} elseif (! empty($query_params['group_by'])) {
3250
+				$this->_extract_related_model_info_from_query_param(
3251
+					$query_params['group_by'],
3252
+					$query_info_carrier,
3253
+					'group_by'
3254
+				);
3255
+			}
3256
+		}
3257
+		if (array_key_exists('having', $query_params)) {
3258
+			$this->_extract_related_models_from_sub_params_array_keys(
3259
+				$query_params[0],
3260
+				$query_info_carrier,
3261
+				'having'
3262
+			);
3263
+		}
3264
+		if (array_key_exists('order_by', $query_params)) {
3265
+			if (is_array($query_params['order_by'])) {
3266
+				$this->_extract_related_models_from_sub_params_array_keys(
3267
+					$query_params['order_by'],
3268
+					$query_info_carrier,
3269
+					'order_by'
3270
+				);
3271
+			} elseif (! empty($query_params['order_by'])) {
3272
+				$this->_extract_related_model_info_from_query_param(
3273
+					$query_params['order_by'],
3274
+					$query_info_carrier,
3275
+					'order_by'
3276
+				);
3277
+			}
3278
+		}
3279
+		if (array_key_exists('force_join', $query_params)) {
3280
+			$this->_extract_related_models_from_sub_params_array_values(
3281
+				$query_params['force_join'],
3282
+				$query_info_carrier,
3283
+				'force_join'
3284
+			);
3285
+		}
3286
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3287
+		return $query_info_carrier;
3288
+	}
3289
+
3290
+
3291
+	/**
3292
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3293
+	 *
3294
+	 * @param array                       $sub_query_params
3295
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3296
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3297
+	 * @return EE_Model_Query_Info_Carrier
3298
+	 * @throws EE_Error
3299
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3300
+	 */
3301
+	private function _extract_related_models_from_sub_params_array_keys(
3302
+		$sub_query_params,
3303
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3304
+		$query_param_type
3305
+	) {
3306
+		if (! empty($sub_query_params)) {
3307
+			$sub_query_params = (array) $sub_query_params;
3308
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3309
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3310
+				$this->_extract_related_model_info_from_query_param(
3311
+					$param,
3312
+					$model_query_info_carrier,
3313
+					$query_param_type
3314
+				);
3315
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3316
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3317
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3318
+				// of array('Registration.TXN_ID'=>23)
3319
+				$query_param_sans_stars =
3320
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3321
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3322
+					if (! is_array($possibly_array_of_params)) {
3323
+						throw new EE_Error(
3324
+							sprintf(
3325
+								esc_html__(
3326
+									"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'))",
3327
+									"event_espresso"
3328
+								),
3329
+								$param,
3330
+								$possibly_array_of_params
3331
+							)
3332
+						);
3333
+					}
3334
+					$this->_extract_related_models_from_sub_params_array_keys(
3335
+						$possibly_array_of_params,
3336
+						$model_query_info_carrier,
3337
+						$query_param_type
3338
+					);
3339
+				} elseif (
3340
+					$query_param_type === 0 // ie WHERE
3341
+					&& is_array($possibly_array_of_params)
3342
+					&& isset($possibly_array_of_params[2])
3343
+					&& $possibly_array_of_params[2] == true
3344
+				) {
3345
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3346
+					// indicating that $possible_array_of_params[1] is actually a field name,
3347
+					// from which we should extract query parameters!
3348
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3349
+						throw new EE_Error(
3350
+							sprintf(
3351
+								esc_html__(
3352
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3353
+									"event_espresso"
3354
+								),
3355
+								$query_param_type,
3356
+								implode(",", $possibly_array_of_params)
3357
+							)
3358
+						);
3359
+					}
3360
+					$this->_extract_related_model_info_from_query_param(
3361
+						$possibly_array_of_params[1],
3362
+						$model_query_info_carrier,
3363
+						$query_param_type
3364
+					);
3365
+				}
3366
+			}
3367
+		}
3368
+		return $model_query_info_carrier;
3369
+	}
3370
+
3371
+
3372
+	/**
3373
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3374
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3375
+	 *
3376
+	 * @param array                       $sub_query_params
3377
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3378
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3379
+	 * @return EE_Model_Query_Info_Carrier
3380
+	 * @throws EE_Error
3381
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3382
+	 */
3383
+	private function _extract_related_models_from_sub_params_array_values(
3384
+		$sub_query_params,
3385
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3386
+		$query_param_type
3387
+	) {
3388
+		if (! empty($sub_query_params)) {
3389
+			if (! is_array($sub_query_params)) {
3390
+				throw new EE_Error(
3391
+					sprintf(
3392
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3393
+						$sub_query_params
3394
+					)
3395
+				);
3396
+			}
3397
+			foreach ($sub_query_params as $param) {
3398
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3399
+				$this->_extract_related_model_info_from_query_param(
3400
+					$param,
3401
+					$model_query_info_carrier,
3402
+					$query_param_type
3403
+				);
3404
+			}
3405
+		}
3406
+		return $model_query_info_carrier;
3407
+	}
3408
+
3409
+
3410
+	/**
3411
+	 * Extract all the query parts from  model query params
3412
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3413
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3414
+	 * but use them in a different order. Eg, we need to know what models we are querying
3415
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3416
+	 * other models before we can finalize the where clause SQL.
3417
+	 *
3418
+	 * @param array $query_params see github link below for more info
3419
+	 * @return EE_Model_Query_Info_Carrier
3420
+	 * @throws EE_Error
3421
+	 * @throws ModelConfigurationException
3422
+	 * @throws ReflectionException
3423
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3424
+	 */
3425
+	public function _create_model_query_info_carrier($query_params)
3426
+	{
3427
+		if (! is_array($query_params)) {
3428
+			EE_Error::doing_it_wrong(
3429
+				'EEM_Base::_create_model_query_info_carrier',
3430
+				sprintf(
3431
+					esc_html__(
3432
+						'$query_params should be an array, you passed a variable of type %s',
3433
+						'event_espresso'
3434
+					),
3435
+					gettype($query_params)
3436
+				),
3437
+				'4.6.0'
3438
+			);
3439
+			$query_params = [];
3440
+		}
3441
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3442
+		// first check if we should alter the query to account for caps or not
3443
+		// because the caps might require us to do extra joins
3444
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3445
+			$query_params[0] = array_replace_recursive(
3446
+				$query_params[0],
3447
+				$this->caps_where_conditions(
3448
+					$query_params['caps']
3449
+				)
3450
+			);
3451
+		}
3452
+
3453
+		// check if we should alter the query to remove data related to protected
3454
+		// custom post types
3455
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3456
+			$where_param_key_for_password = $this->modelChainAndPassword();
3457
+			// only include if related to a cpt where no password has been set
3458
+			$query_params[0]['OR*nopassword'] = [
3459
+				$where_param_key_for_password       => '',
3460
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3461
+			];
3462
+		}
3463
+		$query_object = $this->_extract_related_models_from_query($query_params);
3464
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3465
+		foreach ($query_params[0] as $key => $value) {
3466
+			if (is_int($key)) {
3467
+				throw new EE_Error(
3468
+					sprintf(
3469
+						esc_html__(
3470
+							"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.",
3471
+							"event_espresso"
3472
+						),
3473
+						$key,
3474
+						var_export($value, true),
3475
+						var_export($query_params, true),
3476
+						get_class($this)
3477
+					)
3478
+				);
3479
+			}
3480
+		}
3481
+		if (
3482
+			array_key_exists('default_where_conditions', $query_params)
3483
+			&& ! empty($query_params['default_where_conditions'])
3484
+		) {
3485
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3486
+		} else {
3487
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3488
+		}
3489
+		$query_params[0] = array_merge(
3490
+			$this->_get_default_where_conditions_for_models_in_query(
3491
+				$query_object,
3492
+				$use_default_where_conditions,
3493
+				$query_params[0]
3494
+			),
3495
+			$query_params[0]
3496
+		);
3497
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3498
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3499
+		// So we need to setup a subquery and use that for the main join.
3500
+		// Note for now this only works on the primary table for the model.
3501
+		// So for instance, you could set the limit array like this:
3502
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3503
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3504
+			$query_object->set_main_model_join_sql(
3505
+				$this->_construct_limit_join_select(
3506
+					$query_params['on_join_limit'][0],
3507
+					$query_params['on_join_limit'][1]
3508
+				)
3509
+			);
3510
+		}
3511
+		// set limit
3512
+		if (array_key_exists('limit', $query_params)) {
3513
+			if (is_array($query_params['limit'])) {
3514
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3515
+					$e = sprintf(
3516
+						esc_html__(
3517
+							"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)",
3518
+							"event_espresso"
3519
+						),
3520
+						http_build_query($query_params['limit'])
3521
+					);
3522
+					throw new EE_Error($e . "|" . $e);
3523
+				}
3524
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3525
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3526
+			} elseif (! empty($query_params['limit'])) {
3527
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3528
+			}
3529
+		}
3530
+		// set order by
3531
+		if (array_key_exists('order_by', $query_params)) {
3532
+			if (is_array($query_params['order_by'])) {
3533
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3534
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3535
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3536
+				if (array_key_exists('order', $query_params)) {
3537
+					throw new EE_Error(
3538
+						sprintf(
3539
+							esc_html__(
3540
+								"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 ",
3541
+								"event_espresso"
3542
+							),
3543
+							get_class($this),
3544
+							implode(", ", array_keys($query_params['order_by'])),
3545
+							implode(", ", $query_params['order_by']),
3546
+							$query_params['order']
3547
+						)
3548
+					);
3549
+				}
3550
+				$this->_extract_related_models_from_sub_params_array_keys(
3551
+					$query_params['order_by'],
3552
+					$query_object,
3553
+					'order_by'
3554
+				);
3555
+				// assume it's an array of fields to order by
3556
+				$order_array = [];
3557
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3558
+					$order         = $this->_extract_order($order);
3559
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3560
+				}
3561
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3562
+			} elseif (! empty($query_params['order_by'])) {
3563
+				$this->_extract_related_model_info_from_query_param(
3564
+					$query_params['order_by'],
3565
+					$query_object,
3566
+					'order',
3567
+					$query_params['order_by']
3568
+				);
3569
+				$order = isset($query_params['order'])
3570
+					? $this->_extract_order($query_params['order'])
3571
+					: 'DESC';
3572
+				$query_object->set_order_by_sql(
3573
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3574
+				);
3575
+			}
3576
+		}
3577
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3578
+		if (
3579
+			! array_key_exists('order_by', $query_params)
3580
+			&& array_key_exists('order', $query_params)
3581
+			&& ! empty($query_params['order'])
3582
+		) {
3583
+			$pk_field = $this->get_primary_key_field();
3584
+			$order    = $this->_extract_order($query_params['order']);
3585
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3586
+		}
3587
+		// set group by
3588
+		if (array_key_exists('group_by', $query_params)) {
3589
+			if (is_array($query_params['group_by'])) {
3590
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3591
+				$group_by_array = [];
3592
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3593
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3594
+				}
3595
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3596
+			} elseif (! empty($query_params['group_by'])) {
3597
+				$query_object->set_group_by_sql(
3598
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3599
+				);
3600
+			}
3601
+		}
3602
+		// set having
3603
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3604
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3605
+		}
3606
+		// now, just verify they didn't pass anything wack
3607
+		foreach ($query_params as $query_key => $query_value) {
3608
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3609
+				throw new EE_Error(
3610
+					sprintf(
3611
+						esc_html__(
3612
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3613
+							'event_espresso'
3614
+						),
3615
+						$query_key,
3616
+						get_class($this),
3617
+						//                      print_r( $this->_allowed_query_params, TRUE )
3618
+						implode(',', $this->_allowed_query_params)
3619
+					)
3620
+				);
3621
+			}
3622
+		}
3623
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3624
+		if (empty($main_model_join_sql)) {
3625
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3626
+		}
3627
+		return $query_object;
3628
+	}
3629
+
3630
+
3631
+	/**
3632
+	 * Gets the where conditions that should be imposed on the query based on the
3633
+	 * context (eg reading frontend, backend, edit or delete).
3634
+	 *
3635
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3636
+	 * @return array
3637
+	 * @throws EE_Error
3638
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3639
+	 */
3640
+	public function caps_where_conditions($context = self::caps_read)
3641
+	{
3642
+		EEM_Base::verify_is_valid_cap_context($context);
3643
+		$cap_where_conditions = [];
3644
+		$cap_restrictions     = $this->caps_missing($context);
3645
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3646
+			$cap_where_conditions = array_replace_recursive(
3647
+				$cap_where_conditions,
3648
+				$restriction_if_no_cap->get_default_where_conditions()
3649
+			);
3650
+		}
3651
+		return apply_filters(
3652
+			'FHEE__EEM_Base__caps_where_conditions__return',
3653
+			$cap_where_conditions,
3654
+			$this,
3655
+			$context,
3656
+			$cap_restrictions
3657
+		);
3658
+	}
3659
+
3660
+
3661
+	/**
3662
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3663
+	 * otherwise throws an exception
3664
+	 *
3665
+	 * @param string $should_be_order_string
3666
+	 * @return string either ASC, asc, DESC or desc
3667
+	 * @throws EE_Error
3668
+	 */
3669
+	private function _extract_order($should_be_order_string)
3670
+	{
3671
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3672
+			return $should_be_order_string;
3673
+		}
3674
+		throw new EE_Error(
3675
+			sprintf(
3676
+				esc_html__(
3677
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3678
+					"event_espresso"
3679
+				),
3680
+				get_class($this),
3681
+				$should_be_order_string
3682
+			)
3683
+		);
3684
+	}
3685
+
3686
+
3687
+	/**
3688
+	 * Looks at all the models which are included in this query, and asks each
3689
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3690
+	 * so they can be merged
3691
+	 *
3692
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3693
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3694
+	 *                                                                  'none' means NO default where conditions will
3695
+	 *                                                                  be used AT ALL during this query.
3696
+	 *                                                                  'other_models_only' means default where
3697
+	 *                                                                  conditions from other models will be used, but
3698
+	 *                                                                  not for this primary model. 'all', the default,
3699
+	 *                                                                  means default where conditions will apply as
3700
+	 *                                                                  normal
3701
+	 * @param array                       $where_query_params
3702
+	 * @return array
3703
+	 * @throws EE_Error
3704
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3705
+	 */
3706
+	private function _get_default_where_conditions_for_models_in_query(
3707
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3708
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3709
+		$where_query_params = []
3710
+	) {
3711
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3712
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3713
+			throw new EE_Error(
3714
+				sprintf(
3715
+					esc_html__(
3716
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3717
+						"event_espresso"
3718
+					),
3719
+					$use_default_where_conditions,
3720
+					implode(", ", $allowed_used_default_where_conditions_values)
3721
+				)
3722
+			);
3723
+		}
3724
+		$universal_query_params = [];
3725
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3726
+			$universal_query_params = $this->_get_default_where_conditions();
3727
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3728
+			$universal_query_params = $this->_get_minimum_where_conditions();
3729
+		}
3730
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3731
+			$related_model = $this->get_related_model_obj($model_name);
3732
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3733
+				$related_model_universal_where_params =
3734
+					$related_model->_get_default_where_conditions($model_relation_path);
3735
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3736
+				$related_model_universal_where_params =
3737
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3738
+			} else {
3739
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3740
+				continue;
3741
+			}
3742
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3743
+				$related_model_universal_where_params,
3744
+				$where_query_params,
3745
+				$related_model,
3746
+				$model_relation_path
3747
+			);
3748
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3749
+				$universal_query_params,
3750
+				$overrides
3751
+			);
3752
+		}
3753
+		return $universal_query_params;
3754
+	}
3755
+
3756
+
3757
+	/**
3758
+	 * Determines whether or not we should use default where conditions for the model in question
3759
+	 * (this model, or other related models).
3760
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3761
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3762
+	 * We should use default where conditions on related models when they requested to use default where conditions
3763
+	 * on all models, or specifically just on other related models
3764
+	 *
3765
+	 * @param      $default_where_conditions_value
3766
+	 * @param bool $for_this_model false means this is for OTHER related models
3767
+	 * @return bool
3768
+	 */
3769
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3770
+	{
3771
+		return (
3772
+				   $for_this_model
3773
+				   && in_array(
3774
+					   $default_where_conditions_value,
3775
+					   [
3776
+						   EEM_Base::default_where_conditions_all,
3777
+						   EEM_Base::default_where_conditions_this_only,
3778
+						   EEM_Base::default_where_conditions_minimum_others,
3779
+					   ],
3780
+					   true
3781
+				   )
3782
+			   )
3783
+			   || (
3784
+				   ! $for_this_model
3785
+				   && in_array(
3786
+					   $default_where_conditions_value,
3787
+					   [
3788
+						   EEM_Base::default_where_conditions_all,
3789
+						   EEM_Base::default_where_conditions_others_only,
3790
+					   ],
3791
+					   true
3792
+				   )
3793
+			   );
3794
+	}
3795
+
3796
+
3797
+	/**
3798
+	 * Determines whether or not we should use default minimum conditions for the model in question
3799
+	 * (this model, or other related models).
3800
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3801
+	 * where conditions.
3802
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3803
+	 * on this model or others
3804
+	 *
3805
+	 * @param      $default_where_conditions_value
3806
+	 * @param bool $for_this_model false means this is for OTHER related models
3807
+	 * @return bool
3808
+	 */
3809
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3810
+	{
3811
+		return (
3812
+				   $for_this_model
3813
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3814
+			   )
3815
+			   || (
3816
+				   ! $for_this_model
3817
+				   && in_array(
3818
+					   $default_where_conditions_value,
3819
+					   [
3820
+						   EEM_Base::default_where_conditions_minimum_others,
3821
+						   EEM_Base::default_where_conditions_minimum_all,
3822
+					   ],
3823
+					   true
3824
+				   )
3825
+			   );
3826
+	}
3827
+
3828
+
3829
+	/**
3830
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3831
+	 * then we also add a special where condition which allows for that model's primary key
3832
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3833
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3834
+	 *
3835
+	 * @param array    $default_where_conditions
3836
+	 * @param array    $provided_where_conditions
3837
+	 * @param EEM_Base $model
3838
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3839
+	 * @return array
3840
+	 * @throws EE_Error
3841
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3842
+	 */
3843
+	private function _override_defaults_or_make_null_friendly(
3844
+		$default_where_conditions,
3845
+		$provided_where_conditions,
3846
+		$model,
3847
+		$model_relation_path
3848
+	) {
3849
+		$null_friendly_where_conditions = [];
3850
+		$none_overridden                = true;
3851
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3852
+		foreach ($default_where_conditions as $key => $val) {
3853
+			if (isset($provided_where_conditions[ $key ])) {
3854
+				$none_overridden = false;
3855
+			} else {
3856
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
+			}
3858
+		}
3859
+		if ($none_overridden && $default_where_conditions) {
3860
+			if ($model->has_primary_key_field()) {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
+																				   . "."
3863
+																				   . $model->primary_key_name() ] =
3864
+					['IS NULL'];
3865
+			}/*else{
3866 3866
                 //@todo NO PK, use other defaults
3867 3867
             }*/
3868
-        }
3869
-        return $null_friendly_where_conditions;
3870
-    }
3871
-
3872
-
3873
-    /**
3874
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3875
-     * default where conditions on all get_all, update, and delete queries done by this model.
3876
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3878
-     *
3879
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
-     * @return array
3881
-     * @throws EE_Error
3882
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3883
-     */
3884
-    private function _get_default_where_conditions($model_relation_path = '')
3885
-    {
3886
-        if ($this->_ignore_where_strategy) {
3887
-            return [];
3888
-        }
3889
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3890
-    }
3891
-
3892
-
3893
-    /**
3894
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3895
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3896
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3897
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3898
-     * Similar to _get_default_where_conditions
3899
-     *
3900
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3901
-     * @return array
3902
-     * @throws EE_Error
3903
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3904
-     */
3905
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3906
-    {
3907
-        if ($this->_ignore_where_strategy) {
3908
-            return [];
3909
-        }
3910
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3911
-    }
3912
-
3913
-
3914
-    /**
3915
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3916
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3917
-     *
3918
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3919
-     * @return string
3920
-     * @throws EE_Error
3921
-     */
3922
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3923
-    {
3924
-        $selects = $this->_get_columns_to_select_for_this_model();
3925
-        foreach (
3926
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3927
-        ) {
3928
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3929
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3930
-            foreach ($other_model_selects as $key => $value) {
3931
-                $selects[] = $value;
3932
-            }
3933
-        }
3934
-        return implode(", ", $selects);
3935
-    }
3936
-
3937
-
3938
-    /**
3939
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3940
-     * So that's going to be the columns for all the fields on the model
3941
-     *
3942
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3943
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3944
-     */
3945
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3946
-    {
3947
-        $fields                                       = $this->field_settings();
3948
-        $selects                                      = [];
3949
-        $table_alias_with_model_relation_chain_prefix =
3950
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3951
-                $model_relation_chain,
3952
-                $this->get_this_model_name()
3953
-            );
3954
-        foreach ($fields as $field_obj) {
3955
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3956
-                         . $field_obj->get_table_alias()
3957
-                         . "."
3958
-                         . $field_obj->get_table_column()
3959
-                         . " AS '"
3960
-                         . $table_alias_with_model_relation_chain_prefix
3961
-                         . $field_obj->get_table_alias()
3962
-                         . "."
3963
-                         . $field_obj->get_table_column()
3964
-                         . "'";
3965
-        }
3966
-        // make sure we are also getting the PKs of each table
3967
-        $tables = $this->get_tables();
3968
-        if (count($tables) > 1) {
3969
-            foreach ($tables as $table_obj) {
3970
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3971
-                                       . $table_obj->get_fully_qualified_pk_column();
3972
-                if (! in_array($qualified_pk_column, $selects)) {
3973
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3974
-                }
3975
-            }
3976
-        }
3977
-        return $selects;
3978
-    }
3979
-
3980
-
3981
-    /**
3982
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3983
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3984
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3985
-     * SQL for joining, and the data types
3986
-     *
3987
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3988
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3990
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3991
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3992
-     *                                                          or 'Registration's
3993
-     * @param string|null                 $original_query_param what it originally was (eg
3994
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3995
-     *                                                          matches $query_param
3996
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
-     * @throws EE_Error
3998
-     */
3999
-    private function _extract_related_model_info_from_query_param(
4000
-        $query_param,
4001
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4002
-        $query_param_type,
4003
-        $original_query_param = null
4004
-    ) {
4005
-        if ($original_query_param === null) {
4006
-            $original_query_param = $query_param;
4007
-        }
4008
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4009
-        // whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4010
-        $allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4011
-        $allow_fields             = in_array(
4012
-            $query_param_type,
4013
-            ['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4014
-            true
4015
-        );
4016
-        // check to see if we have a field on this model
4017
-        $this_model_fields = $this->field_settings(true);
4018
-        if (array_key_exists($query_param, $this_model_fields)) {
4019
-            if ($allow_fields) {
4020
-                return;
4021
-            }
4022
-            throw new EE_Error(
4023
-                sprintf(
4024
-                    esc_html__(
4025
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4026
-                        "event_espresso"
4027
-                    ),
4028
-                    $query_param,
4029
-                    get_class($this),
4030
-                    $query_param_type,
4031
-                    $original_query_param
4032
-                )
4033
-            );
4034
-        }
4035
-        // check if this is a special logic query param
4036
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4037
-            if ($allow_logic_query_params) {
4038
-                return;
4039
-            }
4040
-            throw new EE_Error(
4041
-                sprintf(
4042
-                    esc_html__(
4043
-                        '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',
4044
-                        'event_espresso'
4045
-                    ),
4046
-                    implode('", "', $this->_logic_query_param_keys),
4047
-                    $query_param,
4048
-                    get_class($this),
4049
-                    '<br />',
4050
-                    "\t"
4051
-                    . ' $passed_in_query_info = <pre>'
4052
-                    . print_r($passed_in_query_info, true)
4053
-                    . '</pre>'
4054
-                    . "\n\t"
4055
-                    . ' $query_param_type = '
4056
-                    . $query_param_type
4057
-                    . "\n\t"
4058
-                    . ' $original_query_param = '
4059
-                    . $original_query_param
4060
-                )
4061
-            );
4062
-        }
4063
-        // check if it's a custom selection
4064
-        if (
4065
-            $this->_custom_selections instanceof CustomSelects
4066
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4067
-        ) {
4068
-            return;
4069
-        }
4070
-        // check if has a model name at the beginning
4071
-        // and
4072
-        // check if it's a field on a related model
4073
-        if (
4074
-        $this->extractJoinModelFromQueryParams(
4075
-            $passed_in_query_info,
4076
-            $query_param,
4077
-            $original_query_param,
4078
-            $query_param_type
4079
-        )
4080
-        ) {
4081
-            return;
4082
-        }
4083
-
4084
-        // ok so $query_param didn't start with a model name
4085
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4086
-        // it's wack, that's what it is
4087
-        throw new EE_Error(
4088
-            sprintf(
4089
-                esc_html__(
4090
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4091
-                    "event_espresso"
4092
-                ),
4093
-                $query_param,
4094
-                get_class($this),
4095
-                $query_param_type,
4096
-                $original_query_param
4097
-            )
4098
-        );
4099
-    }
4100
-
4101
-
4102
-    /**
4103
-     * Extracts any possible join model information from the provided possible_join_string.
4104
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4105
-     * join
4106
-     * parts that should be added to the query.
4107
-     *
4108
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4109
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4110
-     * @param null|string                 $original_query_param
4111
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4112
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4113
-     *                                                           etc.)
4114
-     * @return bool  returns true if a join was added and false if not.
4115
-     * @throws EE_Error
4116
-     */
4117
-    private function extractJoinModelFromQueryParams(
4118
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4119
-        $possible_join_string,
4120
-        $original_query_param,
4121
-        $query_parameter_type
4122
-    ) {
4123
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4124
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4125
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4126
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4127
-                if ($possible_join_string === '') {
4128
-                    // nothing left to $query_param
4129
-                    // we should actually end in a field name, not a model like this!
4130
-                    throw new EE_Error(
4131
-                        sprintf(
4132
-                            esc_html__(
4133
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4134
-                                "event_espresso"
4135
-                            ),
4136
-                            $possible_join_string,
4137
-                            $query_parameter_type,
4138
-                            get_class($this),
4139
-                            $valid_related_model_name
4140
-                        )
4141
-                    );
4142
-                }
4143
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4144
-                $related_model_obj->_extract_related_model_info_from_query_param(
4145
-                    $possible_join_string,
4146
-                    $query_info_carrier,
4147
-                    $query_parameter_type,
4148
-                    $original_query_param
4149
-                );
4150
-                return true;
4151
-            }
4152
-            if ($possible_join_string === $valid_related_model_name) {
4153
-                $this->_add_join_to_model(
4154
-                    $valid_related_model_name,
4155
-                    $query_info_carrier,
4156
-                    $original_query_param
4157
-                );
4158
-                return true;
4159
-            }
4160
-        }
4161
-        return false;
4162
-    }
4163
-
4164
-
4165
-    /**
4166
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4167
-     *
4168
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4169
-     * @throws EE_Error
4170
-     */
4171
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4172
-    {
4173
-        if (
4174
-            $this->_custom_selections instanceof CustomSelects
4175
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4176
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4177
-            )
4178
-        ) {
4179
-            $original_selects = $this->_custom_selections->originalSelects();
4180
-            foreach ($original_selects as $alias => $select_configuration) {
4181
-                $this->extractJoinModelFromQueryParams(
4182
-                    $query_info_carrier,
4183
-                    $select_configuration[0],
4184
-                    $select_configuration[0],
4185
-                    'custom_selects'
4186
-                );
4187
-            }
4188
-        }
4189
-    }
4190
-
4191
-
4192
-    /**
4193
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4194
-     * and store it on $passed_in_query_info
4195
-     *
4196
-     * @param string                      $model_name
4197
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4198
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4199
-     *                                                          model and $model_name. Eg, if we are querying Event,
4200
-     *                                                          and are adding a join to 'Payment' with the original
4201
-     *                                                          query param key
4202
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4203
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4204
-     *                                                          Payment wants to add default query params so that it
4205
-     *                                                          will know what models to prepend onto its default query
4206
-     *                                                          params or in case it wants to rename tables (in case
4207
-     *                                                          there are multiple joins to the same table)
4208
-     * @return void
4209
-     * @throws EE_Error
4210
-     */
4211
-    private function _add_join_to_model(
4212
-        $model_name,
4213
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4214
-        $original_query_param
4215
-    ) {
4216
-        $relation_obj         = $this->related_settings_for($model_name);
4217
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4218
-        // check if the relation is HABTM, because then we're essentially doing two joins
4219
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4220
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4221
-            $join_model_obj = $relation_obj->get_join_model();
4222
-            // replace the model specified with the join model for this relation chain, whi
4223
-            $relation_chain_to_join_model =
4224
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4225
-                    $model_name,
4226
-                    $join_model_obj->get_this_model_name(),
4227
-                    $model_relation_chain
4228
-                );
4229
-            $passed_in_query_info->merge(
4230
-                new EE_Model_Query_Info_Carrier(
4231
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4232
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4233
-                )
4234
-            );
4235
-        }
4236
-        // now just join to the other table pointed to by the relation object, and add its data types
4237
-        $passed_in_query_info->merge(
4238
-            new EE_Model_Query_Info_Carrier(
4239
-                [$model_relation_chain => $model_name],
4240
-                $relation_obj->get_join_statement($model_relation_chain)
4241
-            )
4242
-        );
4243
-    }
4244
-
4245
-
4246
-    /**
4247
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4248
-     *
4249
-     * @param array $where_params
4250
-     * @return string of SQL
4251
-     * @throws EE_Error
4252
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4253
-     */
4254
-    private function _construct_where_clause($where_params)
4255
-    {
4256
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4257
-        if ($SQL) {
4258
-            return " WHERE " . $SQL;
4259
-        }
4260
-        return '';
4261
-    }
4262
-
4263
-
4264
-    /**
4265
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4266
-     * and should be passed HAVING parameters, not WHERE parameters
4267
-     *
4268
-     * @param array $having_params
4269
-     * @return string
4270
-     * @throws EE_Error
4271
-     */
4272
-    private function _construct_having_clause($having_params)
4273
-    {
4274
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4275
-        if ($SQL) {
4276
-            return " HAVING " . $SQL;
4277
-        }
4278
-        return '';
4279
-    }
4280
-
4281
-
4282
-    /**
4283
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4284
-     * Event_Meta.meta_value = 'foo'))"
4285
-     *
4286
-     * @param array  $where_params
4287
-     * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4288
-     * @return string of SQL
4289
-     * @throws EE_Error
4290
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4291
-     */
4292
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4293
-    {
4294
-        $where_clauses = [];
4295
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4296
-            $query_param =
4297
-                $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4298
-                    $query_param
4299
-                );// str_replace("*",'',$query_param);
4300
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4301
-                switch ($query_param) {
4302
-                    case 'not':
4303
-                    case 'NOT':
4304
-                        $where_clauses[] = "! ("
4305
-                                           . $this->_construct_condition_clause_recursive(
4306
-                                $op_and_value_or_sub_condition,
4307
-                                $glue
4308
-                            )
4309
-                                           . ")";
4310
-                        break;
4311
-                    case 'and':
4312
-                    case 'AND':
4313
-                        $where_clauses[] = " ("
4314
-                                           . $this->_construct_condition_clause_recursive(
4315
-                                $op_and_value_or_sub_condition,
4316
-                                ' AND '
4317
-                            )
4318
-                                           . ")";
4319
-                        break;
4320
-                    case 'or':
4321
-                    case 'OR':
4322
-                        $where_clauses[] = " ("
4323
-                                           . $this->_construct_condition_clause_recursive(
4324
-                                $op_and_value_or_sub_condition,
4325
-                                ' OR '
4326
-                            )
4327
-                                           . ")";
4328
-                        break;
4329
-                }
4330
-            } else {
4331
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4332
-                // if it's not a normal field, maybe it's a custom selection?
4333
-                if (! $field_obj) {
4334
-                    if ($this->_custom_selections instanceof CustomSelects) {
4335
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4336
-                    } else {
4337
-                        throw new EE_Error(
4338
-                            sprintf(
4339
-                                esc_html__(
4340
-                                    "%s is neither a valid model field name, nor a custom selection",
4341
-                                    "event_espresso"
4342
-                                ),
4343
-                                $query_param
4344
-                            )
4345
-                        );
4346
-                    }
4347
-                }
4348
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4349
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4350
-            }
4351
-        }
4352
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4353
-    }
4354
-
4355
-
4356
-    /**
4357
-     * Takes the input parameter and extract the table name (alias) and column name
4358
-     *
4359
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4360
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4361
-     * @throws EE_Error
4362
-     */
4363
-    private function _deduce_column_name_from_query_param($query_param)
4364
-    {
4365
-        $field = $this->_deduce_field_from_query_param($query_param);
4366
-        if ($field) {
4367
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4368
-                $field->get_model_name(),
4369
-                $query_param
4370
-            );
4371
-            return $table_alias_prefix . $field->get_qualified_column();
4372
-        }
4373
-        if (
4374
-            $this->_custom_selections instanceof CustomSelects
4375
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4376
-        ) {
4377
-            // maybe it's custom selection item?
4378
-            // if so, just use it as the "column name"
4379
-            return $query_param;
4380
-        }
4381
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4382
-            ? implode(',', $this->_custom_selections->columnAliases())
4383
-            : '';
4384
-        throw new EE_Error(
4385
-            sprintf(
4386
-                esc_html__(
4387
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4388
-                    "event_espresso"
4389
-                ),
4390
-                $query_param,
4391
-                $custom_select_aliases
4392
-            )
4393
-        );
4394
-    }
4395
-
4396
-
4397
-    /**
4398
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4399
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4400
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4401
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4402
-     *
4403
-     * @param string $condition_query_param_key
4404
-     * @return string
4405
-     */
4406
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4407
-    {
4408
-        $pos_of_star = strpos($condition_query_param_key, '*');
4409
-        if ($pos_of_star === false) {
4410
-            return $condition_query_param_key;
4411
-        }
4412
-        return substr($condition_query_param_key, 0, $pos_of_star);
4413
-    }
4414
-
4415
-
4416
-    /**
4417
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4418
-     *
4419
-     * @param mixed      array | string    $op_and_value
4420
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4421
-     * @return string
4422
-     * @throws EE_Error
4423
-     */
4424
-    private function _construct_op_and_value($op_and_value, $field_obj)
4425
-    {
4426
-        if (is_array($op_and_value)) {
4427
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4428
-            if (! $operator) {
4429
-                $php_array_like_string = [];
4430
-                foreach ($op_and_value as $key => $value) {
4431
-                    $php_array_like_string[] = "$key=>$value";
4432
-                }
4433
-                throw new EE_Error(
4434
-                    sprintf(
4435
-                        esc_html__(
4436
-                            "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))",
4437
-                            "event_espresso"
4438
-                        ),
4439
-                        implode(",", $php_array_like_string)
4440
-                    )
4441
-                );
4442
-            }
4443
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4444
-        } else {
4445
-            $operator = '=';
4446
-            $value    = $op_and_value;
4447
-        }
4448
-        // check to see if the value is actually another field
4449
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4450
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4451
-        }
4452
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4453
-            // in this case, the value should be an array, or at least a comma-separated list
4454
-            // it will need to handle a little differently
4455
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4456
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4457
-            return $operator . SP . $cleaned_value;
4458
-        }
4459
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4460
-            // the value should be an array with count of two.
4461
-            if (count($value) !== 2) {
4462
-                throw new EE_Error(
4463
-                    sprintf(
4464
-                        esc_html__(
4465
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4466
-                            'event_espresso'
4467
-                        ),
4468
-                        "BETWEEN"
4469
-                    )
4470
-                );
4471
-            }
4472
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4473
-            return $operator . SP . $cleaned_value;
4474
-        }
4475
-        if (in_array($operator, $this->valid_null_style_operators())) {
4476
-            if ($value !== null) {
4477
-                throw new EE_Error(
4478
-                    sprintf(
4479
-                        esc_html__(
4480
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4481
-                            "event_espresso"
4482
-                        ),
4483
-                        $value,
4484
-                        $operator
4485
-                    )
4486
-                );
4487
-            }
4488
-            return $operator;
4489
-        }
4490
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4491
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4492
-            // remove other junk. So just treat it as a string.
4493
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4494
-        }
4495
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4496
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4497
-        }
4498
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4499
-            throw new EE_Error(
4500
-                sprintf(
4501
-                    esc_html__(
4502
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4503
-                        'event_espresso'
4504
-                    ),
4505
-                    $operator,
4506
-                    $operator
4507
-                )
4508
-            );
4509
-        }
4510
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4511
-            throw new EE_Error(
4512
-                sprintf(
4513
-                    esc_html__(
4514
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4515
-                        'event_espresso'
4516
-                    ),
4517
-                    $operator,
4518
-                    $operator
4519
-                )
4520
-            );
4521
-        }
4522
-        throw new EE_Error(
4523
-            sprintf(
4524
-                esc_html__(
4525
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4526
-                    "event_espresso"
4527
-                ),
4528
-                http_build_query($op_and_value)
4529
-            )
4530
-        );
4531
-    }
4532
-
4533
-
4534
-    /**
4535
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4536
-     *
4537
-     * @param array                      $values
4538
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4539
-     *                                              '%s'
4540
-     * @return string
4541
-     * @throws EE_Error
4542
-     */
4543
-    public function _construct_between_value($values, $field_obj)
4544
-    {
4545
-        $cleaned_values = [];
4546
-        foreach ($values as $value) {
4547
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4548
-        }
4549
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4550
-    }
4551
-
4552
-
4553
-    /**
4554
-     * Takes an array or a comma-separated list of $values and cleans them
4555
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4556
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4557
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4558
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4559
-     *
4560
-     * @param mixed                      $values    array or comma-separated string
4561
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4562
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4563
-     * @throws EE_Error
4564
-     */
4565
-    public function _construct_in_value($values, $field_obj)
4566
-    {
4567
-        // check if the value is a CSV list
4568
-        if (is_string($values)) {
4569
-            // in which case, turn it into an array
4570
-            $values = explode(",", $values);
4571
-        }
4572
-        $cleaned_values = [];
4573
-        foreach ($values as $value) {
4574
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4575
-        }
4576
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4577
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4578
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4579
-        if (empty($cleaned_values)) {
4580
-            $all_fields       = $this->field_settings();
4581
-            $a_field          = array_shift($all_fields);
4582
-            $main_table       = $this->_get_main_table();
4583
-            $cleaned_values[] = "SELECT "
4584
-                                . $a_field->get_table_column()
4585
-                                . " FROM "
4586
-                                . $main_table->get_table_name()
4587
-                                . " WHERE FALSE";
4588
-        }
4589
-        return "(" . implode(",", $cleaned_values) . ")";
4590
-    }
4591
-
4592
-
4593
-    /**
4594
-     * @param mixed                      $value
4595
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4596
-     * @return false|null|string
4597
-     * @throws EE_Error
4598
-     */
4599
-    private function _wpdb_prepare_using_field($value, $field_obj)
4600
-    {
4601
-        global $wpdb;
4602
-        if ($field_obj instanceof EE_Model_Field_Base) {
4603
-            return $wpdb->prepare(
4604
-                $field_obj->get_wpdb_data_type(),
4605
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4606
-            );
4607
-        } //$field_obj should really just be a data type
4608
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4609
-            throw new EE_Error(
4610
-                sprintf(
4611
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4612
-                    $field_obj,
4613
-                    implode(",", $this->_valid_wpdb_data_types)
4614
-                )
4615
-            );
4616
-        }
4617
-        return $wpdb->prepare($field_obj, $value);
4618
-    }
4619
-
4620
-
4621
-    /**
4622
-     * Takes the input parameter and finds the model field that it indicates.
4623
-     *
4624
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4625
-     * @return EE_Model_Field_Base
4626
-     * @throws EE_Error
4627
-     */
4628
-    protected function _deduce_field_from_query_param($query_param_name)
4629
-    {
4630
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4631
-        // which will help us find the database table and column
4632
-        $query_param_parts = explode(".", $query_param_name);
4633
-        if (empty($query_param_parts)) {
4634
-            throw new EE_Error(
4635
-                sprintf(
4636
-                    esc_html__(
4637
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4638
-                        'event_espresso'
4639
-                    ),
4640
-                    $query_param_name
4641
-                )
4642
-            );
4643
-        }
4644
-        $number_of_parts       = count($query_param_parts);
4645
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4646
-        if ($number_of_parts === 1) {
4647
-            $field_name = $last_query_param_part;
4648
-            $model_obj  = $this;
4649
-        } else {// $number_of_parts >= 2
4650
-            // the last part is the column name, and there are only 2parts. therefore...
4651
-            $field_name = $last_query_param_part;
4652
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4653
-        }
4654
-        try {
4655
-            return $model_obj->field_settings_for($field_name);
4656
-        } catch (EE_Error $e) {
4657
-            return null;
4658
-        }
4659
-    }
4660
-
4661
-
4662
-    /**
4663
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4664
-     * alias and column which corresponds to it
4665
-     *
4666
-     * @param string $field_name
4667
-     * @return string
4668
-     * @throws EE_Error
4669
-     */
4670
-    public function _get_qualified_column_for_field($field_name)
4671
-    {
4672
-        $all_fields = $this->field_settings();
4673
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4674
-        if ($field) {
4675
-            return $field->get_qualified_column();
4676
-        }
4677
-        throw new EE_Error(
4678
-            sprintf(
4679
-                esc_html__(
4680
-                    "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.",
4681
-                    'event_espresso'
4682
-                ),
4683
-                $field_name,
4684
-                get_class($this)
4685
-            )
4686
-        );
4687
-    }
4688
-
4689
-
4690
-    /**
4691
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4692
-     * Example usage:
4693
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4694
-     *      array(),
4695
-     *      ARRAY_A,
4696
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4697
-     *  );
4698
-     * is equivalent to
4699
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4700
-     * and
4701
-     *  EEM_Event::instance()->get_all_wpdb_results(
4702
-     *      array(
4703
-     *          array(
4704
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4705
-     *          ),
4706
-     *          ARRAY_A,
4707
-     *          implode(
4708
-     *              ', ',
4709
-     *              array_merge(
4710
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4711
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4712
-     *              )
4713
-     *          )
4714
-     *      )
4715
-     *  );
4716
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4717
-     *
4718
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4719
-     *                                            and the one whose fields you are selecting for example: when querying
4720
-     *                                            tickets model and selecting fields from the tickets model you would
4721
-     *                                            leave this parameter empty, because no models are needed to join
4722
-     *                                            between the queried model and the selected one. Likewise when
4723
-     *                                            querying the datetime model and selecting fields from the tickets
4724
-     *                                            model, it would also be left empty, because there is a direct
4725
-     *                                            relation from datetimes to tickets, so no model is needed to join
4726
-     *                                            them together. However, when querying from the event model and
4727
-     *                                            selecting fields from the ticket model, you should provide the string
4728
-     *                                            'Datetime', indicating that the event model must first join to the
4729
-     *                                            datetime model in order to find its relation to ticket model.
4730
-     *                                            Also, when querying from the venue model and selecting fields from
4731
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4732
-     *                                            indicating you need to join the venue model to the event model,
4733
-     *                                            to the datetime model, in order to find its relation to the ticket
4734
-     *                                            model. This string is used to deduce the prefix that gets added onto
4735
-     *                                            the models' tables qualified columns
4736
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4737
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4738
-     *                                            qualified column names
4739
-     * @return array|string
4740
-     */
4741
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4742
-    {
4743
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4744
-        $qualified_columns = [];
4745
-        foreach ($this->field_settings() as $field_name => $field) {
4746
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4747
-        }
4748
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4749
-    }
4750
-
4751
-
4752
-    /**
4753
-     * constructs the select use on special limit joins
4754
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4755
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4756
-     * (as that is typically where the limits would be set).
4757
-     *
4758
-     * @param string       $table_alias The table the select is being built for
4759
-     * @param mixed|string $limit       The limit for this select
4760
-     * @return string                The final select join element for the query.
4761
-     * @throws EE_Error
4762
-     */
4763
-    public function _construct_limit_join_select($table_alias, $limit)
4764
-    {
4765
-        $SQL = '';
4766
-        foreach ($this->_tables as $table_obj) {
4767
-            if ($table_obj instanceof EE_Primary_Table) {
4768
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4769
-                    ? $table_obj->get_select_join_limit($limit)
4770
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4771
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4772
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4773
-                    ? $table_obj->get_select_join_limit_join($limit)
4774
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4775
-            }
4776
-        }
4777
-        return $SQL;
4778
-    }
4779
-
4780
-
4781
-    /**
4782
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4783
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4784
-     *
4785
-     * @return string SQL
4786
-     * @throws EE_Error
4787
-     */
4788
-    public function _construct_internal_join()
4789
-    {
4790
-        $SQL = $this->_get_main_table()->get_table_sql();
4791
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4792
-        return $SQL;
4793
-    }
4794
-
4795
-
4796
-    /**
4797
-     * Constructs the SQL for joining all the tables on this model.
4798
-     * Normally $alias should be the primary table's alias, but in cases where
4799
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4800
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4801
-     * alias, this will construct SQL like:
4802
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4803
-     * With $alias being a secondary table's alias, this will construct SQL like:
4804
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4805
-     *
4806
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4807
-     * @return string
4808
-     * @throws EE_Error
4809
-     */
4810
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4811
-    {
4812
-        $SQL               = '';
4813
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4814
-        foreach ($this->_tables as $table_obj) {
4815
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4816
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4817
-                    // so we're joining to this table, meaning the table is already in
4818
-                    // the FROM statement, BUT the primary table isn't. So we want
4819
-                    // to add the inverse join sql
4820
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4821
-                } else {
4822
-                    // just add a regular JOIN to this table from the primary table
4823
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4824
-                }
4825
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4826
-        }
4827
-        return $SQL;
4828
-    }
4829
-
4830
-
4831
-    /**
4832
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4833
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4834
-     * their data type (eg, '%s', '%d', etc)
4835
-     *
4836
-     * @return array
4837
-     */
4838
-    public function _get_data_types()
4839
-    {
4840
-        $data_types = [];
4841
-        foreach ($this->field_settings() as $field_obj) {
4842
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4843
-            /** @var $field_obj EE_Model_Field_Base */
4844
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4845
-        }
4846
-        return $data_types;
4847
-    }
4848
-
4849
-
4850
-    /**
4851
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4852
-     *
4853
-     * @param string $model_name
4854
-     * @return EEM_Base
4855
-     * @throws EE_Error
4856
-     */
4857
-    public function get_related_model_obj($model_name)
4858
-    {
4859
-        $model_classname = "EEM_" . $model_name;
4860
-        if (! class_exists($model_classname)) {
4861
-            throw new EE_Error(
4862
-                sprintf(
4863
-                    esc_html__(
4864
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4865
-                        'event_espresso'
4866
-                    ),
4867
-                    $model_name,
4868
-                    $model_classname
4869
-                )
4870
-            );
4871
-        }
4872
-        return call_user_func($model_classname . "::instance");
4873
-    }
4874
-
4875
-
4876
-    /**
4877
-     * Returns the array of EE_ModelRelations for this model.
4878
-     *
4879
-     * @return EE_Model_Relation_Base[]
4880
-     */
4881
-    public function relation_settings()
4882
-    {
4883
-        return $this->_model_relations;
4884
-    }
4885
-
4886
-
4887
-    /**
4888
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4889
-     * because without THOSE models, this model probably doesn't have much purpose.
4890
-     * (Eg, without an event, datetimes have little purpose.)
4891
-     *
4892
-     * @return EE_Belongs_To_Relation[]
4893
-     */
4894
-    public function belongs_to_relations()
4895
-    {
4896
-        $belongs_to_relations = [];
4897
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4898
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4899
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4900
-            }
4901
-        }
4902
-        return $belongs_to_relations;
4903
-    }
4904
-
4905
-
4906
-    /**
4907
-     * Returns the specified EE_Model_Relation, or throws an exception
4908
-     *
4909
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4910
-     * @return EE_Model_Relation_Base
4911
-     * @throws EE_Error
4912
-     */
4913
-    public function related_settings_for($relation_name)
4914
-    {
4915
-        $relatedModels = $this->relation_settings();
4916
-        if (! array_key_exists($relation_name, $relatedModels)) {
4917
-            throw new EE_Error(
4918
-                sprintf(
4919
-                    esc_html__(
4920
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4921
-                        'event_espresso'
4922
-                    ),
4923
-                    $relation_name,
4924
-                    $this->_get_class_name(),
4925
-                    implode(', ', array_keys($relatedModels))
4926
-                )
4927
-            );
4928
-        }
4929
-        return $relatedModels[ $relation_name ];
4930
-    }
4931
-
4932
-
4933
-    /**
4934
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4935
-     * fields
4936
-     *
4937
-     * @param string  $fieldName
4938
-     * @param boolean $include_db_only_fields
4939
-     * @return EE_Model_Field_Base
4940
-     * @throws EE_Error
4941
-     */
4942
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4943
-    {
4944
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4945
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4946
-            throw new EE_Error(
4947
-                sprintf(
4948
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4949
-                    $fieldName,
4950
-                    get_class($this)
4951
-                )
4952
-            );
4953
-        }
4954
-        return $fieldSettings[ $fieldName ];
4955
-    }
4956
-
4957
-
4958
-    /**
4959
-     * Checks if this field exists on this model
4960
-     *
4961
-     * @param string $fieldName a key in the model's _field_settings array
4962
-     * @return boolean
4963
-     */
4964
-    public function has_field($fieldName)
4965
-    {
4966
-        $fieldSettings = $this->field_settings(true);
4967
-        if (isset($fieldSettings[ $fieldName ])) {
4968
-            return true;
4969
-        }
4970
-        return false;
4971
-    }
4972
-
4973
-
4974
-    /**
4975
-     * Returns whether or not this model has a relation to the specified model
4976
-     *
4977
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4978
-     * @return boolean
4979
-     */
4980
-    public function has_relation($relation_name)
4981
-    {
4982
-        $relations = $this->relation_settings();
4983
-        if (isset($relations[ $relation_name ])) {
4984
-            return true;
4985
-        }
4986
-        return false;
4987
-    }
4988
-
4989
-
4990
-    /**
4991
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4992
-     * Eg, on EE_Answer that would be ANS_ID field object
4993
-     *
4994
-     * @param $field_obj
4995
-     * @return boolean
4996
-     */
4997
-    public function is_primary_key_field($field_obj)
4998
-    {
4999
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5000
-    }
5001
-
5002
-
5003
-    /**
5004
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5005
-     * Eg, on EE_Answer that would be ANS_ID field object
5006
-     *
5007
-     * @return EE_Model_Field_Base
5008
-     * @throws EE_Error
5009
-     */
5010
-    public function get_primary_key_field()
5011
-    {
5012
-        if ($this->_primary_key_field === null) {
5013
-            foreach ($this->field_settings(true) as $field_obj) {
5014
-                if ($this->is_primary_key_field($field_obj)) {
5015
-                    $this->_primary_key_field = $field_obj;
5016
-                    break;
5017
-                }
5018
-            }
5019
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5020
-                throw new EE_Error(
5021
-                    sprintf(
5022
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5023
-                        get_class($this)
5024
-                    )
5025
-                );
5026
-            }
5027
-        }
5028
-        return $this->_primary_key_field;
5029
-    }
5030
-
5031
-
5032
-    /**
5033
-     * Returns whether or not not there is a primary key on this model.
5034
-     * Internally does some caching.
5035
-     *
5036
-     * @return boolean
5037
-     */
5038
-    public function has_primary_key_field()
5039
-    {
5040
-        if ($this->_has_primary_key_field === null) {
5041
-            try {
5042
-                $this->get_primary_key_field();
5043
-                $this->_has_primary_key_field = true;
5044
-            } catch (EE_Error $e) {
5045
-                $this->_has_primary_key_field = false;
5046
-            }
5047
-        }
5048
-        return $this->_has_primary_key_field;
5049
-    }
5050
-
5051
-
5052
-    /**
5053
-     * Finds the first field of type $field_class_name.
5054
-     *
5055
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5056
-     *                                 EE_Foreign_Key_Field, etc
5057
-     * @return EE_Model_Field_Base or null if none is found
5058
-     */
5059
-    public function get_a_field_of_type($field_class_name)
5060
-    {
5061
-        foreach ($this->field_settings() as $field) {
5062
-            if ($field instanceof $field_class_name) {
5063
-                return $field;
5064
-            }
5065
-        }
5066
-        return null;
5067
-    }
5068
-
5069
-
5070
-    /**
5071
-     * Gets a foreign key field pointing to model.
5072
-     *
5073
-     * @param string $model_name eg Event, Registration, not EEM_Event
5074
-     * @return EE_Foreign_Key_Field_Base
5075
-     * @throws EE_Error
5076
-     */
5077
-    public function get_foreign_key_to($model_name)
5078
-    {
5079
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5080
-            foreach ($this->field_settings() as $field) {
5081
-                if (
5082
-                    $field instanceof EE_Foreign_Key_Field_Base
5083
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5084
-                ) {
5085
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5086
-                    break;
5087
-                }
5088
-            }
5089
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5090
-                throw new EE_Error(
5091
-                    sprintf(
5092
-                        esc_html__(
5093
-                            "There is no foreign key field pointing to model %s on model %s",
5094
-                            'event_espresso'
5095
-                        ),
5096
-                        $model_name,
5097
-                        get_class($this)
5098
-                    )
5099
-                );
5100
-            }
5101
-        }
5102
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5103
-    }
5104
-
5105
-
5106
-    /**
5107
-     * Gets the table name (including $wpdb->prefix) for the table alias
5108
-     *
5109
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5110
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5111
-     *                            Either one works
5112
-     * @return string
5113
-     */
5114
-    public function get_table_for_alias($table_alias)
5115
-    {
5116
-        $table_alias_sans_model_relation_chain_prefix =
5117
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5118
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5119
-    }
5120
-
5121
-
5122
-    /**
5123
-     * Returns a flat array of all field son this model, instead of organizing them
5124
-     * by table_alias as they are in the constructor.
5125
-     *
5126
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5127
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5128
-     */
5129
-    public function field_settings($include_db_only_fields = false)
5130
-    {
5131
-        if ($include_db_only_fields) {
5132
-            if ($this->_cached_fields === null) {
5133
-                $this->_cached_fields = [];
5134
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5135
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5136
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5137
-                    }
5138
-                }
5139
-            }
5140
-            return $this->_cached_fields;
5141
-        }
5142
-        if ($this->_cached_fields_non_db_only === null) {
5143
-            $this->_cached_fields_non_db_only = [];
5144
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5145
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5146
-                    /** @var $field_obj EE_Model_Field_Base */
5147
-                    if (! $field_obj->is_db_only_field()) {
5148
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5149
-                    }
5150
-                }
5151
-            }
5152
-        }
5153
-        return $this->_cached_fields_non_db_only;
5154
-    }
5155
-
5156
-
5157
-    /**
5158
-     *        cycle though array of attendees and create objects out of each item
5159
-     *
5160
-     * @access        private
5161
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5162
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5163
-     *                           numerically indexed)
5164
-     * @throws EE_Error
5165
-     * @throws ReflectionException
5166
-     */
5167
-    protected function _create_objects($rows = [])
5168
-    {
5169
-        $array_of_objects = [];
5170
-        if (empty($rows)) {
5171
-            return [];
5172
-        }
5173
-        $count_if_model_has_no_primary_key = 0;
5174
-        $has_primary_key                   = $this->has_primary_key_field();
5175
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5176
-        foreach ((array) $rows as $row) {
5177
-            if (empty($row)) {
5178
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5179
-                return [];
5180
-            }
5181
-            // check if we've already set this object in the results array,
5182
-            // in which case there's no need to process it further (again)
5183
-            if ($has_primary_key) {
5184
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5185
-                    $row,
5186
-                    $primary_key_field->get_qualified_column(),
5187
-                    $primary_key_field->get_table_column()
5188
-                );
5189
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5190
-                    continue;
5191
-                }
5192
-            }
5193
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5194
-            if (! $classInstance) {
5195
-                throw new EE_Error(
5196
-                    sprintf(
5197
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5198
-                        $this->get_this_model_name(),
5199
-                        http_build_query($row)
5200
-                    )
5201
-                );
5202
-            }
5203
-            // set the timezone on the instantiated objects
5204
-            $classInstance->set_timezone($this->get_timezone(), true);
5205
-            // make sure if there is any timezone setting present that we set the timezone for the object
5206
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5207
-            $array_of_objects[ $key ] = $classInstance;
5208
-            // also, for all the relations of type BelongsTo, see if we can cache
5209
-            // those related models
5210
-            // (we could do this for other relations too, but if there are conditions
5211
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5212
-            // so it requires a little more thought than just caching them immediately...)
5213
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5214
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5215
-                    // check if this model's INFO is present. If so, cache it on the model
5216
-                    $other_model           = $relation_obj->get_other_model();
5217
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5218
-                    // if we managed to make a model object from the results, cache it on the main model object
5219
-                    if ($other_model_obj_maybe) {
5220
-                        // set timezone on these other model objects if they are present
5221
-                        $other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5222
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5223
-                    }
5224
-                }
5225
-            }
5226
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5227
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5228
-            // the field in the CustomSelects object
5229
-            if ($this->_custom_selections instanceof CustomSelects) {
5230
-                $classInstance->setCustomSelectsValues(
5231
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5232
-                );
5233
-            }
5234
-        }
5235
-        return $array_of_objects;
5236
-    }
5237
-
5238
-
5239
-    /**
5240
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5241
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5242
-     *
5243
-     * @param array $db_results_row
5244
-     * @return array
5245
-     */
5246
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5247
-    {
5248
-        $results = [];
5249
-        if ($this->_custom_selections instanceof CustomSelects) {
5250
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5251
-                if (isset($db_results_row[ $alias ])) {
5252
-                    $results[ $alias ] = $this->convertValueToDataType(
5253
-                        $db_results_row[ $alias ],
5254
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5255
-                    );
5256
-                }
5257
-            }
5258
-        }
5259
-        return $results;
5260
-    }
5261
-
5262
-
5263
-    /**
5264
-     * This will set the value for the given alias
5265
-     *
5266
-     * @param string $value
5267
-     * @param string $datatype (one of %d, %s, %f)
5268
-     * @return int|string|float (int for %d, string for %s, float for %f)
5269
-     */
5270
-    protected function convertValueToDataType($value, $datatype)
5271
-    {
5272
-        switch ($datatype) {
5273
-            case '%f':
5274
-                return (float) $value;
5275
-            case '%d':
5276
-                return (int) $value;
5277
-            default:
5278
-                return (string) $value;
5279
-        }
5280
-    }
5281
-
5282
-
5283
-    /**
5284
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5285
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5286
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5287
-     * object (as set in the model_field!).
5288
-     *
5289
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5290
-     * @throws EE_Error
5291
-     * @throws ReflectionException
5292
-     */
5293
-    public function create_default_object()
5294
-    {
5295
-        $this_model_fields_and_values = [];
5296
-        // setup the row using default values;
5297
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5298
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5299
-        }
5300
-        $className = $this->_get_class_name();
5301
-        return EE_Registry::instance()->load_class(
5302
-            $className,
5303
-            [$this_model_fields_and_values],
5304
-            false,
5305
-            false
5306
-        );
5307
-    }
5308
-
5309
-
5310
-    /**
5311
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5312
-     *                             or an stdClass where each property is the name of a column,
5313
-     * @return EE_Base_Class
5314
-     * @throws EE_Error
5315
-     * @throws ReflectionException
5316
-     */
5317
-    public function instantiate_class_from_array_or_object($cols_n_values)
5318
-    {
5319
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5320
-            $cols_n_values = get_object_vars($cols_n_values);
5321
-        }
5322
-        $primary_key = null;
5323
-        // make sure the array only has keys that are fields/columns on this model
5324
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5325
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5326
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5327
-        }
5328
-        $className = $this->_get_class_name();
5329
-        // check we actually found results that we can use to build our model object
5330
-        // if not, return null
5331
-        if ($this->has_primary_key_field()) {
5332
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5333
-                return null;
5334
-            }
5335
-        } elseif ($this->unique_indexes()) {
5336
-            $first_column = reset($this_model_fields_n_values);
5337
-            if (empty($first_column)) {
5338
-                return null;
5339
-            }
5340
-        }
5341
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5342
-        if ($primary_key) {
5343
-            $classInstance = $this->get_from_entity_map($primary_key);
5344
-            if (! $classInstance) {
5345
-                $classInstance = EE_Registry::instance()->load_class(
5346
-                    $className,
5347
-                    [$this_model_fields_n_values, $this->get_timezone()],
5348
-                    true,
5349
-                    false
5350
-                );
5351
-                // add this new object to the entity map
5352
-                $classInstance = $this->add_to_entity_map($classInstance);
5353
-            }
5354
-        } else {
5355
-            $classInstance = EE_Registry::instance()->load_class(
5356
-                $className,
5357
-                [$this_model_fields_n_values, $this->get_timezone()],
5358
-                true,
5359
-                false
5360
-            );
5361
-        }
5362
-        return $classInstance;
5363
-    }
5364
-
5365
-
5366
-    /**
5367
-     * Gets the model object from the  entity map if it exists
5368
-     *
5369
-     * @param int|string $id the ID of the model object
5370
-     * @return EE_Base_Class
5371
-     */
5372
-    public function get_from_entity_map($id)
5373
-    {
5374
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5375
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5376
-            : null;
5377
-    }
5378
-
5379
-
5380
-    /**
5381
-     * add_to_entity_map
5382
-     * Adds the object to the model's entity mappings
5383
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5384
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5385
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5386
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5387
-     *        then this method should be called immediately after the update query
5388
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5389
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5390
-     *
5391
-     * @param EE_Base_Class $object
5392
-     * @return EE_Base_Class
5393
-     * @throws EE_Error
5394
-     */
5395
-    public function add_to_entity_map(EE_Base_Class $object)
5396
-    {
5397
-        $className = $this->_get_class_name();
5398
-        if (! $object instanceof $className) {
5399
-            throw new EE_Error(
5400
-                sprintf(
5401
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5402
-                    is_object($object) ? get_class($object) : $object,
5403
-                    $className
5404
-                )
5405
-            );
5406
-        }
5407
-        if (! $object->ID()) {
5408
-            throw new EE_Error(
5409
-                sprintf(
5410
-                    esc_html__(
5411
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5412
-                        "event_espresso"
5413
-                    ),
5414
-                    get_class($this)
5415
-                )
5416
-            );
5417
-        }
5418
-        // double check it's not already there
5419
-        $classInstance = $this->get_from_entity_map($object->ID());
5420
-        if ($classInstance) {
5421
-            return $classInstance;
5422
-        }
5423
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5424
-        return $object;
5425
-    }
5426
-
5427
-
5428
-    /**
5429
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5430
-     * if no identifier is provided, then the entire entity map is emptied
5431
-     *
5432
-     * @param int|string $id the ID of the model object
5433
-     * @return boolean
5434
-     */
5435
-    public function clear_entity_map($id = null)
5436
-    {
5437
-        if (empty($id)) {
5438
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5439
-            return true;
5440
-        }
5441
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5442
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5443
-            return true;
5444
-        }
5445
-        return false;
5446
-    }
5447
-
5448
-
5449
-    /**
5450
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5451
-     * Given an array where keys are column (or column alias) names and values,
5452
-     * returns an array of their corresponding field names and database values
5453
-     *
5454
-     * @param array $cols_n_values
5455
-     * @return array
5456
-     */
5457
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5458
-    {
5459
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5460
-    }
5461
-
5462
-
5463
-    /**
5464
-     * _deduce_fields_n_values_from_cols_n_values
5465
-     * Given an array where keys are column (or column alias) names and values,
5466
-     * returns an array of their corresponding field names and database values
5467
-     *
5468
-     * @param array $cols_n_values
5469
-     * @return array
5470
-     */
5471
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5472
-    {
5473
-        $this_model_fields_n_values = [];
5474
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5475
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5476
-                $cols_n_values,
5477
-                $table_obj->get_fully_qualified_pk_column(),
5478
-                $table_obj->get_pk_column()
5479
-            );
5480
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5481
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5482
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5483
-                    if (! $field_obj->is_db_only_field()) {
5484
-                        // prepare field as if its coming from db
5485
-                        $prepared_value                            =
5486
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5487
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5488
-                    }
5489
-                }
5490
-            } else {
5491
-                // the table's rows existed. Use their values
5492
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5493
-                    if (! $field_obj->is_db_only_field()) {
5494
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5495
-                            $cols_n_values,
5496
-                            $field_obj->get_qualified_column(),
5497
-                            $field_obj->get_table_column()
5498
-                        );
5499
-                    }
5500
-                }
5501
-            }
5502
-        }
5503
-        return $this_model_fields_n_values;
5504
-    }
5505
-
5506
-
5507
-    /**
5508
-     * @param array  $cols_n_values
5509
-     * @param string $qualified_column
5510
-     * @param string $regular_column
5511
-     * @return null
5512
-     */
5513
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5514
-    {
5515
-        $value = null;
5516
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5517
-        // does the field on the model relate to this column retrieved from the db?
5518
-        // or is it a db-only field? (not relating to the model)
5519
-        if (isset($cols_n_values[ $qualified_column ])) {
5520
-            $value = $cols_n_values[ $qualified_column ];
5521
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5522
-            $value = $cols_n_values[ $regular_column ];
5523
-        } elseif (! empty($this->foreign_key_aliases)) {
5524
-            // no PK?  ok check if there is a foreign key alias set for this table
5525
-            // then check if that alias exists in the incoming data
5526
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5527
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5528
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5529
-                    $value = $cols_n_values[ $FK_alias ];
5530
-                    break;
5531
-                }
5532
-            }
5533
-        }
5534
-        return $value;
5535
-    }
5536
-
5537
-
5538
-    /**
5539
-     * refresh_entity_map_from_db
5540
-     * Makes sure the model object in the entity map at $id assumes the values
5541
-     * of the database (opposite of EE_base_Class::save())
5542
-     *
5543
-     * @param int|string $id
5544
-     * @return EE_Base_Class
5545
-     * @throws EE_Error
5546
-     * @throws ReflectionException
5547
-     */
5548
-    public function refresh_entity_map_from_db($id)
5549
-    {
5550
-        $obj_in_map = $this->get_from_entity_map($id);
5551
-        if ($obj_in_map) {
5552
-            $wpdb_results = $this->_get_all_wpdb_results(
5553
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5554
-            );
5555
-            if ($wpdb_results && is_array($wpdb_results)) {
5556
-                $one_row = reset($wpdb_results);
5557
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5558
-                    $obj_in_map->set_from_db($field_name, $db_value);
5559
-                }
5560
-                // clear the cache of related model objects
5561
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5562
-                    $obj_in_map->clear_cache($relation_name, null, true);
5563
-                }
5564
-            }
5565
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5566
-            return $obj_in_map;
5567
-        }
5568
-        return $this->get_one_by_ID($id);
5569
-    }
5570
-
5571
-
5572
-    /**
5573
-     * refresh_entity_map_with
5574
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5575
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5576
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5577
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5578
-     *
5579
-     * @param int|string    $id
5580
-     * @param EE_Base_Class $replacing_model_obj
5581
-     * @return EE_Base_Class
5582
-     * @throws EE_Error
5583
-     * @throws ReflectionException
5584
-     */
5585
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5586
-    {
5587
-        $obj_in_map = $this->get_from_entity_map($id);
5588
-        if ($obj_in_map) {
5589
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5590
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5591
-                    $obj_in_map->set($field_name, $value);
5592
-                }
5593
-                // make the model object in the entity map's cache match the $replacing_model_obj
5594
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5595
-                    $obj_in_map->clear_cache($relation_name, null, true);
5596
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5597
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5598
-                    }
5599
-                }
5600
-            }
5601
-            return $obj_in_map;
5602
-        }
5603
-        $this->add_to_entity_map($replacing_model_obj);
5604
-        return $replacing_model_obj;
5605
-    }
5606
-
5607
-
5608
-    /**
5609
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5610
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5611
-     * require_once($this->_getClassName().".class.php");
5612
-     *
5613
-     * @return string
5614
-     */
5615
-    private function _get_class_name()
5616
-    {
5617
-        return "EE_" . $this->get_this_model_name();
5618
-    }
5619
-
5620
-
5621
-    /**
5622
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5623
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5624
-     * it would be 'Events'.
5625
-     *
5626
-     * @param int $quantity
5627
-     * @return string
5628
-     */
5629
-    public function item_name($quantity = 1)
5630
-    {
5631
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5632
-    }
5633
-
5634
-
5635
-    /**
5636
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5637
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5638
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5639
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5640
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5641
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5642
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5643
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5644
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5645
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5646
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5647
-     *        return $previousReturnValue.$returnString;
5648
-     * }
5649
-     * require('EEM_Answer.model.php');
5650
-     * $answer=EEM_Answer::instance();
5651
-     * echo $answer->my_callback('monkeys',100);
5652
-     * //will output "you called my_callback! and passed args:monkeys,100"
5653
-     *
5654
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5655
-     * @param array  $args       array of original arguments passed to the function
5656
-     * @return mixed whatever the plugin which calls add_filter decides
5657
-     * @throws EE_Error
5658
-     */
5659
-    public function __call($methodName, $args)
5660
-    {
5661
-        $className = get_class($this);
5662
-        $tagName   = "FHEE__{$className}__{$methodName}";
5663
-        if (! has_filter($tagName)) {
5664
-            throw new EE_Error(
5665
-                sprintf(
5666
-                    esc_html__(
5667
-                        '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 );',
5668
-                        'event_espresso'
5669
-                    ),
5670
-                    $methodName,
5671
-                    $className,
5672
-                    $tagName,
5673
-                    '<br />'
5674
-                )
5675
-            );
5676
-        }
5677
-        return apply_filters($tagName, null, $this, $args);
5678
-    }
5679
-
5680
-
5681
-    /**
5682
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5683
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5684
-     *
5685
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5686
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5687
-     *                                                       the object's class name
5688
-     *                                                       or object's ID
5689
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5690
-     *                                                       exists in the database. If it does not, we add it
5691
-     * @return EE_Base_Class
5692
-     * @throws EE_Error
5693
-     * @throws ReflectionException
5694
-     */
5695
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5696
-    {
5697
-        $className = $this->_get_class_name();
5698
-        if ($base_class_obj_or_id instanceof $className) {
5699
-            $model_object = $base_class_obj_or_id;
5700
-        } else {
5701
-            $primary_key_field = $this->get_primary_key_field();
5702
-            if (
5703
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5704
-                && (
5705
-                    is_int($base_class_obj_or_id)
5706
-                    || is_string($base_class_obj_or_id)
5707
-                )
5708
-            ) {
5709
-                // assume it's an ID.
5710
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5711
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5712
-            } elseif (
5713
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5714
-                && is_string($base_class_obj_or_id)
5715
-            ) {
5716
-                // assume its a string representation of the object
5717
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5718
-            } else {
5719
-                throw new EE_Error(
5720
-                    sprintf(
5721
-                        esc_html__(
5722
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5723
-                            'event_espresso'
5724
-                        ),
5725
-                        $base_class_obj_or_id,
5726
-                        $this->_get_class_name(),
5727
-                        print_r($base_class_obj_or_id, true)
5728
-                    )
5729
-                );
5730
-            }
5731
-        }
5732
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5733
-            $model_object->save();
5734
-        }
5735
-        return $model_object;
5736
-    }
5737
-
5738
-
5739
-    /**
5740
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5741
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5742
-     * returns it ID.
5743
-     *
5744
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5745
-     * @return int|string depending on the type of this model object's ID
5746
-     * @throws EE_Error
5747
-     */
5748
-    public function ensure_is_ID($base_class_obj_or_id)
5749
-    {
5750
-        $className = $this->_get_class_name();
5751
-        if ($base_class_obj_or_id instanceof $className) {
5752
-            $id = $base_class_obj_or_id->ID();
5753
-        } elseif (is_int($base_class_obj_or_id)) {
5754
-            // assume it's an ID
5755
-            $id = $base_class_obj_or_id;
5756
-        } elseif (is_string($base_class_obj_or_id)) {
5757
-            // assume its a string representation of the object
5758
-            $id = $base_class_obj_or_id;
5759
-        } else {
5760
-            throw new EE_Error(
5761
-                sprintf(
5762
-                    esc_html__(
5763
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5764
-                        'event_espresso'
5765
-                    ),
5766
-                    $base_class_obj_or_id,
5767
-                    $this->_get_class_name(),
5768
-                    print_r($base_class_obj_or_id, true)
5769
-                )
5770
-            );
5771
-        }
5772
-        return $id;
5773
-    }
5774
-
5775
-
5776
-    /**
5777
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5778
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5779
-     * been sanitized and converted into the appropriate domain.
5780
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5781
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5782
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5783
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5784
-     * $EVT = EEM_Event::instance(); $old_setting =
5785
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5786
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5787
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5788
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5789
-     *
5790
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5791
-     * @return void
5792
-     */
5793
-    public function assume_values_already_prepared_by_model_object(
5794
-        $values_already_prepared = self::not_prepared_by_model_object
5795
-    ) {
5796
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5797
-    }
5798
-
5799
-
5800
-    /**
5801
-     * Read comments for assume_values_already_prepared_by_model_object()
5802
-     *
5803
-     * @return int
5804
-     */
5805
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
-    {
5807
-        return $this->_values_already_prepared_by_model_object;
5808
-    }
5809
-
5810
-
5811
-    /**
5812
-     * Gets all the indexes on this model
5813
-     *
5814
-     * @return EE_Index[]
5815
-     */
5816
-    public function indexes()
5817
-    {
5818
-        return $this->_indexes;
5819
-    }
5820
-
5821
-
5822
-    /**
5823
-     * Gets all the Unique Indexes on this model
5824
-     *
5825
-     * @return EE_Unique_Index[]
5826
-     */
5827
-    public function unique_indexes()
5828
-    {
5829
-        $unique_indexes = [];
5830
-        foreach ($this->_indexes as $name => $index) {
5831
-            if ($index instanceof EE_Unique_Index) {
5832
-                $unique_indexes [ $name ] = $index;
5833
-            }
5834
-        }
5835
-        return $unique_indexes;
5836
-    }
5837
-
5838
-
5839
-    /**
5840
-     * Gets all the fields which, when combined, make the primary key.
5841
-     * This is usually just an array with 1 element (the primary key), but in cases
5842
-     * where there is no primary key, it's a combination of fields as defined
5843
-     * on a primary index
5844
-     *
5845
-     * @return EE_Model_Field_Base[] indexed by the field's name
5846
-     * @throws EE_Error
5847
-     */
5848
-    public function get_combined_primary_key_fields()
5849
-    {
5850
-        foreach ($this->indexes() as $index) {
5851
-            if ($index instanceof EE_Primary_Key_Index) {
5852
-                return $index->fields();
5853
-            }
5854
-        }
5855
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5856
-    }
5857
-
5858
-
5859
-    /**
5860
-     * Used to build a primary key string (when the model has no primary key),
5861
-     * which can be used a unique string to identify this model object.
5862
-     *
5863
-     * @param array $fields_n_values keys are field names, values are their values.
5864
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5865
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5866
-     *                               before passing it to this function (that will convert it from columns-n-values
5867
-     *                               to field-names-n-values).
5868
-     * @return string
5869
-     * @throws EE_Error
5870
-     */
5871
-    public function get_index_primary_key_string($fields_n_values)
5872
-    {
5873
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5874
-            $fields_n_values,
5875
-            $this->get_combined_primary_key_fields()
5876
-        );
5877
-        return http_build_query($cols_n_values_for_primary_key_index);
5878
-    }
5879
-
5880
-
5881
-    /**
5882
-     * Gets the field values from the primary key string
5883
-     *
5884
-     * @param string $index_primary_key_string
5885
-     * @return null|array
5886
-     * @throws EE_Error
5887
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5888
-     */
5889
-    public function parse_index_primary_key_string($index_primary_key_string)
5890
-    {
5891
-        $key_fields = $this->get_combined_primary_key_fields();
5892
-        // check all of them are in the $id
5893
-        $key_values_in_combined_pk = [];
5894
-        parse_str($index_primary_key_string, $key_values_in_combined_pk);
5895
-        foreach ($key_fields as $key_field_name => $field_obj) {
5896
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5897
-                return null;
5898
-            }
5899
-        }
5900
-        return $key_values_in_combined_pk;
5901
-    }
5902
-
5903
-
5904
-    /**
5905
-     * verifies that an array of key-value pairs for model fields has a key
5906
-     * for each field comprising the primary key index
5907
-     *
5908
-     * @param array $key_values
5909
-     * @return boolean
5910
-     * @throws EE_Error
5911
-     */
5912
-    public function has_all_combined_primary_key_fields($key_values)
5913
-    {
5914
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915
-        foreach ($keys_it_should_have as $key) {
5916
-            if (! isset($key_values[ $key ])) {
5917
-                return false;
5918
-            }
5919
-        }
5920
-        return true;
5921
-    }
5922
-
5923
-
5924
-    /**
5925
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5926
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5927
-     *
5928
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5929
-     * @param array               $query_params                     see github link below for more info
5930
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5931
-     * @throws EE_Error
5932
-     * @throws ReflectionException
5933
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5934
-     *                                                              indexed)
5935
-     */
5936
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5937
-    {
5938
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5939
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5940
-        } elseif (is_array($model_object_or_attributes_array)) {
5941
-            $attributes_array = $model_object_or_attributes_array;
5942
-        } else {
5943
-            throw new EE_Error(
5944
-                sprintf(
5945
-                    esc_html__(
5946
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5947
-                        "event_espresso"
5948
-                    ),
5949
-                    $model_object_or_attributes_array
5950
-                )
5951
-            );
5952
-        }
5953
-        // even copies obviously won't have the same ID, so remove the primary key
5954
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5957
-        }
5958
-        if (isset($query_params[0])) {
5959
-            $query_params[0] = array_merge($attributes_array, $query_params);
5960
-        } else {
5961
-            $query_params[0] = $attributes_array;
5962
-        }
5963
-        return $this->get_all($query_params);
5964
-    }
5965
-
5966
-
5967
-    /**
5968
-     * Gets the first copy we find. See get_all_copies for more details
5969
-     *
5970
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5971
-     * @param array $query_params
5972
-     * @return EE_Base_Class
5973
-     * @throws EE_Error
5974
-     * @throws ReflectionException
5975
-     */
5976
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5977
-    {
5978
-        if (! is_array($query_params)) {
5979
-            EE_Error::doing_it_wrong(
5980
-                'EEM_Base::get_one_copy',
5981
-                sprintf(
5982
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
-                    gettype($query_params)
5984
-                ),
5985
-                '4.6.0'
5986
-            );
5987
-            $query_params = [];
5988
-        }
5989
-        $query_params['limit'] = 1;
5990
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
-        if (is_array($copies)) {
5992
-            return array_shift($copies);
5993
-        }
5994
-        return null;
5995
-    }
5996
-
5997
-
5998
-    /**
5999
-     * Updates the item with the specified id. Ignores default query parameters because
6000
-     * we have specified the ID, and its assumed we KNOW what we're doing
6001
-     *
6002
-     * @param array      $fields_n_values keys are field names, values are their new values
6003
-     * @param int|string $id              the value of the primary key to update
6004
-     * @return int number of rows updated
6005
-     * @throws EE_Error
6006
-     * @throws ReflectionException
6007
-     */
6008
-    public function update_by_ID($fields_n_values, $id)
6009
-    {
6010
-        $query_params = [
6011
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6012
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
-        ];
6014
-        return $this->update($fields_n_values, $query_params);
6015
-    }
6016
-
6017
-
6018
-    /**
6019
-     * Changes an operator which was supplied to the models into one usable in SQL
6020
-     *
6021
-     * @param string $operator_supplied
6022
-     * @return string an operator which can be used in SQL
6023
-     * @throws EE_Error
6024
-     */
6025
-    private function _prepare_operator_for_sql($operator_supplied)
6026
-    {
6027
-        $sql_operator =
6028
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
-                : null;
6030
-        if ($sql_operator) {
6031
-            return $sql_operator;
6032
-        }
6033
-        throw new EE_Error(
6034
-            sprintf(
6035
-                esc_html__(
6036
-                    "The operator '%s' is not in the list of valid operators: %s",
6037
-                    "event_espresso"
6038
-                ),
6039
-                $operator_supplied,
6040
-                implode(",", array_keys($this->_valid_operators))
6041
-            )
6042
-        );
6043
-    }
6044
-
6045
-
6046
-    /**
6047
-     * Gets the valid operators
6048
-     *
6049
-     * @return array keys are accepted strings, values are the SQL they are converted to
6050
-     */
6051
-    public function valid_operators()
6052
-    {
6053
-        return $this->_valid_operators;
6054
-    }
6055
-
6056
-
6057
-    /**
6058
-     * Gets the between-style operators (take 2 arguments).
6059
-     *
6060
-     * @return array keys are accepted strings, values are the SQL they are converted to
6061
-     */
6062
-    public function valid_between_style_operators()
6063
-    {
6064
-        return array_intersect(
6065
-            $this->valid_operators(),
6066
-            $this->_between_style_operators
6067
-        );
6068
-    }
6069
-
6070
-
6071
-    /**
6072
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6073
-     *
6074
-     * @return array keys are accepted strings, values are the SQL they are converted to
6075
-     */
6076
-    public function valid_like_style_operators()
6077
-    {
6078
-        return array_intersect(
6079
-            $this->valid_operators(),
6080
-            $this->_like_style_operators
6081
-        );
6082
-    }
6083
-
6084
-
6085
-    /**
6086
-     * Gets the "in"-style operators
6087
-     *
6088
-     * @return array keys are accepted strings, values are the SQL they are converted to
6089
-     */
6090
-    public function valid_in_style_operators()
6091
-    {
6092
-        return array_intersect(
6093
-            $this->valid_operators(),
6094
-            $this->_in_style_operators
6095
-        );
6096
-    }
6097
-
6098
-
6099
-    /**
6100
-     * Gets the "null"-style operators (accept no arguments)
6101
-     *
6102
-     * @return array keys are accepted strings, values are the SQL they are converted to
6103
-     */
6104
-    public function valid_null_style_operators()
6105
-    {
6106
-        return array_intersect(
6107
-            $this->valid_operators(),
6108
-            $this->_null_style_operators
6109
-        );
6110
-    }
6111
-
6112
-
6113
-    /**
6114
-     * Gets an array where keys are the primary keys and values are their 'names'
6115
-     * (as determined by the model object's name() function, which is often overridden)
6116
-     *
6117
-     * @param array $query_params like get_all's
6118
-     * @return string[]
6119
-     * @throws EE_Error
6120
-     * @throws ReflectionException
6121
-     */
6122
-    public function get_all_names($query_params = [])
6123
-    {
6124
-        $objs  = $this->get_all($query_params);
6125
-        $names = [];
6126
-        foreach ($objs as $obj) {
6127
-            $names[ $obj->ID() ] = $obj->name();
6128
-        }
6129
-        return $names;
6130
-    }
6131
-
6132
-
6133
-    /**
6134
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6135
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6136
-     * this is duplicated effort and reduces efficiency) you would be better to use
6137
-     * array_keys() on $model_objects.
6138
-     *
6139
-     * @param EE_Base_Class[] $model_objects
6140
-     * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6141
-     *                                               in the returned array
6142
-     * @return array
6143
-     * @throws EE_Error
6144
-     */
6145
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6146
-    {
6147
-        if (! $this->has_primary_key_field()) {
6148
-            if (WP_DEBUG) {
6149
-                EE_Error::add_error(
6150
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6151
-                    __FILE__,
6152
-                    __FUNCTION__,
6153
-                    __LINE__
6154
-                );
6155
-            }
6156
-        }
6157
-        $IDs = [];
6158
-        foreach ($model_objects as $model_object) {
6159
-            $id = $model_object->ID();
6160
-            if (! $id) {
6161
-                if ($filter_out_empty_ids) {
6162
-                    continue;
6163
-                }
6164
-                if (WP_DEBUG) {
6165
-                    EE_Error::add_error(
6166
-                        esc_html__(
6167
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6168
-                            'event_espresso'
6169
-                        ),
6170
-                        __FILE__,
6171
-                        __FUNCTION__,
6172
-                        __LINE__
6173
-                    );
6174
-                }
6175
-            }
6176
-            $IDs[] = $id;
6177
-        }
6178
-        return $IDs;
6179
-    }
6180
-
6181
-
6182
-    /**
6183
-     * Returns the string used in capabilities relating to this model. If there
6184
-     * are no capabilities that relate to this model returns false
6185
-     *
6186
-     * @return string|false
6187
-     */
6188
-    public function cap_slug()
6189
-    {
6190
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6191
-    }
6192
-
6193
-
6194
-    /**
6195
-     * Returns the capability-restrictions array (@param string $context
6196
-     *
6197
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6198
-     * @throws EE_Error
6199
-     * @see EEM_Base::_cap_restrictions).
6200
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6201
-     *      only returns the cap restrictions array in that context (ie, the array
6202
-     *      at that key)
6203
-     *
6204
-     */
6205
-    public function cap_restrictions($context = EEM_Base::caps_read)
6206
-    {
6207
-        EEM_Base::verify_is_valid_cap_context($context);
6208
-        // check if we ought to run the restriction generator first
6209
-        if (
6210
-            isset($this->_cap_restriction_generators[ $context ])
6211
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6212
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6213
-        ) {
6214
-            $this->_cap_restrictions[ $context ] = array_merge(
6215
-                $this->_cap_restrictions[ $context ],
6216
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6217
-            );
6218
-        }
6219
-        // and make sure we've finalized the construction of each restriction
6220
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6221
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6222
-                $where_conditions_obj->_finalize_construct($this);
6223
-            }
6224
-        }
6225
-        return $this->_cap_restrictions[ $context ];
6226
-    }
6227
-
6228
-
6229
-    /**
6230
-     * Indicating whether or not this model thinks its a wp core model
6231
-     *
6232
-     * @return boolean
6233
-     */
6234
-    public function is_wp_core_model()
6235
-    {
6236
-        return $this->_wp_core_model;
6237
-    }
6238
-
6239
-
6240
-    /**
6241
-     * Gets all the caps that are missing which impose a restriction on
6242
-     * queries made in this context
6243
-     *
6244
-     * @param string $context one of EEM_Base::caps_ constants
6245
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6246
-     * @throws EE_Error
6247
-     */
6248
-    public function caps_missing($context = EEM_Base::caps_read)
6249
-    {
6250
-        $missing_caps     = [];
6251
-        $cap_restrictions = $this->cap_restrictions($context);
6252
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6253
-            if (
6254
-            ! EE_Capabilities::instance()
6255
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6256
-            ) {
6257
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6258
-            }
6259
-        }
6260
-        return $missing_caps;
6261
-    }
6262
-
6263
-
6264
-    /**
6265
-     * Gets the mapping from capability contexts to action strings used in capability names
6266
-     *
6267
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6268
-     * one of 'read', 'edit', or 'delete'
6269
-     */
6270
-    public function cap_contexts_to_cap_action_map()
6271
-    {
6272
-        return apply_filters(
6273
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6274
-            $this->_cap_contexts_to_cap_action_map,
6275
-            $this
6276
-        );
6277
-    }
6278
-
6279
-
6280
-    /**
6281
-     * Gets the action string for the specified capability context
6282
-     *
6283
-     * @param string $context
6284
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6285
-     * @throws EE_Error
6286
-     */
6287
-    public function cap_action_for_context($context)
6288
-    {
6289
-        $mapping = $this->cap_contexts_to_cap_action_map();
6290
-        if (isset($mapping[ $context ])) {
6291
-            return $mapping[ $context ];
6292
-        }
6293
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6294
-            return $action;
6295
-        }
6296
-        throw new EE_Error(
6297
-            sprintf(
6298
-                esc_html__(
6299
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6300
-                    'event_espresso'
6301
-                ),
6302
-                $context,
6303
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6304
-            )
6305
-        );
6306
-    }
6307
-
6308
-
6309
-    /**
6310
-     * Returns all the capability contexts which are valid when querying models
6311
-     *
6312
-     * @return array
6313
-     */
6314
-    public static function valid_cap_contexts()
6315
-    {
6316
-        return apply_filters(
6317
-            'FHEE__EEM_Base__valid_cap_contexts',
6318
-            [
6319
-                self::caps_read,
6320
-                self::caps_read_admin,
6321
-                self::caps_edit,
6322
-                self::caps_delete,
6323
-            ]
6324
-        );
6325
-    }
6326
-
6327
-
6328
-    /**
6329
-     * Returns all valid options for 'default_where_conditions'
6330
-     *
6331
-     * @return array
6332
-     */
6333
-    public static function valid_default_where_conditions()
6334
-    {
6335
-        return [
6336
-            EEM_Base::default_where_conditions_all,
6337
-            EEM_Base::default_where_conditions_this_only,
6338
-            EEM_Base::default_where_conditions_others_only,
6339
-            EEM_Base::default_where_conditions_minimum_all,
6340
-            EEM_Base::default_where_conditions_minimum_others,
6341
-            EEM_Base::default_where_conditions_none,
6342
-        ];
6343
-    }
6344
-
6345
-    // public static function default_where_conditions_full
6346
-
6347
-
6348
-    /**
6349
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6350
-     *
6351
-     * @param string $context
6352
-     * @return bool
6353
-     * @throws EE_Error
6354
-     */
6355
-    public static function verify_is_valid_cap_context($context)
6356
-    {
6357
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6358
-        if (in_array($context, $valid_cap_contexts)) {
6359
-            return true;
6360
-        }
6361
-        throw new EE_Error(
6362
-            sprintf(
6363
-                esc_html__(
6364
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6365
-                    'event_espresso'
6366
-                ),
6367
-                $context,
6368
-                'EEM_Base',
6369
-                implode(',', $valid_cap_contexts)
6370
-            )
6371
-        );
6372
-    }
6373
-
6374
-
6375
-    /**
6376
-     * Clears all the models field caches. This is only useful when a sub-class
6377
-     * might have added a field or something and these caches might be invalidated
6378
-     */
6379
-    protected function _invalidate_field_caches()
6380
-    {
6381
-        $this->_cache_foreign_key_to_fields = [];
6382
-        $this->_cached_fields               = null;
6383
-        $this->_cached_fields_non_db_only   = null;
6384
-    }
6385
-
6386
-
6387
-    /**
6388
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6389
-     * (eg "and", "or", "not").
6390
-     *
6391
-     * @return array
6392
-     */
6393
-    public function logic_query_param_keys()
6394
-    {
6395
-        return $this->_logic_query_param_keys;
6396
-    }
6397
-
6398
-
6399
-    /**
6400
-     * Determines whether or not the where query param array key is for a logic query param.
6401
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6402
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6403
-     *
6404
-     * @param $query_param_key
6405
-     * @return bool
6406
-     */
6407
-    public function is_logic_query_param_key($query_param_key)
6408
-    {
6409
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6410
-            if (
6411
-                $query_param_key === $logic_query_param_key
6412
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6413
-            ) {
6414
-                return true;
6415
-            }
6416
-        }
6417
-        return false;
6418
-    }
6419
-
6420
-
6421
-    /**
6422
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6423
-     *
6424
-     * @return boolean
6425
-     * @since 4.9.74.p
6426
-     */
6427
-    public function hasPassword()
6428
-    {
6429
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6430
-        if ($this->has_password_field === null) {
6431
-            $password_field           = $this->getPasswordField();
6432
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6433
-        }
6434
-        return $this->has_password_field;
6435
-    }
6436
-
6437
-
6438
-    /**
6439
-     * Returns the password field on this model, if there is one
6440
-     *
6441
-     * @return EE_Password_Field|null
6442
-     * @since 4.9.74.p
6443
-     */
6444
-    public function getPasswordField()
6445
-    {
6446
-        // if we definitely already know there is a password field or not (because has_password_field is true or false)
6447
-        // there's no need to search for it. If we don't know yet, then find out
6448
-        if ($this->has_password_field === null && $this->password_field === null) {
6449
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6450
-        }
6451
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6452
-        return $this->password_field;
6453
-    }
6454
-
6455
-
6456
-    /**
6457
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6458
-     *
6459
-     * @return EE_Model_Field_Base[]
6460
-     * @throws EE_Error
6461
-     * @since 4.9.74.p
6462
-     */
6463
-    public function getPasswordProtectedFields()
6464
-    {
6465
-        $password_field = $this->getPasswordField();
6466
-        $fields         = [];
6467
-        if ($password_field instanceof EE_Password_Field) {
6468
-            $field_names = $password_field->protectedFields();
6469
-            foreach ($field_names as $field_name) {
6470
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6471
-            }
6472
-        }
6473
-        return $fields;
6474
-    }
6475
-
6476
-
6477
-    /**
6478
-     * Checks if the current user can perform the requested action on this model
6479
-     *
6480
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6481
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6482
-     * @return bool
6483
-     * @throws EE_Error
6484
-     * @throws InvalidArgumentException
6485
-     * @throws InvalidDataTypeException
6486
-     * @throws InvalidInterfaceException
6487
-     * @throws ReflectionException
6488
-     * @throws UnexpectedEntityException
6489
-     * @since 4.9.74.p
6490
-     */
6491
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6492
-    {
6493
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6494
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6495
-        }
6496
-        if (! is_array($model_obj_or_fields_n_values)) {
6497
-            throw new UnexpectedEntityException(
6498
-                $model_obj_or_fields_n_values,
6499
-                'EE_Base_Class',
6500
-                sprintf(
6501
-                    esc_html__(
6502
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6503
-                        'event_espresso'
6504
-                    ),
6505
-                    __FUNCTION__
6506
-                )
6507
-            );
6508
-        }
6509
-        return $this->exists(
6510
-            $this->alter_query_params_to_restrict_by_ID(
6511
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6512
-                [
6513
-                    'default_where_conditions' => 'none',
6514
-                    'caps'                     => $cap_to_check,
6515
-                ]
6516
-            )
6517
-        );
6518
-    }
6519
-
6520
-
6521
-    /**
6522
-     * Returns the query param where conditions key to the password affecting this model.
6523
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6524
-     *
6525
-     * @return null|string
6526
-     * @throws EE_Error
6527
-     * @throws InvalidArgumentException
6528
-     * @throws InvalidDataTypeException
6529
-     * @throws InvalidInterfaceException
6530
-     * @throws ModelConfigurationException
6531
-     * @throws ReflectionException
6532
-     * @since 4.9.74.p
6533
-     */
6534
-    public function modelChainAndPassword()
6535
-    {
6536
-        if ($this->model_chain_to_password === null) {
6537
-            throw new ModelConfigurationException(
6538
-                $this,
6539
-                esc_html_x(
6540
-                // @codingStandardsIgnoreStart
6541
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6542
-                    // @codingStandardsIgnoreEnd
6543
-                    '1: model name',
6544
-                    'event_espresso'
6545
-                )
6546
-            );
6547
-        }
6548
-        if ($this->model_chain_to_password === '') {
6549
-            $model_with_password = $this;
6550
-        } else {
6551
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6552
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6553
-            } else {
6554
-                $last_model_in_chain = $this->model_chain_to_password;
6555
-            }
6556
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6557
-        }
6558
-
6559
-        $password_field = $model_with_password->getPasswordField();
6560
-        if ($password_field instanceof EE_Password_Field) {
6561
-            $password_field_name = $password_field->get_name();
6562
-        } else {
6563
-            throw new ModelConfigurationException(
6564
-                $this,
6565
-                sprintf(
6566
-                    esc_html_x(
6567
-                        '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"',
6568
-                        '1: model name, 2: special string',
6569
-                        'event_espresso'
6570
-                    ),
6571
-                    $model_with_password->get_this_model_name(),
6572
-                    $this->model_chain_to_password
6573
-                )
6574
-            );
6575
-        }
6576
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6577
-    }
6578
-
6579
-
6580
-    /**
6581
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6582
-     * or if this model itself has a password affecting access to some of its other fields.
6583
-     *
6584
-     * @return boolean
6585
-     * @since 4.9.74.p
6586
-     */
6587
-    public function restrictedByRelatedModelPassword()
6588
-    {
6589
-        return $this->model_chain_to_password !== null;
6590
-    }
3868
+		}
3869
+		return $null_friendly_where_conditions;
3870
+	}
3871
+
3872
+
3873
+	/**
3874
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3875
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3876
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3878
+	 *
3879
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
+	 * @return array
3881
+	 * @throws EE_Error
3882
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3883
+	 */
3884
+	private function _get_default_where_conditions($model_relation_path = '')
3885
+	{
3886
+		if ($this->_ignore_where_strategy) {
3887
+			return [];
3888
+		}
3889
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3890
+	}
3891
+
3892
+
3893
+	/**
3894
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3895
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3896
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3897
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3898
+	 * Similar to _get_default_where_conditions
3899
+	 *
3900
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3901
+	 * @return array
3902
+	 * @throws EE_Error
3903
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3904
+	 */
3905
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3906
+	{
3907
+		if ($this->_ignore_where_strategy) {
3908
+			return [];
3909
+		}
3910
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3911
+	}
3912
+
3913
+
3914
+	/**
3915
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3916
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3917
+	 *
3918
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3919
+	 * @return string
3920
+	 * @throws EE_Error
3921
+	 */
3922
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3923
+	{
3924
+		$selects = $this->_get_columns_to_select_for_this_model();
3925
+		foreach (
3926
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3927
+		) {
3928
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3929
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3930
+			foreach ($other_model_selects as $key => $value) {
3931
+				$selects[] = $value;
3932
+			}
3933
+		}
3934
+		return implode(", ", $selects);
3935
+	}
3936
+
3937
+
3938
+	/**
3939
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3940
+	 * So that's going to be the columns for all the fields on the model
3941
+	 *
3942
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3943
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3944
+	 */
3945
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3946
+	{
3947
+		$fields                                       = $this->field_settings();
3948
+		$selects                                      = [];
3949
+		$table_alias_with_model_relation_chain_prefix =
3950
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3951
+				$model_relation_chain,
3952
+				$this->get_this_model_name()
3953
+			);
3954
+		foreach ($fields as $field_obj) {
3955
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3956
+						 . $field_obj->get_table_alias()
3957
+						 . "."
3958
+						 . $field_obj->get_table_column()
3959
+						 . " AS '"
3960
+						 . $table_alias_with_model_relation_chain_prefix
3961
+						 . $field_obj->get_table_alias()
3962
+						 . "."
3963
+						 . $field_obj->get_table_column()
3964
+						 . "'";
3965
+		}
3966
+		// make sure we are also getting the PKs of each table
3967
+		$tables = $this->get_tables();
3968
+		if (count($tables) > 1) {
3969
+			foreach ($tables as $table_obj) {
3970
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3971
+									   . $table_obj->get_fully_qualified_pk_column();
3972
+				if (! in_array($qualified_pk_column, $selects)) {
3973
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3974
+				}
3975
+			}
3976
+		}
3977
+		return $selects;
3978
+	}
3979
+
3980
+
3981
+	/**
3982
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3983
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3984
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3985
+	 * SQL for joining, and the data types
3986
+	 *
3987
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3988
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3990
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3991
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3992
+	 *                                                          or 'Registration's
3993
+	 * @param string|null                 $original_query_param what it originally was (eg
3994
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3995
+	 *                                                          matches $query_param
3996
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
+	 * @throws EE_Error
3998
+	 */
3999
+	private function _extract_related_model_info_from_query_param(
4000
+		$query_param,
4001
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4002
+		$query_param_type,
4003
+		$original_query_param = null
4004
+	) {
4005
+		if ($original_query_param === null) {
4006
+			$original_query_param = $query_param;
4007
+		}
4008
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4009
+		// whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4010
+		$allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4011
+		$allow_fields             = in_array(
4012
+			$query_param_type,
4013
+			['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4014
+			true
4015
+		);
4016
+		// check to see if we have a field on this model
4017
+		$this_model_fields = $this->field_settings(true);
4018
+		if (array_key_exists($query_param, $this_model_fields)) {
4019
+			if ($allow_fields) {
4020
+				return;
4021
+			}
4022
+			throw new EE_Error(
4023
+				sprintf(
4024
+					esc_html__(
4025
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4026
+						"event_espresso"
4027
+					),
4028
+					$query_param,
4029
+					get_class($this),
4030
+					$query_param_type,
4031
+					$original_query_param
4032
+				)
4033
+			);
4034
+		}
4035
+		// check if this is a special logic query param
4036
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4037
+			if ($allow_logic_query_params) {
4038
+				return;
4039
+			}
4040
+			throw new EE_Error(
4041
+				sprintf(
4042
+					esc_html__(
4043
+						'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',
4044
+						'event_espresso'
4045
+					),
4046
+					implode('", "', $this->_logic_query_param_keys),
4047
+					$query_param,
4048
+					get_class($this),
4049
+					'<br />',
4050
+					"\t"
4051
+					. ' $passed_in_query_info = <pre>'
4052
+					. print_r($passed_in_query_info, true)
4053
+					. '</pre>'
4054
+					. "\n\t"
4055
+					. ' $query_param_type = '
4056
+					. $query_param_type
4057
+					. "\n\t"
4058
+					. ' $original_query_param = '
4059
+					. $original_query_param
4060
+				)
4061
+			);
4062
+		}
4063
+		// check if it's a custom selection
4064
+		if (
4065
+			$this->_custom_selections instanceof CustomSelects
4066
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4067
+		) {
4068
+			return;
4069
+		}
4070
+		// check if has a model name at the beginning
4071
+		// and
4072
+		// check if it's a field on a related model
4073
+		if (
4074
+		$this->extractJoinModelFromQueryParams(
4075
+			$passed_in_query_info,
4076
+			$query_param,
4077
+			$original_query_param,
4078
+			$query_param_type
4079
+		)
4080
+		) {
4081
+			return;
4082
+		}
4083
+
4084
+		// ok so $query_param didn't start with a model name
4085
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4086
+		// it's wack, that's what it is
4087
+		throw new EE_Error(
4088
+			sprintf(
4089
+				esc_html__(
4090
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4091
+					"event_espresso"
4092
+				),
4093
+				$query_param,
4094
+				get_class($this),
4095
+				$query_param_type,
4096
+				$original_query_param
4097
+			)
4098
+		);
4099
+	}
4100
+
4101
+
4102
+	/**
4103
+	 * Extracts any possible join model information from the provided possible_join_string.
4104
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4105
+	 * join
4106
+	 * parts that should be added to the query.
4107
+	 *
4108
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4109
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4110
+	 * @param null|string                 $original_query_param
4111
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4112
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4113
+	 *                                                           etc.)
4114
+	 * @return bool  returns true if a join was added and false if not.
4115
+	 * @throws EE_Error
4116
+	 */
4117
+	private function extractJoinModelFromQueryParams(
4118
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4119
+		$possible_join_string,
4120
+		$original_query_param,
4121
+		$query_parameter_type
4122
+	) {
4123
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4124
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4125
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4126
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4127
+				if ($possible_join_string === '') {
4128
+					// nothing left to $query_param
4129
+					// we should actually end in a field name, not a model like this!
4130
+					throw new EE_Error(
4131
+						sprintf(
4132
+							esc_html__(
4133
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4134
+								"event_espresso"
4135
+							),
4136
+							$possible_join_string,
4137
+							$query_parameter_type,
4138
+							get_class($this),
4139
+							$valid_related_model_name
4140
+						)
4141
+					);
4142
+				}
4143
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4144
+				$related_model_obj->_extract_related_model_info_from_query_param(
4145
+					$possible_join_string,
4146
+					$query_info_carrier,
4147
+					$query_parameter_type,
4148
+					$original_query_param
4149
+				);
4150
+				return true;
4151
+			}
4152
+			if ($possible_join_string === $valid_related_model_name) {
4153
+				$this->_add_join_to_model(
4154
+					$valid_related_model_name,
4155
+					$query_info_carrier,
4156
+					$original_query_param
4157
+				);
4158
+				return true;
4159
+			}
4160
+		}
4161
+		return false;
4162
+	}
4163
+
4164
+
4165
+	/**
4166
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4167
+	 *
4168
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4169
+	 * @throws EE_Error
4170
+	 */
4171
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4172
+	{
4173
+		if (
4174
+			$this->_custom_selections instanceof CustomSelects
4175
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4176
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4177
+			)
4178
+		) {
4179
+			$original_selects = $this->_custom_selections->originalSelects();
4180
+			foreach ($original_selects as $alias => $select_configuration) {
4181
+				$this->extractJoinModelFromQueryParams(
4182
+					$query_info_carrier,
4183
+					$select_configuration[0],
4184
+					$select_configuration[0],
4185
+					'custom_selects'
4186
+				);
4187
+			}
4188
+		}
4189
+	}
4190
+
4191
+
4192
+	/**
4193
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4194
+	 * and store it on $passed_in_query_info
4195
+	 *
4196
+	 * @param string                      $model_name
4197
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4198
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4199
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4200
+	 *                                                          and are adding a join to 'Payment' with the original
4201
+	 *                                                          query param key
4202
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4203
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4204
+	 *                                                          Payment wants to add default query params so that it
4205
+	 *                                                          will know what models to prepend onto its default query
4206
+	 *                                                          params or in case it wants to rename tables (in case
4207
+	 *                                                          there are multiple joins to the same table)
4208
+	 * @return void
4209
+	 * @throws EE_Error
4210
+	 */
4211
+	private function _add_join_to_model(
4212
+		$model_name,
4213
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4214
+		$original_query_param
4215
+	) {
4216
+		$relation_obj         = $this->related_settings_for($model_name);
4217
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4218
+		// check if the relation is HABTM, because then we're essentially doing two joins
4219
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4220
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4221
+			$join_model_obj = $relation_obj->get_join_model();
4222
+			// replace the model specified with the join model for this relation chain, whi
4223
+			$relation_chain_to_join_model =
4224
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4225
+					$model_name,
4226
+					$join_model_obj->get_this_model_name(),
4227
+					$model_relation_chain
4228
+				);
4229
+			$passed_in_query_info->merge(
4230
+				new EE_Model_Query_Info_Carrier(
4231
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4232
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4233
+				)
4234
+			);
4235
+		}
4236
+		// now just join to the other table pointed to by the relation object, and add its data types
4237
+		$passed_in_query_info->merge(
4238
+			new EE_Model_Query_Info_Carrier(
4239
+				[$model_relation_chain => $model_name],
4240
+				$relation_obj->get_join_statement($model_relation_chain)
4241
+			)
4242
+		);
4243
+	}
4244
+
4245
+
4246
+	/**
4247
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4248
+	 *
4249
+	 * @param array $where_params
4250
+	 * @return string of SQL
4251
+	 * @throws EE_Error
4252
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4253
+	 */
4254
+	private function _construct_where_clause($where_params)
4255
+	{
4256
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4257
+		if ($SQL) {
4258
+			return " WHERE " . $SQL;
4259
+		}
4260
+		return '';
4261
+	}
4262
+
4263
+
4264
+	/**
4265
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4266
+	 * and should be passed HAVING parameters, not WHERE parameters
4267
+	 *
4268
+	 * @param array $having_params
4269
+	 * @return string
4270
+	 * @throws EE_Error
4271
+	 */
4272
+	private function _construct_having_clause($having_params)
4273
+	{
4274
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4275
+		if ($SQL) {
4276
+			return " HAVING " . $SQL;
4277
+		}
4278
+		return '';
4279
+	}
4280
+
4281
+
4282
+	/**
4283
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4284
+	 * Event_Meta.meta_value = 'foo'))"
4285
+	 *
4286
+	 * @param array  $where_params
4287
+	 * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4288
+	 * @return string of SQL
4289
+	 * @throws EE_Error
4290
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4291
+	 */
4292
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4293
+	{
4294
+		$where_clauses = [];
4295
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4296
+			$query_param =
4297
+				$this->_remove_stars_and_anything_after_from_condition_query_param_key(
4298
+					$query_param
4299
+				);// str_replace("*",'',$query_param);
4300
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4301
+				switch ($query_param) {
4302
+					case 'not':
4303
+					case 'NOT':
4304
+						$where_clauses[] = "! ("
4305
+										   . $this->_construct_condition_clause_recursive(
4306
+								$op_and_value_or_sub_condition,
4307
+								$glue
4308
+							)
4309
+										   . ")";
4310
+						break;
4311
+					case 'and':
4312
+					case 'AND':
4313
+						$where_clauses[] = " ("
4314
+										   . $this->_construct_condition_clause_recursive(
4315
+								$op_and_value_or_sub_condition,
4316
+								' AND '
4317
+							)
4318
+										   . ")";
4319
+						break;
4320
+					case 'or':
4321
+					case 'OR':
4322
+						$where_clauses[] = " ("
4323
+										   . $this->_construct_condition_clause_recursive(
4324
+								$op_and_value_or_sub_condition,
4325
+								' OR '
4326
+							)
4327
+										   . ")";
4328
+						break;
4329
+				}
4330
+			} else {
4331
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4332
+				// if it's not a normal field, maybe it's a custom selection?
4333
+				if (! $field_obj) {
4334
+					if ($this->_custom_selections instanceof CustomSelects) {
4335
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4336
+					} else {
4337
+						throw new EE_Error(
4338
+							sprintf(
4339
+								esc_html__(
4340
+									"%s is neither a valid model field name, nor a custom selection",
4341
+									"event_espresso"
4342
+								),
4343
+								$query_param
4344
+							)
4345
+						);
4346
+					}
4347
+				}
4348
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4349
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4350
+			}
4351
+		}
4352
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4353
+	}
4354
+
4355
+
4356
+	/**
4357
+	 * Takes the input parameter and extract the table name (alias) and column name
4358
+	 *
4359
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4360
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4361
+	 * @throws EE_Error
4362
+	 */
4363
+	private function _deduce_column_name_from_query_param($query_param)
4364
+	{
4365
+		$field = $this->_deduce_field_from_query_param($query_param);
4366
+		if ($field) {
4367
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4368
+				$field->get_model_name(),
4369
+				$query_param
4370
+			);
4371
+			return $table_alias_prefix . $field->get_qualified_column();
4372
+		}
4373
+		if (
4374
+			$this->_custom_selections instanceof CustomSelects
4375
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4376
+		) {
4377
+			// maybe it's custom selection item?
4378
+			// if so, just use it as the "column name"
4379
+			return $query_param;
4380
+		}
4381
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4382
+			? implode(',', $this->_custom_selections->columnAliases())
4383
+			: '';
4384
+		throw new EE_Error(
4385
+			sprintf(
4386
+				esc_html__(
4387
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4388
+					"event_espresso"
4389
+				),
4390
+				$query_param,
4391
+				$custom_select_aliases
4392
+			)
4393
+		);
4394
+	}
4395
+
4396
+
4397
+	/**
4398
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4399
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4400
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4401
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4402
+	 *
4403
+	 * @param string $condition_query_param_key
4404
+	 * @return string
4405
+	 */
4406
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4407
+	{
4408
+		$pos_of_star = strpos($condition_query_param_key, '*');
4409
+		if ($pos_of_star === false) {
4410
+			return $condition_query_param_key;
4411
+		}
4412
+		return substr($condition_query_param_key, 0, $pos_of_star);
4413
+	}
4414
+
4415
+
4416
+	/**
4417
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4418
+	 *
4419
+	 * @param mixed      array | string    $op_and_value
4420
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4421
+	 * @return string
4422
+	 * @throws EE_Error
4423
+	 */
4424
+	private function _construct_op_and_value($op_and_value, $field_obj)
4425
+	{
4426
+		if (is_array($op_and_value)) {
4427
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4428
+			if (! $operator) {
4429
+				$php_array_like_string = [];
4430
+				foreach ($op_and_value as $key => $value) {
4431
+					$php_array_like_string[] = "$key=>$value";
4432
+				}
4433
+				throw new EE_Error(
4434
+					sprintf(
4435
+						esc_html__(
4436
+							"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))",
4437
+							"event_espresso"
4438
+						),
4439
+						implode(",", $php_array_like_string)
4440
+					)
4441
+				);
4442
+			}
4443
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4444
+		} else {
4445
+			$operator = '=';
4446
+			$value    = $op_and_value;
4447
+		}
4448
+		// check to see if the value is actually another field
4449
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4450
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4451
+		}
4452
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4453
+			// in this case, the value should be an array, or at least a comma-separated list
4454
+			// it will need to handle a little differently
4455
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4456
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4457
+			return $operator . SP . $cleaned_value;
4458
+		}
4459
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4460
+			// the value should be an array with count of two.
4461
+			if (count($value) !== 2) {
4462
+				throw new EE_Error(
4463
+					sprintf(
4464
+						esc_html__(
4465
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4466
+							'event_espresso'
4467
+						),
4468
+						"BETWEEN"
4469
+					)
4470
+				);
4471
+			}
4472
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4473
+			return $operator . SP . $cleaned_value;
4474
+		}
4475
+		if (in_array($operator, $this->valid_null_style_operators())) {
4476
+			if ($value !== null) {
4477
+				throw new EE_Error(
4478
+					sprintf(
4479
+						esc_html__(
4480
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4481
+							"event_espresso"
4482
+						),
4483
+						$value,
4484
+						$operator
4485
+					)
4486
+				);
4487
+			}
4488
+			return $operator;
4489
+		}
4490
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4491
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4492
+			// remove other junk. So just treat it as a string.
4493
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4494
+		}
4495
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4496
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4497
+		}
4498
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4499
+			throw new EE_Error(
4500
+				sprintf(
4501
+					esc_html__(
4502
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4503
+						'event_espresso'
4504
+					),
4505
+					$operator,
4506
+					$operator
4507
+				)
4508
+			);
4509
+		}
4510
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4511
+			throw new EE_Error(
4512
+				sprintf(
4513
+					esc_html__(
4514
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4515
+						'event_espresso'
4516
+					),
4517
+					$operator,
4518
+					$operator
4519
+				)
4520
+			);
4521
+		}
4522
+		throw new EE_Error(
4523
+			sprintf(
4524
+				esc_html__(
4525
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4526
+					"event_espresso"
4527
+				),
4528
+				http_build_query($op_and_value)
4529
+			)
4530
+		);
4531
+	}
4532
+
4533
+
4534
+	/**
4535
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4536
+	 *
4537
+	 * @param array                      $values
4538
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4539
+	 *                                              '%s'
4540
+	 * @return string
4541
+	 * @throws EE_Error
4542
+	 */
4543
+	public function _construct_between_value($values, $field_obj)
4544
+	{
4545
+		$cleaned_values = [];
4546
+		foreach ($values as $value) {
4547
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4548
+		}
4549
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4550
+	}
4551
+
4552
+
4553
+	/**
4554
+	 * Takes an array or a comma-separated list of $values and cleans them
4555
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4556
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4557
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4558
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4559
+	 *
4560
+	 * @param mixed                      $values    array or comma-separated string
4561
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4562
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4563
+	 * @throws EE_Error
4564
+	 */
4565
+	public function _construct_in_value($values, $field_obj)
4566
+	{
4567
+		// check if the value is a CSV list
4568
+		if (is_string($values)) {
4569
+			// in which case, turn it into an array
4570
+			$values = explode(",", $values);
4571
+		}
4572
+		$cleaned_values = [];
4573
+		foreach ($values as $value) {
4574
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4575
+		}
4576
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4577
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4578
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4579
+		if (empty($cleaned_values)) {
4580
+			$all_fields       = $this->field_settings();
4581
+			$a_field          = array_shift($all_fields);
4582
+			$main_table       = $this->_get_main_table();
4583
+			$cleaned_values[] = "SELECT "
4584
+								. $a_field->get_table_column()
4585
+								. " FROM "
4586
+								. $main_table->get_table_name()
4587
+								. " WHERE FALSE";
4588
+		}
4589
+		return "(" . implode(",", $cleaned_values) . ")";
4590
+	}
4591
+
4592
+
4593
+	/**
4594
+	 * @param mixed                      $value
4595
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4596
+	 * @return false|null|string
4597
+	 * @throws EE_Error
4598
+	 */
4599
+	private function _wpdb_prepare_using_field($value, $field_obj)
4600
+	{
4601
+		global $wpdb;
4602
+		if ($field_obj instanceof EE_Model_Field_Base) {
4603
+			return $wpdb->prepare(
4604
+				$field_obj->get_wpdb_data_type(),
4605
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4606
+			);
4607
+		} //$field_obj should really just be a data type
4608
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4609
+			throw new EE_Error(
4610
+				sprintf(
4611
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4612
+					$field_obj,
4613
+					implode(",", $this->_valid_wpdb_data_types)
4614
+				)
4615
+			);
4616
+		}
4617
+		return $wpdb->prepare($field_obj, $value);
4618
+	}
4619
+
4620
+
4621
+	/**
4622
+	 * Takes the input parameter and finds the model field that it indicates.
4623
+	 *
4624
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4625
+	 * @return EE_Model_Field_Base
4626
+	 * @throws EE_Error
4627
+	 */
4628
+	protected function _deduce_field_from_query_param($query_param_name)
4629
+	{
4630
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4631
+		// which will help us find the database table and column
4632
+		$query_param_parts = explode(".", $query_param_name);
4633
+		if (empty($query_param_parts)) {
4634
+			throw new EE_Error(
4635
+				sprintf(
4636
+					esc_html__(
4637
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4638
+						'event_espresso'
4639
+					),
4640
+					$query_param_name
4641
+				)
4642
+			);
4643
+		}
4644
+		$number_of_parts       = count($query_param_parts);
4645
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4646
+		if ($number_of_parts === 1) {
4647
+			$field_name = $last_query_param_part;
4648
+			$model_obj  = $this;
4649
+		} else {// $number_of_parts >= 2
4650
+			// the last part is the column name, and there are only 2parts. therefore...
4651
+			$field_name = $last_query_param_part;
4652
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4653
+		}
4654
+		try {
4655
+			return $model_obj->field_settings_for($field_name);
4656
+		} catch (EE_Error $e) {
4657
+			return null;
4658
+		}
4659
+	}
4660
+
4661
+
4662
+	/**
4663
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4664
+	 * alias and column which corresponds to it
4665
+	 *
4666
+	 * @param string $field_name
4667
+	 * @return string
4668
+	 * @throws EE_Error
4669
+	 */
4670
+	public function _get_qualified_column_for_field($field_name)
4671
+	{
4672
+		$all_fields = $this->field_settings();
4673
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4674
+		if ($field) {
4675
+			return $field->get_qualified_column();
4676
+		}
4677
+		throw new EE_Error(
4678
+			sprintf(
4679
+				esc_html__(
4680
+					"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.",
4681
+					'event_espresso'
4682
+				),
4683
+				$field_name,
4684
+				get_class($this)
4685
+			)
4686
+		);
4687
+	}
4688
+
4689
+
4690
+	/**
4691
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4692
+	 * Example usage:
4693
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4694
+	 *      array(),
4695
+	 *      ARRAY_A,
4696
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4697
+	 *  );
4698
+	 * is equivalent to
4699
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4700
+	 * and
4701
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4702
+	 *      array(
4703
+	 *          array(
4704
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4705
+	 *          ),
4706
+	 *          ARRAY_A,
4707
+	 *          implode(
4708
+	 *              ', ',
4709
+	 *              array_merge(
4710
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4711
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4712
+	 *              )
4713
+	 *          )
4714
+	 *      )
4715
+	 *  );
4716
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4717
+	 *
4718
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4719
+	 *                                            and the one whose fields you are selecting for example: when querying
4720
+	 *                                            tickets model and selecting fields from the tickets model you would
4721
+	 *                                            leave this parameter empty, because no models are needed to join
4722
+	 *                                            between the queried model and the selected one. Likewise when
4723
+	 *                                            querying the datetime model and selecting fields from the tickets
4724
+	 *                                            model, it would also be left empty, because there is a direct
4725
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4726
+	 *                                            them together. However, when querying from the event model and
4727
+	 *                                            selecting fields from the ticket model, you should provide the string
4728
+	 *                                            'Datetime', indicating that the event model must first join to the
4729
+	 *                                            datetime model in order to find its relation to ticket model.
4730
+	 *                                            Also, when querying from the venue model and selecting fields from
4731
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4732
+	 *                                            indicating you need to join the venue model to the event model,
4733
+	 *                                            to the datetime model, in order to find its relation to the ticket
4734
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4735
+	 *                                            the models' tables qualified columns
4736
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4737
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4738
+	 *                                            qualified column names
4739
+	 * @return array|string
4740
+	 */
4741
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4742
+	{
4743
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4744
+		$qualified_columns = [];
4745
+		foreach ($this->field_settings() as $field_name => $field) {
4746
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4747
+		}
4748
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4749
+	}
4750
+
4751
+
4752
+	/**
4753
+	 * constructs the select use on special limit joins
4754
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4755
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4756
+	 * (as that is typically where the limits would be set).
4757
+	 *
4758
+	 * @param string       $table_alias The table the select is being built for
4759
+	 * @param mixed|string $limit       The limit for this select
4760
+	 * @return string                The final select join element for the query.
4761
+	 * @throws EE_Error
4762
+	 */
4763
+	public function _construct_limit_join_select($table_alias, $limit)
4764
+	{
4765
+		$SQL = '';
4766
+		foreach ($this->_tables as $table_obj) {
4767
+			if ($table_obj instanceof EE_Primary_Table) {
4768
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4769
+					? $table_obj->get_select_join_limit($limit)
4770
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4771
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4772
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4773
+					? $table_obj->get_select_join_limit_join($limit)
4774
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4775
+			}
4776
+		}
4777
+		return $SQL;
4778
+	}
4779
+
4780
+
4781
+	/**
4782
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4783
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4784
+	 *
4785
+	 * @return string SQL
4786
+	 * @throws EE_Error
4787
+	 */
4788
+	public function _construct_internal_join()
4789
+	{
4790
+		$SQL = $this->_get_main_table()->get_table_sql();
4791
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4792
+		return $SQL;
4793
+	}
4794
+
4795
+
4796
+	/**
4797
+	 * Constructs the SQL for joining all the tables on this model.
4798
+	 * Normally $alias should be the primary table's alias, but in cases where
4799
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4800
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4801
+	 * alias, this will construct SQL like:
4802
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4803
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4804
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4805
+	 *
4806
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4807
+	 * @return string
4808
+	 * @throws EE_Error
4809
+	 */
4810
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4811
+	{
4812
+		$SQL               = '';
4813
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4814
+		foreach ($this->_tables as $table_obj) {
4815
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4816
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4817
+					// so we're joining to this table, meaning the table is already in
4818
+					// the FROM statement, BUT the primary table isn't. So we want
4819
+					// to add the inverse join sql
4820
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4821
+				} else {
4822
+					// just add a regular JOIN to this table from the primary table
4823
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4824
+				}
4825
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4826
+		}
4827
+		return $SQL;
4828
+	}
4829
+
4830
+
4831
+	/**
4832
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4833
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4834
+	 * their data type (eg, '%s', '%d', etc)
4835
+	 *
4836
+	 * @return array
4837
+	 */
4838
+	public function _get_data_types()
4839
+	{
4840
+		$data_types = [];
4841
+		foreach ($this->field_settings() as $field_obj) {
4842
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4843
+			/** @var $field_obj EE_Model_Field_Base */
4844
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4845
+		}
4846
+		return $data_types;
4847
+	}
4848
+
4849
+
4850
+	/**
4851
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4852
+	 *
4853
+	 * @param string $model_name
4854
+	 * @return EEM_Base
4855
+	 * @throws EE_Error
4856
+	 */
4857
+	public function get_related_model_obj($model_name)
4858
+	{
4859
+		$model_classname = "EEM_" . $model_name;
4860
+		if (! class_exists($model_classname)) {
4861
+			throw new EE_Error(
4862
+				sprintf(
4863
+					esc_html__(
4864
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4865
+						'event_espresso'
4866
+					),
4867
+					$model_name,
4868
+					$model_classname
4869
+				)
4870
+			);
4871
+		}
4872
+		return call_user_func($model_classname . "::instance");
4873
+	}
4874
+
4875
+
4876
+	/**
4877
+	 * Returns the array of EE_ModelRelations for this model.
4878
+	 *
4879
+	 * @return EE_Model_Relation_Base[]
4880
+	 */
4881
+	public function relation_settings()
4882
+	{
4883
+		return $this->_model_relations;
4884
+	}
4885
+
4886
+
4887
+	/**
4888
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4889
+	 * because without THOSE models, this model probably doesn't have much purpose.
4890
+	 * (Eg, without an event, datetimes have little purpose.)
4891
+	 *
4892
+	 * @return EE_Belongs_To_Relation[]
4893
+	 */
4894
+	public function belongs_to_relations()
4895
+	{
4896
+		$belongs_to_relations = [];
4897
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4898
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4899
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4900
+			}
4901
+		}
4902
+		return $belongs_to_relations;
4903
+	}
4904
+
4905
+
4906
+	/**
4907
+	 * Returns the specified EE_Model_Relation, or throws an exception
4908
+	 *
4909
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4910
+	 * @return EE_Model_Relation_Base
4911
+	 * @throws EE_Error
4912
+	 */
4913
+	public function related_settings_for($relation_name)
4914
+	{
4915
+		$relatedModels = $this->relation_settings();
4916
+		if (! array_key_exists($relation_name, $relatedModels)) {
4917
+			throw new EE_Error(
4918
+				sprintf(
4919
+					esc_html__(
4920
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4921
+						'event_espresso'
4922
+					),
4923
+					$relation_name,
4924
+					$this->_get_class_name(),
4925
+					implode(', ', array_keys($relatedModels))
4926
+				)
4927
+			);
4928
+		}
4929
+		return $relatedModels[ $relation_name ];
4930
+	}
4931
+
4932
+
4933
+	/**
4934
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4935
+	 * fields
4936
+	 *
4937
+	 * @param string  $fieldName
4938
+	 * @param boolean $include_db_only_fields
4939
+	 * @return EE_Model_Field_Base
4940
+	 * @throws EE_Error
4941
+	 */
4942
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4943
+	{
4944
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4945
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4946
+			throw new EE_Error(
4947
+				sprintf(
4948
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4949
+					$fieldName,
4950
+					get_class($this)
4951
+				)
4952
+			);
4953
+		}
4954
+		return $fieldSettings[ $fieldName ];
4955
+	}
4956
+
4957
+
4958
+	/**
4959
+	 * Checks if this field exists on this model
4960
+	 *
4961
+	 * @param string $fieldName a key in the model's _field_settings array
4962
+	 * @return boolean
4963
+	 */
4964
+	public function has_field($fieldName)
4965
+	{
4966
+		$fieldSettings = $this->field_settings(true);
4967
+		if (isset($fieldSettings[ $fieldName ])) {
4968
+			return true;
4969
+		}
4970
+		return false;
4971
+	}
4972
+
4973
+
4974
+	/**
4975
+	 * Returns whether or not this model has a relation to the specified model
4976
+	 *
4977
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4978
+	 * @return boolean
4979
+	 */
4980
+	public function has_relation($relation_name)
4981
+	{
4982
+		$relations = $this->relation_settings();
4983
+		if (isset($relations[ $relation_name ])) {
4984
+			return true;
4985
+		}
4986
+		return false;
4987
+	}
4988
+
4989
+
4990
+	/**
4991
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4992
+	 * Eg, on EE_Answer that would be ANS_ID field object
4993
+	 *
4994
+	 * @param $field_obj
4995
+	 * @return boolean
4996
+	 */
4997
+	public function is_primary_key_field($field_obj)
4998
+	{
4999
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5000
+	}
5001
+
5002
+
5003
+	/**
5004
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5005
+	 * Eg, on EE_Answer that would be ANS_ID field object
5006
+	 *
5007
+	 * @return EE_Model_Field_Base
5008
+	 * @throws EE_Error
5009
+	 */
5010
+	public function get_primary_key_field()
5011
+	{
5012
+		if ($this->_primary_key_field === null) {
5013
+			foreach ($this->field_settings(true) as $field_obj) {
5014
+				if ($this->is_primary_key_field($field_obj)) {
5015
+					$this->_primary_key_field = $field_obj;
5016
+					break;
5017
+				}
5018
+			}
5019
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5020
+				throw new EE_Error(
5021
+					sprintf(
5022
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5023
+						get_class($this)
5024
+					)
5025
+				);
5026
+			}
5027
+		}
5028
+		return $this->_primary_key_field;
5029
+	}
5030
+
5031
+
5032
+	/**
5033
+	 * Returns whether or not not there is a primary key on this model.
5034
+	 * Internally does some caching.
5035
+	 *
5036
+	 * @return boolean
5037
+	 */
5038
+	public function has_primary_key_field()
5039
+	{
5040
+		if ($this->_has_primary_key_field === null) {
5041
+			try {
5042
+				$this->get_primary_key_field();
5043
+				$this->_has_primary_key_field = true;
5044
+			} catch (EE_Error $e) {
5045
+				$this->_has_primary_key_field = false;
5046
+			}
5047
+		}
5048
+		return $this->_has_primary_key_field;
5049
+	}
5050
+
5051
+
5052
+	/**
5053
+	 * Finds the first field of type $field_class_name.
5054
+	 *
5055
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5056
+	 *                                 EE_Foreign_Key_Field, etc
5057
+	 * @return EE_Model_Field_Base or null if none is found
5058
+	 */
5059
+	public function get_a_field_of_type($field_class_name)
5060
+	{
5061
+		foreach ($this->field_settings() as $field) {
5062
+			if ($field instanceof $field_class_name) {
5063
+				return $field;
5064
+			}
5065
+		}
5066
+		return null;
5067
+	}
5068
+
5069
+
5070
+	/**
5071
+	 * Gets a foreign key field pointing to model.
5072
+	 *
5073
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5074
+	 * @return EE_Foreign_Key_Field_Base
5075
+	 * @throws EE_Error
5076
+	 */
5077
+	public function get_foreign_key_to($model_name)
5078
+	{
5079
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5080
+			foreach ($this->field_settings() as $field) {
5081
+				if (
5082
+					$field instanceof EE_Foreign_Key_Field_Base
5083
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5084
+				) {
5085
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5086
+					break;
5087
+				}
5088
+			}
5089
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5090
+				throw new EE_Error(
5091
+					sprintf(
5092
+						esc_html__(
5093
+							"There is no foreign key field pointing to model %s on model %s",
5094
+							'event_espresso'
5095
+						),
5096
+						$model_name,
5097
+						get_class($this)
5098
+					)
5099
+				);
5100
+			}
5101
+		}
5102
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5103
+	}
5104
+
5105
+
5106
+	/**
5107
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5108
+	 *
5109
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5110
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5111
+	 *                            Either one works
5112
+	 * @return string
5113
+	 */
5114
+	public function get_table_for_alias($table_alias)
5115
+	{
5116
+		$table_alias_sans_model_relation_chain_prefix =
5117
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5118
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5119
+	}
5120
+
5121
+
5122
+	/**
5123
+	 * Returns a flat array of all field son this model, instead of organizing them
5124
+	 * by table_alias as they are in the constructor.
5125
+	 *
5126
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5127
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5128
+	 */
5129
+	public function field_settings($include_db_only_fields = false)
5130
+	{
5131
+		if ($include_db_only_fields) {
5132
+			if ($this->_cached_fields === null) {
5133
+				$this->_cached_fields = [];
5134
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5135
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5136
+						$this->_cached_fields[ $field_name ] = $field_obj;
5137
+					}
5138
+				}
5139
+			}
5140
+			return $this->_cached_fields;
5141
+		}
5142
+		if ($this->_cached_fields_non_db_only === null) {
5143
+			$this->_cached_fields_non_db_only = [];
5144
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5145
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5146
+					/** @var $field_obj EE_Model_Field_Base */
5147
+					if (! $field_obj->is_db_only_field()) {
5148
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5149
+					}
5150
+				}
5151
+			}
5152
+		}
5153
+		return $this->_cached_fields_non_db_only;
5154
+	}
5155
+
5156
+
5157
+	/**
5158
+	 *        cycle though array of attendees and create objects out of each item
5159
+	 *
5160
+	 * @access        private
5161
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5162
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5163
+	 *                           numerically indexed)
5164
+	 * @throws EE_Error
5165
+	 * @throws ReflectionException
5166
+	 */
5167
+	protected function _create_objects($rows = [])
5168
+	{
5169
+		$array_of_objects = [];
5170
+		if (empty($rows)) {
5171
+			return [];
5172
+		}
5173
+		$count_if_model_has_no_primary_key = 0;
5174
+		$has_primary_key                   = $this->has_primary_key_field();
5175
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5176
+		foreach ((array) $rows as $row) {
5177
+			if (empty($row)) {
5178
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5179
+				return [];
5180
+			}
5181
+			// check if we've already set this object in the results array,
5182
+			// in which case there's no need to process it further (again)
5183
+			if ($has_primary_key) {
5184
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5185
+					$row,
5186
+					$primary_key_field->get_qualified_column(),
5187
+					$primary_key_field->get_table_column()
5188
+				);
5189
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5190
+					continue;
5191
+				}
5192
+			}
5193
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5194
+			if (! $classInstance) {
5195
+				throw new EE_Error(
5196
+					sprintf(
5197
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5198
+						$this->get_this_model_name(),
5199
+						http_build_query($row)
5200
+					)
5201
+				);
5202
+			}
5203
+			// set the timezone on the instantiated objects
5204
+			$classInstance->set_timezone($this->get_timezone(), true);
5205
+			// make sure if there is any timezone setting present that we set the timezone for the object
5206
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5207
+			$array_of_objects[ $key ] = $classInstance;
5208
+			// also, for all the relations of type BelongsTo, see if we can cache
5209
+			// those related models
5210
+			// (we could do this for other relations too, but if there are conditions
5211
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5212
+			// so it requires a little more thought than just caching them immediately...)
5213
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5214
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5215
+					// check if this model's INFO is present. If so, cache it on the model
5216
+					$other_model           = $relation_obj->get_other_model();
5217
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5218
+					// if we managed to make a model object from the results, cache it on the main model object
5219
+					if ($other_model_obj_maybe) {
5220
+						// set timezone on these other model objects if they are present
5221
+						$other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5222
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5223
+					}
5224
+				}
5225
+			}
5226
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5227
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5228
+			// the field in the CustomSelects object
5229
+			if ($this->_custom_selections instanceof CustomSelects) {
5230
+				$classInstance->setCustomSelectsValues(
5231
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5232
+				);
5233
+			}
5234
+		}
5235
+		return $array_of_objects;
5236
+	}
5237
+
5238
+
5239
+	/**
5240
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5241
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5242
+	 *
5243
+	 * @param array $db_results_row
5244
+	 * @return array
5245
+	 */
5246
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5247
+	{
5248
+		$results = [];
5249
+		if ($this->_custom_selections instanceof CustomSelects) {
5250
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5251
+				if (isset($db_results_row[ $alias ])) {
5252
+					$results[ $alias ] = $this->convertValueToDataType(
5253
+						$db_results_row[ $alias ],
5254
+						$this->_custom_selections->getDataTypeForAlias($alias)
5255
+					);
5256
+				}
5257
+			}
5258
+		}
5259
+		return $results;
5260
+	}
5261
+
5262
+
5263
+	/**
5264
+	 * This will set the value for the given alias
5265
+	 *
5266
+	 * @param string $value
5267
+	 * @param string $datatype (one of %d, %s, %f)
5268
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5269
+	 */
5270
+	protected function convertValueToDataType($value, $datatype)
5271
+	{
5272
+		switch ($datatype) {
5273
+			case '%f':
5274
+				return (float) $value;
5275
+			case '%d':
5276
+				return (int) $value;
5277
+			default:
5278
+				return (string) $value;
5279
+		}
5280
+	}
5281
+
5282
+
5283
+	/**
5284
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5285
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5286
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5287
+	 * object (as set in the model_field!).
5288
+	 *
5289
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5290
+	 * @throws EE_Error
5291
+	 * @throws ReflectionException
5292
+	 */
5293
+	public function create_default_object()
5294
+	{
5295
+		$this_model_fields_and_values = [];
5296
+		// setup the row using default values;
5297
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5298
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5299
+		}
5300
+		$className = $this->_get_class_name();
5301
+		return EE_Registry::instance()->load_class(
5302
+			$className,
5303
+			[$this_model_fields_and_values],
5304
+			false,
5305
+			false
5306
+		);
5307
+	}
5308
+
5309
+
5310
+	/**
5311
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5312
+	 *                             or an stdClass where each property is the name of a column,
5313
+	 * @return EE_Base_Class
5314
+	 * @throws EE_Error
5315
+	 * @throws ReflectionException
5316
+	 */
5317
+	public function instantiate_class_from_array_or_object($cols_n_values)
5318
+	{
5319
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5320
+			$cols_n_values = get_object_vars($cols_n_values);
5321
+		}
5322
+		$primary_key = null;
5323
+		// make sure the array only has keys that are fields/columns on this model
5324
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5325
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5326
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5327
+		}
5328
+		$className = $this->_get_class_name();
5329
+		// check we actually found results that we can use to build our model object
5330
+		// if not, return null
5331
+		if ($this->has_primary_key_field()) {
5332
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5333
+				return null;
5334
+			}
5335
+		} elseif ($this->unique_indexes()) {
5336
+			$first_column = reset($this_model_fields_n_values);
5337
+			if (empty($first_column)) {
5338
+				return null;
5339
+			}
5340
+		}
5341
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5342
+		if ($primary_key) {
5343
+			$classInstance = $this->get_from_entity_map($primary_key);
5344
+			if (! $classInstance) {
5345
+				$classInstance = EE_Registry::instance()->load_class(
5346
+					$className,
5347
+					[$this_model_fields_n_values, $this->get_timezone()],
5348
+					true,
5349
+					false
5350
+				);
5351
+				// add this new object to the entity map
5352
+				$classInstance = $this->add_to_entity_map($classInstance);
5353
+			}
5354
+		} else {
5355
+			$classInstance = EE_Registry::instance()->load_class(
5356
+				$className,
5357
+				[$this_model_fields_n_values, $this->get_timezone()],
5358
+				true,
5359
+				false
5360
+			);
5361
+		}
5362
+		return $classInstance;
5363
+	}
5364
+
5365
+
5366
+	/**
5367
+	 * Gets the model object from the  entity map if it exists
5368
+	 *
5369
+	 * @param int|string $id the ID of the model object
5370
+	 * @return EE_Base_Class
5371
+	 */
5372
+	public function get_from_entity_map($id)
5373
+	{
5374
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5375
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5376
+			: null;
5377
+	}
5378
+
5379
+
5380
+	/**
5381
+	 * add_to_entity_map
5382
+	 * Adds the object to the model's entity mappings
5383
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5384
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5385
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5386
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5387
+	 *        then this method should be called immediately after the update query
5388
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5389
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5390
+	 *
5391
+	 * @param EE_Base_Class $object
5392
+	 * @return EE_Base_Class
5393
+	 * @throws EE_Error
5394
+	 */
5395
+	public function add_to_entity_map(EE_Base_Class $object)
5396
+	{
5397
+		$className = $this->_get_class_name();
5398
+		if (! $object instanceof $className) {
5399
+			throw new EE_Error(
5400
+				sprintf(
5401
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5402
+					is_object($object) ? get_class($object) : $object,
5403
+					$className
5404
+				)
5405
+			);
5406
+		}
5407
+		if (! $object->ID()) {
5408
+			throw new EE_Error(
5409
+				sprintf(
5410
+					esc_html__(
5411
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5412
+						"event_espresso"
5413
+					),
5414
+					get_class($this)
5415
+				)
5416
+			);
5417
+		}
5418
+		// double check it's not already there
5419
+		$classInstance = $this->get_from_entity_map($object->ID());
5420
+		if ($classInstance) {
5421
+			return $classInstance;
5422
+		}
5423
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5424
+		return $object;
5425
+	}
5426
+
5427
+
5428
+	/**
5429
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5430
+	 * if no identifier is provided, then the entire entity map is emptied
5431
+	 *
5432
+	 * @param int|string $id the ID of the model object
5433
+	 * @return boolean
5434
+	 */
5435
+	public function clear_entity_map($id = null)
5436
+	{
5437
+		if (empty($id)) {
5438
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5439
+			return true;
5440
+		}
5441
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5442
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5443
+			return true;
5444
+		}
5445
+		return false;
5446
+	}
5447
+
5448
+
5449
+	/**
5450
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5451
+	 * Given an array where keys are column (or column alias) names and values,
5452
+	 * returns an array of their corresponding field names and database values
5453
+	 *
5454
+	 * @param array $cols_n_values
5455
+	 * @return array
5456
+	 */
5457
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5458
+	{
5459
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5460
+	}
5461
+
5462
+
5463
+	/**
5464
+	 * _deduce_fields_n_values_from_cols_n_values
5465
+	 * Given an array where keys are column (or column alias) names and values,
5466
+	 * returns an array of their corresponding field names and database values
5467
+	 *
5468
+	 * @param array $cols_n_values
5469
+	 * @return array
5470
+	 */
5471
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5472
+	{
5473
+		$this_model_fields_n_values = [];
5474
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5475
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5476
+				$cols_n_values,
5477
+				$table_obj->get_fully_qualified_pk_column(),
5478
+				$table_obj->get_pk_column()
5479
+			);
5480
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5481
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5482
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5483
+					if (! $field_obj->is_db_only_field()) {
5484
+						// prepare field as if its coming from db
5485
+						$prepared_value                            =
5486
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5487
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5488
+					}
5489
+				}
5490
+			} else {
5491
+				// the table's rows existed. Use their values
5492
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5493
+					if (! $field_obj->is_db_only_field()) {
5494
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5495
+							$cols_n_values,
5496
+							$field_obj->get_qualified_column(),
5497
+							$field_obj->get_table_column()
5498
+						);
5499
+					}
5500
+				}
5501
+			}
5502
+		}
5503
+		return $this_model_fields_n_values;
5504
+	}
5505
+
5506
+
5507
+	/**
5508
+	 * @param array  $cols_n_values
5509
+	 * @param string $qualified_column
5510
+	 * @param string $regular_column
5511
+	 * @return null
5512
+	 */
5513
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5514
+	{
5515
+		$value = null;
5516
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5517
+		// does the field on the model relate to this column retrieved from the db?
5518
+		// or is it a db-only field? (not relating to the model)
5519
+		if (isset($cols_n_values[ $qualified_column ])) {
5520
+			$value = $cols_n_values[ $qualified_column ];
5521
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5522
+			$value = $cols_n_values[ $regular_column ];
5523
+		} elseif (! empty($this->foreign_key_aliases)) {
5524
+			// no PK?  ok check if there is a foreign key alias set for this table
5525
+			// then check if that alias exists in the incoming data
5526
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5527
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5528
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5529
+					$value = $cols_n_values[ $FK_alias ];
5530
+					break;
5531
+				}
5532
+			}
5533
+		}
5534
+		return $value;
5535
+	}
5536
+
5537
+
5538
+	/**
5539
+	 * refresh_entity_map_from_db
5540
+	 * Makes sure the model object in the entity map at $id assumes the values
5541
+	 * of the database (opposite of EE_base_Class::save())
5542
+	 *
5543
+	 * @param int|string $id
5544
+	 * @return EE_Base_Class
5545
+	 * @throws EE_Error
5546
+	 * @throws ReflectionException
5547
+	 */
5548
+	public function refresh_entity_map_from_db($id)
5549
+	{
5550
+		$obj_in_map = $this->get_from_entity_map($id);
5551
+		if ($obj_in_map) {
5552
+			$wpdb_results = $this->_get_all_wpdb_results(
5553
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5554
+			);
5555
+			if ($wpdb_results && is_array($wpdb_results)) {
5556
+				$one_row = reset($wpdb_results);
5557
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5558
+					$obj_in_map->set_from_db($field_name, $db_value);
5559
+				}
5560
+				// clear the cache of related model objects
5561
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5562
+					$obj_in_map->clear_cache($relation_name, null, true);
5563
+				}
5564
+			}
5565
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5566
+			return $obj_in_map;
5567
+		}
5568
+		return $this->get_one_by_ID($id);
5569
+	}
5570
+
5571
+
5572
+	/**
5573
+	 * refresh_entity_map_with
5574
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5575
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5576
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5577
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5578
+	 *
5579
+	 * @param int|string    $id
5580
+	 * @param EE_Base_Class $replacing_model_obj
5581
+	 * @return EE_Base_Class
5582
+	 * @throws EE_Error
5583
+	 * @throws ReflectionException
5584
+	 */
5585
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5586
+	{
5587
+		$obj_in_map = $this->get_from_entity_map($id);
5588
+		if ($obj_in_map) {
5589
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5590
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5591
+					$obj_in_map->set($field_name, $value);
5592
+				}
5593
+				// make the model object in the entity map's cache match the $replacing_model_obj
5594
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5595
+					$obj_in_map->clear_cache($relation_name, null, true);
5596
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5597
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5598
+					}
5599
+				}
5600
+			}
5601
+			return $obj_in_map;
5602
+		}
5603
+		$this->add_to_entity_map($replacing_model_obj);
5604
+		return $replacing_model_obj;
5605
+	}
5606
+
5607
+
5608
+	/**
5609
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5610
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5611
+	 * require_once($this->_getClassName().".class.php");
5612
+	 *
5613
+	 * @return string
5614
+	 */
5615
+	private function _get_class_name()
5616
+	{
5617
+		return "EE_" . $this->get_this_model_name();
5618
+	}
5619
+
5620
+
5621
+	/**
5622
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5623
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5624
+	 * it would be 'Events'.
5625
+	 *
5626
+	 * @param int $quantity
5627
+	 * @return string
5628
+	 */
5629
+	public function item_name($quantity = 1)
5630
+	{
5631
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5632
+	}
5633
+
5634
+
5635
+	/**
5636
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5637
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5638
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5639
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5640
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5641
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5642
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5643
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5644
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5645
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5646
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5647
+	 *        return $previousReturnValue.$returnString;
5648
+	 * }
5649
+	 * require('EEM_Answer.model.php');
5650
+	 * $answer=EEM_Answer::instance();
5651
+	 * echo $answer->my_callback('monkeys',100);
5652
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5653
+	 *
5654
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5655
+	 * @param array  $args       array of original arguments passed to the function
5656
+	 * @return mixed whatever the plugin which calls add_filter decides
5657
+	 * @throws EE_Error
5658
+	 */
5659
+	public function __call($methodName, $args)
5660
+	{
5661
+		$className = get_class($this);
5662
+		$tagName   = "FHEE__{$className}__{$methodName}";
5663
+		if (! has_filter($tagName)) {
5664
+			throw new EE_Error(
5665
+				sprintf(
5666
+					esc_html__(
5667
+						'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 );',
5668
+						'event_espresso'
5669
+					),
5670
+					$methodName,
5671
+					$className,
5672
+					$tagName,
5673
+					'<br />'
5674
+				)
5675
+			);
5676
+		}
5677
+		return apply_filters($tagName, null, $this, $args);
5678
+	}
5679
+
5680
+
5681
+	/**
5682
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5683
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5684
+	 *
5685
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5686
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5687
+	 *                                                       the object's class name
5688
+	 *                                                       or object's ID
5689
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5690
+	 *                                                       exists in the database. If it does not, we add it
5691
+	 * @return EE_Base_Class
5692
+	 * @throws EE_Error
5693
+	 * @throws ReflectionException
5694
+	 */
5695
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5696
+	{
5697
+		$className = $this->_get_class_name();
5698
+		if ($base_class_obj_or_id instanceof $className) {
5699
+			$model_object = $base_class_obj_or_id;
5700
+		} else {
5701
+			$primary_key_field = $this->get_primary_key_field();
5702
+			if (
5703
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5704
+				&& (
5705
+					is_int($base_class_obj_or_id)
5706
+					|| is_string($base_class_obj_or_id)
5707
+				)
5708
+			) {
5709
+				// assume it's an ID.
5710
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5711
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5712
+			} elseif (
5713
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5714
+				&& is_string($base_class_obj_or_id)
5715
+			) {
5716
+				// assume its a string representation of the object
5717
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5718
+			} else {
5719
+				throw new EE_Error(
5720
+					sprintf(
5721
+						esc_html__(
5722
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5723
+							'event_espresso'
5724
+						),
5725
+						$base_class_obj_or_id,
5726
+						$this->_get_class_name(),
5727
+						print_r($base_class_obj_or_id, true)
5728
+					)
5729
+				);
5730
+			}
5731
+		}
5732
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5733
+			$model_object->save();
5734
+		}
5735
+		return $model_object;
5736
+	}
5737
+
5738
+
5739
+	/**
5740
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5741
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5742
+	 * returns it ID.
5743
+	 *
5744
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5745
+	 * @return int|string depending on the type of this model object's ID
5746
+	 * @throws EE_Error
5747
+	 */
5748
+	public function ensure_is_ID($base_class_obj_or_id)
5749
+	{
5750
+		$className = $this->_get_class_name();
5751
+		if ($base_class_obj_or_id instanceof $className) {
5752
+			$id = $base_class_obj_or_id->ID();
5753
+		} elseif (is_int($base_class_obj_or_id)) {
5754
+			// assume it's an ID
5755
+			$id = $base_class_obj_or_id;
5756
+		} elseif (is_string($base_class_obj_or_id)) {
5757
+			// assume its a string representation of the object
5758
+			$id = $base_class_obj_or_id;
5759
+		} else {
5760
+			throw new EE_Error(
5761
+				sprintf(
5762
+					esc_html__(
5763
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5764
+						'event_espresso'
5765
+					),
5766
+					$base_class_obj_or_id,
5767
+					$this->_get_class_name(),
5768
+					print_r($base_class_obj_or_id, true)
5769
+				)
5770
+			);
5771
+		}
5772
+		return $id;
5773
+	}
5774
+
5775
+
5776
+	/**
5777
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5778
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5779
+	 * been sanitized and converted into the appropriate domain.
5780
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5781
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5782
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5783
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5784
+	 * $EVT = EEM_Event::instance(); $old_setting =
5785
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5786
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5787
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5788
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5789
+	 *
5790
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5791
+	 * @return void
5792
+	 */
5793
+	public function assume_values_already_prepared_by_model_object(
5794
+		$values_already_prepared = self::not_prepared_by_model_object
5795
+	) {
5796
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5797
+	}
5798
+
5799
+
5800
+	/**
5801
+	 * Read comments for assume_values_already_prepared_by_model_object()
5802
+	 *
5803
+	 * @return int
5804
+	 */
5805
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
+	{
5807
+		return $this->_values_already_prepared_by_model_object;
5808
+	}
5809
+
5810
+
5811
+	/**
5812
+	 * Gets all the indexes on this model
5813
+	 *
5814
+	 * @return EE_Index[]
5815
+	 */
5816
+	public function indexes()
5817
+	{
5818
+		return $this->_indexes;
5819
+	}
5820
+
5821
+
5822
+	/**
5823
+	 * Gets all the Unique Indexes on this model
5824
+	 *
5825
+	 * @return EE_Unique_Index[]
5826
+	 */
5827
+	public function unique_indexes()
5828
+	{
5829
+		$unique_indexes = [];
5830
+		foreach ($this->_indexes as $name => $index) {
5831
+			if ($index instanceof EE_Unique_Index) {
5832
+				$unique_indexes [ $name ] = $index;
5833
+			}
5834
+		}
5835
+		return $unique_indexes;
5836
+	}
5837
+
5838
+
5839
+	/**
5840
+	 * Gets all the fields which, when combined, make the primary key.
5841
+	 * This is usually just an array with 1 element (the primary key), but in cases
5842
+	 * where there is no primary key, it's a combination of fields as defined
5843
+	 * on a primary index
5844
+	 *
5845
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5846
+	 * @throws EE_Error
5847
+	 */
5848
+	public function get_combined_primary_key_fields()
5849
+	{
5850
+		foreach ($this->indexes() as $index) {
5851
+			if ($index instanceof EE_Primary_Key_Index) {
5852
+				return $index->fields();
5853
+			}
5854
+		}
5855
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5856
+	}
5857
+
5858
+
5859
+	/**
5860
+	 * Used to build a primary key string (when the model has no primary key),
5861
+	 * which can be used a unique string to identify this model object.
5862
+	 *
5863
+	 * @param array $fields_n_values keys are field names, values are their values.
5864
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5865
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5866
+	 *                               before passing it to this function (that will convert it from columns-n-values
5867
+	 *                               to field-names-n-values).
5868
+	 * @return string
5869
+	 * @throws EE_Error
5870
+	 */
5871
+	public function get_index_primary_key_string($fields_n_values)
5872
+	{
5873
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5874
+			$fields_n_values,
5875
+			$this->get_combined_primary_key_fields()
5876
+		);
5877
+		return http_build_query($cols_n_values_for_primary_key_index);
5878
+	}
5879
+
5880
+
5881
+	/**
5882
+	 * Gets the field values from the primary key string
5883
+	 *
5884
+	 * @param string $index_primary_key_string
5885
+	 * @return null|array
5886
+	 * @throws EE_Error
5887
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5888
+	 */
5889
+	public function parse_index_primary_key_string($index_primary_key_string)
5890
+	{
5891
+		$key_fields = $this->get_combined_primary_key_fields();
5892
+		// check all of them are in the $id
5893
+		$key_values_in_combined_pk = [];
5894
+		parse_str($index_primary_key_string, $key_values_in_combined_pk);
5895
+		foreach ($key_fields as $key_field_name => $field_obj) {
5896
+			if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5897
+				return null;
5898
+			}
5899
+		}
5900
+		return $key_values_in_combined_pk;
5901
+	}
5902
+
5903
+
5904
+	/**
5905
+	 * verifies that an array of key-value pairs for model fields has a key
5906
+	 * for each field comprising the primary key index
5907
+	 *
5908
+	 * @param array $key_values
5909
+	 * @return boolean
5910
+	 * @throws EE_Error
5911
+	 */
5912
+	public function has_all_combined_primary_key_fields($key_values)
5913
+	{
5914
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915
+		foreach ($keys_it_should_have as $key) {
5916
+			if (! isset($key_values[ $key ])) {
5917
+				return false;
5918
+			}
5919
+		}
5920
+		return true;
5921
+	}
5922
+
5923
+
5924
+	/**
5925
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5926
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5927
+	 *
5928
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5929
+	 * @param array               $query_params                     see github link below for more info
5930
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5931
+	 * @throws EE_Error
5932
+	 * @throws ReflectionException
5933
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5934
+	 *                                                              indexed)
5935
+	 */
5936
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5937
+	{
5938
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5939
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5940
+		} elseif (is_array($model_object_or_attributes_array)) {
5941
+			$attributes_array = $model_object_or_attributes_array;
5942
+		} else {
5943
+			throw new EE_Error(
5944
+				sprintf(
5945
+					esc_html__(
5946
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5947
+						"event_espresso"
5948
+					),
5949
+					$model_object_or_attributes_array
5950
+				)
5951
+			);
5952
+		}
5953
+		// even copies obviously won't have the same ID, so remove the primary key
5954
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
+			unset($attributes_array[ $this->primary_key_name() ]);
5957
+		}
5958
+		if (isset($query_params[0])) {
5959
+			$query_params[0] = array_merge($attributes_array, $query_params);
5960
+		} else {
5961
+			$query_params[0] = $attributes_array;
5962
+		}
5963
+		return $this->get_all($query_params);
5964
+	}
5965
+
5966
+
5967
+	/**
5968
+	 * Gets the first copy we find. See get_all_copies for more details
5969
+	 *
5970
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5971
+	 * @param array $query_params
5972
+	 * @return EE_Base_Class
5973
+	 * @throws EE_Error
5974
+	 * @throws ReflectionException
5975
+	 */
5976
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5977
+	{
5978
+		if (! is_array($query_params)) {
5979
+			EE_Error::doing_it_wrong(
5980
+				'EEM_Base::get_one_copy',
5981
+				sprintf(
5982
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
+					gettype($query_params)
5984
+				),
5985
+				'4.6.0'
5986
+			);
5987
+			$query_params = [];
5988
+		}
5989
+		$query_params['limit'] = 1;
5990
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
+		if (is_array($copies)) {
5992
+			return array_shift($copies);
5993
+		}
5994
+		return null;
5995
+	}
5996
+
5997
+
5998
+	/**
5999
+	 * Updates the item with the specified id. Ignores default query parameters because
6000
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6001
+	 *
6002
+	 * @param array      $fields_n_values keys are field names, values are their new values
6003
+	 * @param int|string $id              the value of the primary key to update
6004
+	 * @return int number of rows updated
6005
+	 * @throws EE_Error
6006
+	 * @throws ReflectionException
6007
+	 */
6008
+	public function update_by_ID($fields_n_values, $id)
6009
+	{
6010
+		$query_params = [
6011
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6012
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
+		];
6014
+		return $this->update($fields_n_values, $query_params);
6015
+	}
6016
+
6017
+
6018
+	/**
6019
+	 * Changes an operator which was supplied to the models into one usable in SQL
6020
+	 *
6021
+	 * @param string $operator_supplied
6022
+	 * @return string an operator which can be used in SQL
6023
+	 * @throws EE_Error
6024
+	 */
6025
+	private function _prepare_operator_for_sql($operator_supplied)
6026
+	{
6027
+		$sql_operator =
6028
+			isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
+				: null;
6030
+		if ($sql_operator) {
6031
+			return $sql_operator;
6032
+		}
6033
+		throw new EE_Error(
6034
+			sprintf(
6035
+				esc_html__(
6036
+					"The operator '%s' is not in the list of valid operators: %s",
6037
+					"event_espresso"
6038
+				),
6039
+				$operator_supplied,
6040
+				implode(",", array_keys($this->_valid_operators))
6041
+			)
6042
+		);
6043
+	}
6044
+
6045
+
6046
+	/**
6047
+	 * Gets the valid operators
6048
+	 *
6049
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6050
+	 */
6051
+	public function valid_operators()
6052
+	{
6053
+		return $this->_valid_operators;
6054
+	}
6055
+
6056
+
6057
+	/**
6058
+	 * Gets the between-style operators (take 2 arguments).
6059
+	 *
6060
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6061
+	 */
6062
+	public function valid_between_style_operators()
6063
+	{
6064
+		return array_intersect(
6065
+			$this->valid_operators(),
6066
+			$this->_between_style_operators
6067
+		);
6068
+	}
6069
+
6070
+
6071
+	/**
6072
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6073
+	 *
6074
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6075
+	 */
6076
+	public function valid_like_style_operators()
6077
+	{
6078
+		return array_intersect(
6079
+			$this->valid_operators(),
6080
+			$this->_like_style_operators
6081
+		);
6082
+	}
6083
+
6084
+
6085
+	/**
6086
+	 * Gets the "in"-style operators
6087
+	 *
6088
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6089
+	 */
6090
+	public function valid_in_style_operators()
6091
+	{
6092
+		return array_intersect(
6093
+			$this->valid_operators(),
6094
+			$this->_in_style_operators
6095
+		);
6096
+	}
6097
+
6098
+
6099
+	/**
6100
+	 * Gets the "null"-style operators (accept no arguments)
6101
+	 *
6102
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6103
+	 */
6104
+	public function valid_null_style_operators()
6105
+	{
6106
+		return array_intersect(
6107
+			$this->valid_operators(),
6108
+			$this->_null_style_operators
6109
+		);
6110
+	}
6111
+
6112
+
6113
+	/**
6114
+	 * Gets an array where keys are the primary keys and values are their 'names'
6115
+	 * (as determined by the model object's name() function, which is often overridden)
6116
+	 *
6117
+	 * @param array $query_params like get_all's
6118
+	 * @return string[]
6119
+	 * @throws EE_Error
6120
+	 * @throws ReflectionException
6121
+	 */
6122
+	public function get_all_names($query_params = [])
6123
+	{
6124
+		$objs  = $this->get_all($query_params);
6125
+		$names = [];
6126
+		foreach ($objs as $obj) {
6127
+			$names[ $obj->ID() ] = $obj->name();
6128
+		}
6129
+		return $names;
6130
+	}
6131
+
6132
+
6133
+	/**
6134
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6135
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6136
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6137
+	 * array_keys() on $model_objects.
6138
+	 *
6139
+	 * @param EE_Base_Class[] $model_objects
6140
+	 * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6141
+	 *                                               in the returned array
6142
+	 * @return array
6143
+	 * @throws EE_Error
6144
+	 */
6145
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6146
+	{
6147
+		if (! $this->has_primary_key_field()) {
6148
+			if (WP_DEBUG) {
6149
+				EE_Error::add_error(
6150
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6151
+					__FILE__,
6152
+					__FUNCTION__,
6153
+					__LINE__
6154
+				);
6155
+			}
6156
+		}
6157
+		$IDs = [];
6158
+		foreach ($model_objects as $model_object) {
6159
+			$id = $model_object->ID();
6160
+			if (! $id) {
6161
+				if ($filter_out_empty_ids) {
6162
+					continue;
6163
+				}
6164
+				if (WP_DEBUG) {
6165
+					EE_Error::add_error(
6166
+						esc_html__(
6167
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6168
+							'event_espresso'
6169
+						),
6170
+						__FILE__,
6171
+						__FUNCTION__,
6172
+						__LINE__
6173
+					);
6174
+				}
6175
+			}
6176
+			$IDs[] = $id;
6177
+		}
6178
+		return $IDs;
6179
+	}
6180
+
6181
+
6182
+	/**
6183
+	 * Returns the string used in capabilities relating to this model. If there
6184
+	 * are no capabilities that relate to this model returns false
6185
+	 *
6186
+	 * @return string|false
6187
+	 */
6188
+	public function cap_slug()
6189
+	{
6190
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6191
+	}
6192
+
6193
+
6194
+	/**
6195
+	 * Returns the capability-restrictions array (@param string $context
6196
+	 *
6197
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6198
+	 * @throws EE_Error
6199
+	 * @see EEM_Base::_cap_restrictions).
6200
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6201
+	 *      only returns the cap restrictions array in that context (ie, the array
6202
+	 *      at that key)
6203
+	 *
6204
+	 */
6205
+	public function cap_restrictions($context = EEM_Base::caps_read)
6206
+	{
6207
+		EEM_Base::verify_is_valid_cap_context($context);
6208
+		// check if we ought to run the restriction generator first
6209
+		if (
6210
+			isset($this->_cap_restriction_generators[ $context ])
6211
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6212
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6213
+		) {
6214
+			$this->_cap_restrictions[ $context ] = array_merge(
6215
+				$this->_cap_restrictions[ $context ],
6216
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6217
+			);
6218
+		}
6219
+		// and make sure we've finalized the construction of each restriction
6220
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6221
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6222
+				$where_conditions_obj->_finalize_construct($this);
6223
+			}
6224
+		}
6225
+		return $this->_cap_restrictions[ $context ];
6226
+	}
6227
+
6228
+
6229
+	/**
6230
+	 * Indicating whether or not this model thinks its a wp core model
6231
+	 *
6232
+	 * @return boolean
6233
+	 */
6234
+	public function is_wp_core_model()
6235
+	{
6236
+		return $this->_wp_core_model;
6237
+	}
6238
+
6239
+
6240
+	/**
6241
+	 * Gets all the caps that are missing which impose a restriction on
6242
+	 * queries made in this context
6243
+	 *
6244
+	 * @param string $context one of EEM_Base::caps_ constants
6245
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6246
+	 * @throws EE_Error
6247
+	 */
6248
+	public function caps_missing($context = EEM_Base::caps_read)
6249
+	{
6250
+		$missing_caps     = [];
6251
+		$cap_restrictions = $this->cap_restrictions($context);
6252
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6253
+			if (
6254
+			! EE_Capabilities::instance()
6255
+							 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6256
+			) {
6257
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6258
+			}
6259
+		}
6260
+		return $missing_caps;
6261
+	}
6262
+
6263
+
6264
+	/**
6265
+	 * Gets the mapping from capability contexts to action strings used in capability names
6266
+	 *
6267
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6268
+	 * one of 'read', 'edit', or 'delete'
6269
+	 */
6270
+	public function cap_contexts_to_cap_action_map()
6271
+	{
6272
+		return apply_filters(
6273
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6274
+			$this->_cap_contexts_to_cap_action_map,
6275
+			$this
6276
+		);
6277
+	}
6278
+
6279
+
6280
+	/**
6281
+	 * Gets the action string for the specified capability context
6282
+	 *
6283
+	 * @param string $context
6284
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6285
+	 * @throws EE_Error
6286
+	 */
6287
+	public function cap_action_for_context($context)
6288
+	{
6289
+		$mapping = $this->cap_contexts_to_cap_action_map();
6290
+		if (isset($mapping[ $context ])) {
6291
+			return $mapping[ $context ];
6292
+		}
6293
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6294
+			return $action;
6295
+		}
6296
+		throw new EE_Error(
6297
+			sprintf(
6298
+				esc_html__(
6299
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6300
+					'event_espresso'
6301
+				),
6302
+				$context,
6303
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6304
+			)
6305
+		);
6306
+	}
6307
+
6308
+
6309
+	/**
6310
+	 * Returns all the capability contexts which are valid when querying models
6311
+	 *
6312
+	 * @return array
6313
+	 */
6314
+	public static function valid_cap_contexts()
6315
+	{
6316
+		return apply_filters(
6317
+			'FHEE__EEM_Base__valid_cap_contexts',
6318
+			[
6319
+				self::caps_read,
6320
+				self::caps_read_admin,
6321
+				self::caps_edit,
6322
+				self::caps_delete,
6323
+			]
6324
+		);
6325
+	}
6326
+
6327
+
6328
+	/**
6329
+	 * Returns all valid options for 'default_where_conditions'
6330
+	 *
6331
+	 * @return array
6332
+	 */
6333
+	public static function valid_default_where_conditions()
6334
+	{
6335
+		return [
6336
+			EEM_Base::default_where_conditions_all,
6337
+			EEM_Base::default_where_conditions_this_only,
6338
+			EEM_Base::default_where_conditions_others_only,
6339
+			EEM_Base::default_where_conditions_minimum_all,
6340
+			EEM_Base::default_where_conditions_minimum_others,
6341
+			EEM_Base::default_where_conditions_none,
6342
+		];
6343
+	}
6344
+
6345
+	// public static function default_where_conditions_full
6346
+
6347
+
6348
+	/**
6349
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6350
+	 *
6351
+	 * @param string $context
6352
+	 * @return bool
6353
+	 * @throws EE_Error
6354
+	 */
6355
+	public static function verify_is_valid_cap_context($context)
6356
+	{
6357
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6358
+		if (in_array($context, $valid_cap_contexts)) {
6359
+			return true;
6360
+		}
6361
+		throw new EE_Error(
6362
+			sprintf(
6363
+				esc_html__(
6364
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6365
+					'event_espresso'
6366
+				),
6367
+				$context,
6368
+				'EEM_Base',
6369
+				implode(',', $valid_cap_contexts)
6370
+			)
6371
+		);
6372
+	}
6373
+
6374
+
6375
+	/**
6376
+	 * Clears all the models field caches. This is only useful when a sub-class
6377
+	 * might have added a field or something and these caches might be invalidated
6378
+	 */
6379
+	protected function _invalidate_field_caches()
6380
+	{
6381
+		$this->_cache_foreign_key_to_fields = [];
6382
+		$this->_cached_fields               = null;
6383
+		$this->_cached_fields_non_db_only   = null;
6384
+	}
6385
+
6386
+
6387
+	/**
6388
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6389
+	 * (eg "and", "or", "not").
6390
+	 *
6391
+	 * @return array
6392
+	 */
6393
+	public function logic_query_param_keys()
6394
+	{
6395
+		return $this->_logic_query_param_keys;
6396
+	}
6397
+
6398
+
6399
+	/**
6400
+	 * Determines whether or not the where query param array key is for a logic query param.
6401
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6402
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6403
+	 *
6404
+	 * @param $query_param_key
6405
+	 * @return bool
6406
+	 */
6407
+	public function is_logic_query_param_key($query_param_key)
6408
+	{
6409
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6410
+			if (
6411
+				$query_param_key === $logic_query_param_key
6412
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6413
+			) {
6414
+				return true;
6415
+			}
6416
+		}
6417
+		return false;
6418
+	}
6419
+
6420
+
6421
+	/**
6422
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6423
+	 *
6424
+	 * @return boolean
6425
+	 * @since 4.9.74.p
6426
+	 */
6427
+	public function hasPassword()
6428
+	{
6429
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6430
+		if ($this->has_password_field === null) {
6431
+			$password_field           = $this->getPasswordField();
6432
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6433
+		}
6434
+		return $this->has_password_field;
6435
+	}
6436
+
6437
+
6438
+	/**
6439
+	 * Returns the password field on this model, if there is one
6440
+	 *
6441
+	 * @return EE_Password_Field|null
6442
+	 * @since 4.9.74.p
6443
+	 */
6444
+	public function getPasswordField()
6445
+	{
6446
+		// if we definitely already know there is a password field or not (because has_password_field is true or false)
6447
+		// there's no need to search for it. If we don't know yet, then find out
6448
+		if ($this->has_password_field === null && $this->password_field === null) {
6449
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6450
+		}
6451
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6452
+		return $this->password_field;
6453
+	}
6454
+
6455
+
6456
+	/**
6457
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6458
+	 *
6459
+	 * @return EE_Model_Field_Base[]
6460
+	 * @throws EE_Error
6461
+	 * @since 4.9.74.p
6462
+	 */
6463
+	public function getPasswordProtectedFields()
6464
+	{
6465
+		$password_field = $this->getPasswordField();
6466
+		$fields         = [];
6467
+		if ($password_field instanceof EE_Password_Field) {
6468
+			$field_names = $password_field->protectedFields();
6469
+			foreach ($field_names as $field_name) {
6470
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6471
+			}
6472
+		}
6473
+		return $fields;
6474
+	}
6475
+
6476
+
6477
+	/**
6478
+	 * Checks if the current user can perform the requested action on this model
6479
+	 *
6480
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6481
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6482
+	 * @return bool
6483
+	 * @throws EE_Error
6484
+	 * @throws InvalidArgumentException
6485
+	 * @throws InvalidDataTypeException
6486
+	 * @throws InvalidInterfaceException
6487
+	 * @throws ReflectionException
6488
+	 * @throws UnexpectedEntityException
6489
+	 * @since 4.9.74.p
6490
+	 */
6491
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6492
+	{
6493
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6494
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6495
+		}
6496
+		if (! is_array($model_obj_or_fields_n_values)) {
6497
+			throw new UnexpectedEntityException(
6498
+				$model_obj_or_fields_n_values,
6499
+				'EE_Base_Class',
6500
+				sprintf(
6501
+					esc_html__(
6502
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6503
+						'event_espresso'
6504
+					),
6505
+					__FUNCTION__
6506
+				)
6507
+			);
6508
+		}
6509
+		return $this->exists(
6510
+			$this->alter_query_params_to_restrict_by_ID(
6511
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6512
+				[
6513
+					'default_where_conditions' => 'none',
6514
+					'caps'                     => $cap_to_check,
6515
+				]
6516
+			)
6517
+		);
6518
+	}
6519
+
6520
+
6521
+	/**
6522
+	 * Returns the query param where conditions key to the password affecting this model.
6523
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6524
+	 *
6525
+	 * @return null|string
6526
+	 * @throws EE_Error
6527
+	 * @throws InvalidArgumentException
6528
+	 * @throws InvalidDataTypeException
6529
+	 * @throws InvalidInterfaceException
6530
+	 * @throws ModelConfigurationException
6531
+	 * @throws ReflectionException
6532
+	 * @since 4.9.74.p
6533
+	 */
6534
+	public function modelChainAndPassword()
6535
+	{
6536
+		if ($this->model_chain_to_password === null) {
6537
+			throw new ModelConfigurationException(
6538
+				$this,
6539
+				esc_html_x(
6540
+				// @codingStandardsIgnoreStart
6541
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6542
+					// @codingStandardsIgnoreEnd
6543
+					'1: model name',
6544
+					'event_espresso'
6545
+				)
6546
+			);
6547
+		}
6548
+		if ($this->model_chain_to_password === '') {
6549
+			$model_with_password = $this;
6550
+		} else {
6551
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6552
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6553
+			} else {
6554
+				$last_model_in_chain = $this->model_chain_to_password;
6555
+			}
6556
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6557
+		}
6558
+
6559
+		$password_field = $model_with_password->getPasswordField();
6560
+		if ($password_field instanceof EE_Password_Field) {
6561
+			$password_field_name = $password_field->get_name();
6562
+		} else {
6563
+			throw new ModelConfigurationException(
6564
+				$this,
6565
+				sprintf(
6566
+					esc_html_x(
6567
+						'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"',
6568
+						'1: model name, 2: special string',
6569
+						'event_espresso'
6570
+					),
6571
+					$model_with_password->get_this_model_name(),
6572
+					$this->model_chain_to_password
6573
+				)
6574
+			);
6575
+		}
6576
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6577
+	}
6578
+
6579
+
6580
+	/**
6581
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6582
+	 * or if this model itself has a password affecting access to some of its other fields.
6583
+	 *
6584
+	 * @return boolean
6585
+	 * @since 4.9.74.p
6586
+	 */
6587
+	public function restrictedByRelatedModelPassword()
6588
+	{
6589
+		return $this->model_chain_to_password !== null;
6590
+	}
6591 6591
 }
Please login to merge, or discard this patch.
Spacing   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = '')
568 568
     {
569 569
         // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
570
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
571 571
             throw new EE_Error(
572 572
                 sprintf(
573 573
                     esc_html__(
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          *
591 591
          * @var EE_Table_Base[] $_tables
592 592
          */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
593
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
594 594
         foreach ($this->_tables as $table_alias => $table_obj) {
595 595
             /** @var $table_obj EE_Table_Base */
596 596
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -605,10 +605,10 @@  discard block
 block discarded – undo
605 605
          *
606 606
          * @param EE_Model_Field_Base[] $_fields
607 607
          */
608
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
609 609
         $this->_invalidate_field_caches();
610 610
         foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
612 612
                 throw new EE_Error(
613 613
                     sprintf(
614 614
                         esc_html__(
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
          * @param EE_Model_Relation_Base[] $_model_relations
646 646
          */
647 647
         $this->_model_relations = (array) apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
648
+            'FHEE__'.get_class($this).'__construct__model_relations',
649 649
             $this->_model_relations
650 650
         );
651 651
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -657,12 +657,12 @@  discard block
 block discarded – undo
657 657
         }
658 658
         $this->set_timezone($timezone);
659 659
         // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
660
+        if ( ! $this->_default_where_conditions_strategy) {
661 661
             // nothing was set during child constructor, so set default
662 662
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663 663
         }
664 664
         $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
665
+        if ( ! $this->_minimum_where_conditions_strategy) {
666 666
             // nothing was set during child constructor, so set default
667 667
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668 668
         }
@@ -675,8 +675,8 @@  discard block
 block discarded – undo
675 675
         // initialize the standard cap restriction generators if none were specified by the child constructor
676 676
         if ($this->_cap_restriction_generators !== false) {
677 677
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
678
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
679
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
680 680
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681 681
                         new EE_Restriction_Generator_Protected(),
682 682
                         $cap_context,
@@ -688,10 +688,10 @@  discard block
 block discarded – undo
688 688
         // if there are cap restriction generators, use them to make the default cap restrictions
689 689
         if ($this->_cap_restriction_generators !== false) {
690 690
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
691
+                if ( ! $generator_object) {
692 692
                     continue;
693 693
                 }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
695 695
                     throw new EE_Error(
696 696
                         sprintf(
697 697
                             esc_html__(
@@ -704,12 +704,12 @@  discard block
 block discarded – undo
704 704
                     );
705 705
                 }
706 706
                 $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
707
+                if ( ! $generator_object->construction_finalized()) {
708 708
                     $generator_object->_construct_finalize($this, $action);
709 709
                 }
710 710
             }
711 711
         }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
+        do_action('AHEE__'.get_class($this).'__construct__end');
713 713
     }
714 714
 
715 715
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
     public static function instance($timezone = '')
754 754
     {
755 755
         // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
756
+        if ( ! static::$_instance instanceof static) {
757 757
             // instantiate Espresso_model
758 758
             static::$_instance = new static(
759 759
                 $timezone,
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
             foreach ($r->getDefaultProperties() as $property => $value) {
790 790
                 // don't set instance to null like it was originally,
791 791
                 // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
792
+                if ( ! isset($static_properties[$property])) {
793 793
                     static::$_instance->{$property} = $value;
794 794
                 }
795 795
             }
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
      */
814 814
     private static function getLoader()
815 815
     {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
816
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
817 817
             EEM_Base::$loader = LoaderFactory::getLoader();
818 818
         }
819 819
         return EEM_Base::$loader;
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
      */
834 834
     public function status_array($translated = false)
835 835
     {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
836
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
837 837
             return [];
838 838
         }
839 839
         $model_name   = $this->get_this_model_name();
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842 842
         $status_array = [];
843 843
         foreach ($stati as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
844
+            $status_array[$status->ID()] = $status->get('STS_code');
845 845
         }
846 846
         return $translated
847 847
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
     {
905 905
         $wp_user_field_name = $this->wp_user_field_name();
906 906
         if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
907
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
908 908
         }
909 909
         return $query_params;
910 910
     }
@@ -922,17 +922,17 @@  discard block
 block discarded – undo
922 922
     public function wp_user_field_name()
923 923
     {
924 924
         try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
925
+            if ( ! empty($this->_model_chain_to_wp_user)) {
926 926
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927 927
                 $last_model_name              = end($models_to_follow_to_wp_users);
928 928
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
929
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
930 930
             } else {
931 931
                 $model_with_fk_to_wp_users = $this;
932 932
                 $model_chain_to_wp_user    = '';
933 933
             }
934 934
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
935
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
936 936
         } catch (EE_Error $e) {
937 937
             return false;
938 938
         }
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
         if ($this->_custom_selections instanceof CustomSelects) {
1009 1009
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010 1010
             $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1011
+                ? ', '.$custom_expressions
1012 1012
                 : $custom_expressions;
1013 1013
         }
1014 1014
 
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1015
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1016 1016
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017 1017
     }
1018 1018
 
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
      */
1030 1030
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031 1031
     {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1032
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033 1033
             return null;
1034 1034
         }
1035 1035
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
         if (is_array($columns_to_select)) {
1079 1079
             $select_sql_array = [];
1080 1080
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1081
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
                         )
1091 1091
                     );
1092 1092
                 }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1093
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094 1094
                     throw new EE_Error(
1095 1095
                         sprintf(
1096 1096
                             esc_html__(
@@ -1162,12 +1162,12 @@  discard block
 block discarded – undo
1162 1162
      */
1163 1163
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1164 1164
     {
1165
-        if (! isset($query_params[0])) {
1165
+        if ( ! isset($query_params[0])) {
1166 1166
             $query_params[0] = [];
1167 1167
         }
1168 1168
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1169 1169
         if ($conditions_from_id === null) {
1170
-            $query_params[0][ $this->primary_key_name() ] = $id;
1170
+            $query_params[0][$this->primary_key_name()] = $id;
1171 1171
         } else {
1172 1172
             // no primary key, so the $id must be from the get_index_primary_key_string()
1173 1173
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1187,7 +1187,7 @@  discard block
 block discarded – undo
1187 1187
      */
1188 1188
     public function get_one($query_params = [])
1189 1189
     {
1190
-        if (! is_array($query_params)) {
1190
+        if ( ! is_array($query_params)) {
1191 1191
             EE_Error::doing_it_wrong(
1192 1192
                 'EEM_Base::get_one',
1193 1193
                 sprintf(
@@ -1387,7 +1387,7 @@  discard block
 block discarded – undo
1387 1387
                 return [];
1388 1388
             }
1389 1389
         }
1390
-        if (! is_array($query_params)) {
1390
+        if ( ! is_array($query_params)) {
1391 1391
             EE_Error::doing_it_wrong(
1392 1392
                 'EEM_Base::_get_consecutive',
1393 1393
                 sprintf(
@@ -1399,7 +1399,7 @@  discard block
 block discarded – undo
1399 1399
             $query_params = [];
1400 1400
         }
1401 1401
         // let's add the where query param for consecutive look up.
1402
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1402
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1403 1403
         $query_params['limit']                 = $limit;
1404 1404
         // set direction
1405 1405
         $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
     {
1487 1487
         $field_settings = $this->field_settings_for($field_name);
1488 1488
         // if not a valid EE_Datetime_Field then throw error
1489
-        if (! $field_settings instanceof EE_Datetime_Field) {
1489
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1490 1490
             throw new EE_Error(
1491 1491
                 sprintf(
1492 1492
                     esc_html__(
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
      */
1644 1644
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1645 1645
     {
1646
-        if (! is_array($query_params)) {
1646
+        if ( ! is_array($query_params)) {
1647 1647
             EE_Error::doing_it_wrong(
1648 1648
                 'EEM_Base::update',
1649 1649
                 sprintf(
@@ -1693,7 +1693,7 @@  discard block
 block discarded – undo
1693 1693
             $wpdb_result = (array) $wpdb_result;
1694 1694
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1695 1695
             if ($this->has_primary_key_field()) {
1696
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1696
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1697 1697
             } else {
1698 1698
                 // 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)
1699 1699
                 $main_table_pk_value = null;
@@ -1709,7 +1709,7 @@  discard block
 block discarded – undo
1709 1709
                     // in this table, right? so insert a row in the current table, using any fields available
1710 1710
                     if (
1711 1711
                     ! (array_key_exists($this_table_pk_column, $wpdb_result)
1712
-                       && $wpdb_result[ $this_table_pk_column ])
1712
+                       && $wpdb_result[$this_table_pk_column])
1713 1713
                     ) {
1714 1714
                         $success = $this->_insert_into_specific_table(
1715 1715
                             $table_obj,
@@ -1717,7 +1717,7 @@  discard block
 block discarded – undo
1717 1717
                             $main_table_pk_value
1718 1718
                         );
1719 1719
                         // if we died here, report the error
1720
-                        if (! $success) {
1720
+                        if ( ! $success) {
1721 1721
                             return false;
1722 1722
                         }
1723 1723
                     }
@@ -1739,10 +1739,10 @@  discard block
 block discarded – undo
1739 1739
                 $model_objs_affected_ids     = [];
1740 1740
                 foreach ($models_affected_key_columns as $row) {
1741 1741
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1742
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1742
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1743 1743
                 }
1744 1744
             }
1745
-            if (! $model_objs_affected_ids) {
1745
+            if ( ! $model_objs_affected_ids) {
1746 1746
                 // wait wait wait- if nothing was affected let's stop here
1747 1747
                 return 0;
1748 1748
             }
@@ -1765,8 +1765,8 @@  discard block
 block discarded – undo
1765 1765
             }
1766 1766
         }
1767 1767
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1769
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1768
+        $SQL              = "UPDATE ".$model_query_info->get_full_join_sql()
1769
+                            . " SET ".$this->_construct_update_sql($fields_n_values)
1770 1770
                             . $model_query_info->get_where_sql();
1771 1771
         // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1772 1772
         $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
@@ -1780,7 +1780,7 @@  discard block
 block discarded – undo
1780 1780
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1781 1781
          */
1782 1782
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1783
-        return $rows_affected;// how many supposedly got updated
1783
+        return $rows_affected; // how many supposedly got updated
1784 1784
     }
1785 1785
 
1786 1786
 
@@ -1811,7 +1811,7 @@  discard block
 block discarded – undo
1811 1811
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1812 1812
         $select_expressions = $field->get_qualified_column();
1813 1813
         $SQL                =
1814
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1814
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1815 1815
         return $this->_do_wpdb_query('get_col', [$SQL]);
1816 1816
     }
1817 1817
 
@@ -1831,7 +1831,7 @@  discard block
 block discarded – undo
1831 1831
     {
1832 1832
         $query_params['limit'] = 1;
1833 1833
         $col                   = $this->get_col($query_params, $field_to_select);
1834
-        if (! empty($col)) {
1834
+        if ( ! empty($col)) {
1835 1835
             return reset($col);
1836 1836
         }
1837 1837
         return null;
@@ -1861,7 +1861,7 @@  discard block
 block discarded – undo
1861 1861
             $value_sql       = $prepared_value === null
1862 1862
                 ? 'NULL'
1863 1863
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1864
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1864
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1865 1865
         }
1866 1866
         return implode(",", $cols_n_values);
1867 1867
     }
@@ -1991,9 +1991,9 @@  discard block
 block discarded – undo
1991 1991
         if ($deletion_where_query_part) {
1992 1992
             $model_query_info = $this->_create_model_query_info_carrier($query_params);
1993 1993
             $table_aliases    = implode(', ', array_keys($this->_tables));
1994
-            $SQL              = "DELETE " . $table_aliases
1995
-                                . " FROM " . $model_query_info->get_full_join_sql()
1996
-                                . " WHERE " . $deletion_where_query_part;
1994
+            $SQL              = "DELETE ".$table_aliases
1995
+                                . " FROM ".$model_query_info->get_full_join_sql()
1996
+                                . " WHERE ".$deletion_where_query_part;
1997 1997
             $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1998 1998
         } else {
1999 1999
             $rows_deleted = 0;
@@ -2004,12 +2004,12 @@  discard block
 block discarded – undo
2004 2004
         if (
2005 2005
             $this->has_primary_key_field()
2006 2006
             && $rows_deleted !== false
2007
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2007
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2008 2008
         ) {
2009
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2009
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2010 2010
             foreach ($ids_for_removal as $id) {
2011
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2012
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2011
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2012
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2013 2013
                 }
2014 2014
             }
2015 2015
 
@@ -2049,7 +2049,7 @@  discard block
 block discarded – undo
2049 2049
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2050 2050
          */
2051 2051
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2052
-        return $rows_deleted;// how many supposedly got deleted
2052
+        return $rows_deleted; // how many supposedly got deleted
2053 2053
     }
2054 2054
 
2055 2055
 
@@ -2145,15 +2145,15 @@  discard block
 block discarded – undo
2145 2145
                 if (
2146 2146
                     $allow_blocking
2147 2147
                     && $this->delete_is_blocked_by_related_models(
2148
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2148
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2149 2149
                     )
2150 2150
                 ) {
2151 2151
                     continue;
2152 2152
                 }
2153 2153
                 // primary table deletes
2154
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2155
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2156
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2154
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2155
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2156
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2157 2157
                 }
2158 2158
             }
2159 2159
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2162,8 +2162,8 @@  discard block
 block discarded – undo
2162 2162
                 $ids_to_delete_indexed_by_column_for_row = [];
2163 2163
                 foreach ($fields as $cpk_field) {
2164 2164
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2165
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2166
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2165
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2166
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2167 2167
                     }
2168 2168
                 }
2169 2169
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2203,7 +2203,7 @@  discard block
 block discarded – undo
2203 2203
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2204 2204
                 // make sure we have unique $ids
2205 2205
                 $ids     = array_unique($ids);
2206
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2206
+                $query[] = $column.' IN('.implode(',', $ids).')';
2207 2207
             }
2208 2208
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2209 2209
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2211,7 +2211,7 @@  discard block
 block discarded – undo
2211 2211
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2212 2212
                 $values_for_each_combined_primary_key_for_a_row = [];
2213 2213
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2214
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2214
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2215 2215
                 }
2216 2216
                 $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2217 2217
                 $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
@@ -2284,9 +2284,9 @@  discard block
 block discarded – undo
2284 2284
                 $column_to_count = '*';
2285 2285
             }
2286 2286
         }
2287
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2287
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2288 2288
         $SQL             =
2289
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2290 2290
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2291 2291
     }
2292 2292
 
@@ -2310,7 +2310,7 @@  discard block
 block discarded – undo
2310 2310
             $field_obj = $this->get_primary_key_field();
2311 2311
         }
2312 2312
         $column_to_count = $field_obj->get_qualified_column();
2313
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2313
+        $SQL             = "SELECT SUM(".$column_to_count.")"
2314 2314
                            . $this->_construct_2nd_half_of_select_query($model_query_info);
2315 2315
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2316 2316
         $data_type       = $field_obj->get_wpdb_data_type();
@@ -2337,7 +2337,7 @@  discard block
 block discarded – undo
2337 2337
         // if we're in maintenance mode level 2, DON'T run any queries
2338 2338
         // because level 2 indicates the database needs updating and
2339 2339
         // is probably out of sync with the code
2340
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2341 2341
             throw new EE_Error(
2342 2342
                 sprintf(
2343 2343
                     esc_html__(
@@ -2348,7 +2348,7 @@  discard block
 block discarded – undo
2348 2348
             );
2349 2349
         }
2350 2350
         global $wpdb;
2351
-        if (! method_exists($wpdb, $wpdb_method)) {
2351
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2352 2352
             throw new EE_Error(
2353 2353
                 sprintf(
2354 2354
                     esc_html__(
@@ -2367,7 +2367,7 @@  discard block
 block discarded – undo
2367 2367
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2368 2368
         if (WP_DEBUG) {
2369 2369
             $wpdb->show_errors($old_show_errors_value);
2370
-            if (! empty($wpdb->last_error)) {
2370
+            if ( ! empty($wpdb->last_error)) {
2371 2371
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2372 2372
             }
2373 2373
             if ($result === false) {
@@ -2437,7 +2437,7 @@  discard block
 block discarded – undo
2437 2437
                     // ummmm... you in trouble
2438 2438
                     return $result;
2439 2439
             }
2440
-            if (! empty($error_message)) {
2440
+            if ( ! empty($error_message)) {
2441 2441
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2442 2442
                 trigger_error($error_message);
2443 2443
             }
@@ -2514,11 +2514,11 @@  discard block
 block discarded – undo
2514 2514
      */
2515 2515
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2516 2516
     {
2517
-        return " FROM " . $model_query_info->get_full_join_sql() .
2518
-               $model_query_info->get_where_sql() .
2519
-               $model_query_info->get_group_by_sql() .
2520
-               $model_query_info->get_having_sql() .
2521
-               $model_query_info->get_order_by_sql() .
2517
+        return " FROM ".$model_query_info->get_full_join_sql().
2518
+               $model_query_info->get_where_sql().
2519
+               $model_query_info->get_group_by_sql().
2520
+               $model_query_info->get_having_sql().
2521
+               $model_query_info->get_order_by_sql().
2522 2522
                $model_query_info->get_limit_sql();
2523 2523
     }
2524 2524
 
@@ -2711,12 +2711,12 @@  discard block
 block discarded – undo
2711 2711
         $related_model = $this->get_related_model_obj($model_name);
2712 2712
         // we're just going to use the query params on the related model's normal get_all query,
2713 2713
         // except add a condition to say to match the current mod
2714
-        if (! isset($query_params['default_where_conditions'])) {
2714
+        if ( ! isset($query_params['default_where_conditions'])) {
2715 2715
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2716 2716
         }
2717 2717
         $this_model_name                                                 = $this->get_this_model_name();
2718 2718
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2719
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2719
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2720 2720
         return $related_model->count($query_params, $field_to_count, $distinct);
2721 2721
     }
2722 2722
 
@@ -2737,7 +2737,7 @@  discard block
 block discarded – undo
2737 2737
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2738 2738
     {
2739 2739
         $related_model = $this->get_related_model_obj($model_name);
2740
-        if (! is_array($query_params)) {
2740
+        if ( ! is_array($query_params)) {
2741 2741
             EE_Error::doing_it_wrong(
2742 2742
                 'EEM_Base::sum_related',
2743 2743
                 sprintf(
@@ -2750,12 +2750,12 @@  discard block
 block discarded – undo
2750 2750
         }
2751 2751
         // we're just going to use the query params on the related model's normal get_all query,
2752 2752
         // except add a condition to say to match the current mod
2753
-        if (! isset($query_params['default_where_conditions'])) {
2753
+        if ( ! isset($query_params['default_where_conditions'])) {
2754 2754
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2755 2755
         }
2756 2756
         $this_model_name                                                 = $this->get_this_model_name();
2757 2757
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2758
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2758
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2759 2759
         return $related_model->sum($query_params, $field_to_sum);
2760 2760
     }
2761 2761
 
@@ -2807,7 +2807,7 @@  discard block
 block discarded – undo
2807 2807
                 $field_with_model_name = $field;
2808 2808
             }
2809 2809
         }
2810
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2810
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2811 2811
             throw new EE_Error(
2812 2812
                 sprintf(
2813 2813
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2946,14 +2946,14 @@  discard block
 block discarded – undo
2946 2946
                 || $this->get_primary_key_field()
2947 2947
                    instanceof
2948 2948
                    EE_Primary_Key_String_Field)
2949
-            && isset($fields_n_values[ $this->primary_key_name() ])
2949
+            && isset($fields_n_values[$this->primary_key_name()])
2950 2950
         ) {
2951
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2951
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2952 2952
         }
2953 2953
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2954 2954
             $uniqueness_where_params                              =
2955 2955
                 array_intersect_key($fields_n_values, $unique_index->fields());
2956
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2956
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2957 2957
         }
2958 2958
         // if there is nothing to base this search on, then we shouldn't find anything
2959 2959
         if (empty($query_params)) {
@@ -3030,16 +3030,16 @@  discard block
 block discarded – undo
3030 3030
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3031 3031
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3032 3032
             if ($prepared_value !== null) {
3033
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3033
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3034 3034
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3035 3035
             }
3036 3036
         }
3037 3037
         if ($table instanceof EE_Secondary_Table && $new_id) {
3038 3038
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3039 3039
             // so add the fk to the main table as a column
3040
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3040
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3041 3041
             $format_for_insertion[]                              =
3042
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3042
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3043 3043
         }
3044 3044
         // insert the new entry
3045 3045
         $result = $this->_do_wpdb_query(
@@ -3056,7 +3056,7 @@  discard block
 block discarded – undo
3056 3056
             }
3057 3057
             // it's not an auto-increment primary key, so
3058 3058
             // it must have been supplied
3059
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3059
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3060 3060
         }
3061 3061
         // we can't return a  primary key because there is none. instead return
3062 3062
         // a unique string indicating this model
@@ -3080,14 +3080,14 @@  discard block
 block discarded – undo
3080 3080
         if (
3081 3081
             ! $field_obj->is_nullable()
3082 3082
             && (
3083
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3084
-                || $fields_n_values[ $field_obj->get_name() ] === null
3083
+                ! isset($fields_n_values[$field_obj->get_name()])
3084
+                || $fields_n_values[$field_obj->get_name()] === null
3085 3085
             )
3086 3086
         ) {
3087
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3087
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3088 3088
         }
3089
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3090
-            ? $fields_n_values[ $field_obj->get_name() ]
3089
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3090
+            ? $fields_n_values[$field_obj->get_name()]
3091 3091
             : null;
3092 3092
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3093 3093
     }
@@ -3188,7 +3188,7 @@  discard block
 block discarded – undo
3188 3188
      */
3189 3189
     public function get_table_obj_by_alias($table_alias = '')
3190 3190
     {
3191
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3191
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3192 3192
     }
3193 3193
 
3194 3194
 
@@ -3202,7 +3202,7 @@  discard block
 block discarded – undo
3202 3202
         $other_tables = [];
3203 3203
         foreach ($this->_tables as $table_alias => $table) {
3204 3204
             if ($table instanceof EE_Secondary_Table) {
3205
-                $other_tables[ $table_alias ] = $table;
3205
+                $other_tables[$table_alias] = $table;
3206 3206
             }
3207 3207
         }
3208 3208
         return $other_tables;
@@ -3217,7 +3217,7 @@  discard block
 block discarded – undo
3217 3217
      */
3218 3218
     public function _get_fields_for_table($table_alias)
3219 3219
     {
3220
-        return $this->_fields[ $table_alias ];
3220
+        return $this->_fields[$table_alias];
3221 3221
     }
3222 3222
 
3223 3223
 
@@ -3246,7 +3246,7 @@  discard block
 block discarded – undo
3246 3246
                     $query_info_carrier,
3247 3247
                     'group_by'
3248 3248
                 );
3249
-            } elseif (! empty($query_params['group_by'])) {
3249
+            } elseif ( ! empty($query_params['group_by'])) {
3250 3250
                 $this->_extract_related_model_info_from_query_param(
3251 3251
                     $query_params['group_by'],
3252 3252
                     $query_info_carrier,
@@ -3268,7 +3268,7 @@  discard block
 block discarded – undo
3268 3268
                     $query_info_carrier,
3269 3269
                     'order_by'
3270 3270
                 );
3271
-            } elseif (! empty($query_params['order_by'])) {
3271
+            } elseif ( ! empty($query_params['order_by'])) {
3272 3272
                 $this->_extract_related_model_info_from_query_param(
3273 3273
                     $query_params['order_by'],
3274 3274
                     $query_info_carrier,
@@ -3303,7 +3303,7 @@  discard block
 block discarded – undo
3303 3303
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3304 3304
         $query_param_type
3305 3305
     ) {
3306
-        if (! empty($sub_query_params)) {
3306
+        if ( ! empty($sub_query_params)) {
3307 3307
             $sub_query_params = (array) $sub_query_params;
3308 3308
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3309 3309
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3319,7 +3319,7 @@  discard block
 block discarded – undo
3319 3319
                 $query_param_sans_stars =
3320 3320
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3321 3321
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3322
-                    if (! is_array($possibly_array_of_params)) {
3322
+                    if ( ! is_array($possibly_array_of_params)) {
3323 3323
                         throw new EE_Error(
3324 3324
                             sprintf(
3325 3325
                                 esc_html__(
@@ -3345,7 +3345,7 @@  discard block
 block discarded – undo
3345 3345
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3346 3346
                     // indicating that $possible_array_of_params[1] is actually a field name,
3347 3347
                     // from which we should extract query parameters!
3348
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3349 3349
                         throw new EE_Error(
3350 3350
                             sprintf(
3351 3351
                                 esc_html__(
@@ -3385,8 +3385,8 @@  discard block
 block discarded – undo
3385 3385
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3386 3386
         $query_param_type
3387 3387
     ) {
3388
-        if (! empty($sub_query_params)) {
3389
-            if (! is_array($sub_query_params)) {
3388
+        if ( ! empty($sub_query_params)) {
3389
+            if ( ! is_array($sub_query_params)) {
3390 3390
                 throw new EE_Error(
3391 3391
                     sprintf(
3392 3392
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3424,7 +3424,7 @@  discard block
 block discarded – undo
3424 3424
      */
3425 3425
     public function _create_model_query_info_carrier($query_params)
3426 3426
     {
3427
-        if (! is_array($query_params)) {
3427
+        if ( ! is_array($query_params)) {
3428 3428
             EE_Error::doing_it_wrong(
3429 3429
                 'EEM_Base::_create_model_query_info_carrier',
3430 3430
                 sprintf(
@@ -3457,7 +3457,7 @@  discard block
 block discarded – undo
3457 3457
             // only include if related to a cpt where no password has been set
3458 3458
             $query_params[0]['OR*nopassword'] = [
3459 3459
                 $where_param_key_for_password       => '',
3460
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3460
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3461 3461
             ];
3462 3462
         }
3463 3463
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3511,7 +3511,7 @@  discard block
 block discarded – undo
3511 3511
         // set limit
3512 3512
         if (array_key_exists('limit', $query_params)) {
3513 3513
             if (is_array($query_params['limit'])) {
3514
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3515 3515
                     $e = sprintf(
3516 3516
                         esc_html__(
3517 3517
                             "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)",
@@ -3519,12 +3519,12 @@  discard block
 block discarded – undo
3519 3519
                         ),
3520 3520
                         http_build_query($query_params['limit'])
3521 3521
                     );
3522
-                    throw new EE_Error($e . "|" . $e);
3522
+                    throw new EE_Error($e."|".$e);
3523 3523
                 }
3524 3524
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3525
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3526
-            } elseif (! empty($query_params['limit'])) {
3527
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3525
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3526
+            } elseif ( ! empty($query_params['limit'])) {
3527
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3528 3528
             }
3529 3529
         }
3530 3530
         // set order by
@@ -3556,10 +3556,10 @@  discard block
 block discarded – undo
3556 3556
                 $order_array = [];
3557 3557
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3558 3558
                     $order         = $this->_extract_order($order);
3559
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3559
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3560 3560
                 }
3561
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3562
-            } elseif (! empty($query_params['order_by'])) {
3561
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3562
+            } elseif ( ! empty($query_params['order_by'])) {
3563 3563
                 $this->_extract_related_model_info_from_query_param(
3564 3564
                     $query_params['order_by'],
3565 3565
                     $query_object,
@@ -3570,7 +3570,7 @@  discard block
 block discarded – undo
3570 3570
                     ? $this->_extract_order($query_params['order'])
3571 3571
                     : 'DESC';
3572 3572
                 $query_object->set_order_by_sql(
3573
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3573
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3574 3574
                 );
3575 3575
             }
3576 3576
         }
@@ -3582,7 +3582,7 @@  discard block
 block discarded – undo
3582 3582
         ) {
3583 3583
             $pk_field = $this->get_primary_key_field();
3584 3584
             $order    = $this->_extract_order($query_params['order']);
3585
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3585
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3586 3586
         }
3587 3587
         // set group by
3588 3588
         if (array_key_exists('group_by', $query_params)) {
@@ -3592,10 +3592,10 @@  discard block
 block discarded – undo
3592 3592
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3593 3593
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3594 3594
                 }
3595
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3596
-            } elseif (! empty($query_params['group_by'])) {
3595
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3596
+            } elseif ( ! empty($query_params['group_by'])) {
3597 3597
                 $query_object->set_group_by_sql(
3598
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3598
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3599 3599
                 );
3600 3600
             }
3601 3601
         }
@@ -3605,7 +3605,7 @@  discard block
 block discarded – undo
3605 3605
         }
3606 3606
         // now, just verify they didn't pass anything wack
3607 3607
         foreach ($query_params as $query_key => $query_value) {
3608
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3608
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3609 3609
                 throw new EE_Error(
3610 3610
                     sprintf(
3611 3611
                         esc_html__(
@@ -3709,7 +3709,7 @@  discard block
 block discarded – undo
3709 3709
         $where_query_params = []
3710 3710
     ) {
3711 3711
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3712
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3713 3713
             throw new EE_Error(
3714 3714
                 sprintf(
3715 3715
                     esc_html__(
@@ -3739,7 +3739,7 @@  discard block
 block discarded – undo
3739 3739
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3740 3740
                 continue;
3741 3741
             }
3742
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3742
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3743 3743
                 $related_model_universal_where_params,
3744 3744
                 $where_query_params,
3745 3745
                 $related_model,
@@ -3848,19 +3848,19 @@  discard block
 block discarded – undo
3848 3848
     ) {
3849 3849
         $null_friendly_where_conditions = [];
3850 3850
         $none_overridden                = true;
3851
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3851
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3852 3852
         foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3853
+            if (isset($provided_where_conditions[$key])) {
3854 3854
                 $none_overridden = false;
3855 3855
             } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3857 3857
             }
3858 3858
         }
3859 3859
         if ($none_overridden && $default_where_conditions) {
3860 3860
             if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3862 3862
                                                                                    . "."
3863
-                                                                                   . $model->primary_key_name() ] =
3863
+                                                                                   . $model->primary_key_name()] =
3864 3864
                     ['IS NULL'];
3865 3865
             }/*else{
3866 3866
                 //@todo NO PK, use other defaults
@@ -3969,7 +3969,7 @@  discard block
 block discarded – undo
3969 3969
             foreach ($tables as $table_obj) {
3970 3970
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3971 3971
                                        . $table_obj->get_fully_qualified_pk_column();
3972
-                if (! in_array($qualified_pk_column, $selects)) {
3972
+                if ( ! in_array($qualified_pk_column, $selects)) {
3973 3973
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3974 3974
                 }
3975 3975
             }
@@ -4121,9 +4121,9 @@  discard block
 block discarded – undo
4121 4121
         $query_parameter_type
4122 4122
     ) {
4123 4123
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4124
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4125 4125
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4126
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4127 4127
                 if ($possible_join_string === '') {
4128 4128
                     // nothing left to $query_param
4129 4129
                     // we should actually end in a field name, not a model like this!
@@ -4255,7 +4255,7 @@  discard block
 block discarded – undo
4255 4255
     {
4256 4256
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4257 4257
         if ($SQL) {
4258
-            return " WHERE " . $SQL;
4258
+            return " WHERE ".$SQL;
4259 4259
         }
4260 4260
         return '';
4261 4261
     }
@@ -4273,7 +4273,7 @@  discard block
 block discarded – undo
4273 4273
     {
4274 4274
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4275 4275
         if ($SQL) {
4276
-            return " HAVING " . $SQL;
4276
+            return " HAVING ".$SQL;
4277 4277
         }
4278 4278
         return '';
4279 4279
     }
@@ -4296,7 +4296,7 @@  discard block
 block discarded – undo
4296 4296
             $query_param =
4297 4297
                 $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4298 4298
                     $query_param
4299
-                );// str_replace("*",'',$query_param);
4299
+                ); // str_replace("*",'',$query_param);
4300 4300
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4301 4301
                 switch ($query_param) {
4302 4302
                     case 'not':
@@ -4330,7 +4330,7 @@  discard block
 block discarded – undo
4330 4330
             } else {
4331 4331
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4332 4332
                 // if it's not a normal field, maybe it's a custom selection?
4333
-                if (! $field_obj) {
4333
+                if ( ! $field_obj) {
4334 4334
                     if ($this->_custom_selections instanceof CustomSelects) {
4335 4335
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4336 4336
                     } else {
@@ -4346,7 +4346,7 @@  discard block
 block discarded – undo
4346 4346
                     }
4347 4347
                 }
4348 4348
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4349
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4349
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4350 4350
             }
4351 4351
         }
4352 4352
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4368,7 +4368,7 @@  discard block
 block discarded – undo
4368 4368
                 $field->get_model_name(),
4369 4369
                 $query_param
4370 4370
             );
4371
-            return $table_alias_prefix . $field->get_qualified_column();
4371
+            return $table_alias_prefix.$field->get_qualified_column();
4372 4372
         }
4373 4373
         if (
4374 4374
             $this->_custom_selections instanceof CustomSelects
@@ -4425,7 +4425,7 @@  discard block
 block discarded – undo
4425 4425
     {
4426 4426
         if (is_array($op_and_value)) {
4427 4427
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4428
-            if (! $operator) {
4428
+            if ( ! $operator) {
4429 4429
                 $php_array_like_string = [];
4430 4430
                 foreach ($op_and_value as $key => $value) {
4431 4431
                     $php_array_like_string[] = "$key=>$value";
@@ -4447,14 +4447,14 @@  discard block
 block discarded – undo
4447 4447
         }
4448 4448
         // check to see if the value is actually another field
4449 4449
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4450
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4450
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4451 4451
         }
4452 4452
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4453 4453
             // in this case, the value should be an array, or at least a comma-separated list
4454 4454
             // it will need to handle a little differently
4455 4455
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4456 4456
             // note: $cleaned_value has already been run through $wpdb->prepare()
4457
-            return $operator . SP . $cleaned_value;
4457
+            return $operator.SP.$cleaned_value;
4458 4458
         }
4459 4459
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4460 4460
             // the value should be an array with count of two.
@@ -4470,7 +4470,7 @@  discard block
 block discarded – undo
4470 4470
                 );
4471 4471
             }
4472 4472
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4473
-            return $operator . SP . $cleaned_value;
4473
+            return $operator.SP.$cleaned_value;
4474 4474
         }
4475 4475
         if (in_array($operator, $this->valid_null_style_operators())) {
4476 4476
             if ($value !== null) {
@@ -4490,10 +4490,10 @@  discard block
 block discarded – undo
4490 4490
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4491 4491
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4492 4492
             // remove other junk. So just treat it as a string.
4493
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4493
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4494 4494
         }
4495
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4496
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4495
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4496
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4497 4497
         }
4498 4498
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4499 4499
             throw new EE_Error(
@@ -4507,7 +4507,7 @@  discard block
 block discarded – undo
4507 4507
                 )
4508 4508
             );
4509 4509
         }
4510
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4511 4511
             throw new EE_Error(
4512 4512
                 sprintf(
4513 4513
                     esc_html__(
@@ -4546,7 +4546,7 @@  discard block
 block discarded – undo
4546 4546
         foreach ($values as $value) {
4547 4547
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4548 4548
         }
4549
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4549
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4550 4550
     }
4551 4551
 
4552 4552
 
@@ -4586,7 +4586,7 @@  discard block
 block discarded – undo
4586 4586
                                 . $main_table->get_table_name()
4587 4587
                                 . " WHERE FALSE";
4588 4588
         }
4589
-        return "(" . implode(",", $cleaned_values) . ")";
4589
+        return "(".implode(",", $cleaned_values).")";
4590 4590
     }
4591 4591
 
4592 4592
 
@@ -4605,7 +4605,7 @@  discard block
 block discarded – undo
4605 4605
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4606 4606
             );
4607 4607
         } //$field_obj should really just be a data type
4608
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4609 4609
             throw new EE_Error(
4610 4610
                 sprintf(
4611 4611
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4642,14 +4642,14 @@  discard block
 block discarded – undo
4642 4642
             );
4643 4643
         }
4644 4644
         $number_of_parts       = count($query_param_parts);
4645
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4645
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4646 4646
         if ($number_of_parts === 1) {
4647 4647
             $field_name = $last_query_param_part;
4648 4648
             $model_obj  = $this;
4649 4649
         } else {// $number_of_parts >= 2
4650 4650
             // the last part is the column name, and there are only 2parts. therefore...
4651 4651
             $field_name = $last_query_param_part;
4652
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4652
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4653 4653
         }
4654 4654
         try {
4655 4655
             return $model_obj->field_settings_for($field_name);
@@ -4670,7 +4670,7 @@  discard block
 block discarded – undo
4670 4670
     public function _get_qualified_column_for_field($field_name)
4671 4671
     {
4672 4672
         $all_fields = $this->field_settings();
4673
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4673
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4674 4674
         if ($field) {
4675 4675
             return $field->get_qualified_column();
4676 4676
         }
@@ -4740,10 +4740,10 @@  discard block
 block discarded – undo
4740 4740
      */
4741 4741
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4742 4742
     {
4743
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4743
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4744 4744
         $qualified_columns = [];
4745 4745
         foreach ($this->field_settings() as $field_name => $field) {
4746
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4746
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4747 4747
         }
4748 4748
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4749 4749
     }
@@ -4767,11 +4767,11 @@  discard block
 block discarded – undo
4767 4767
             if ($table_obj instanceof EE_Primary_Table) {
4768 4768
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4769 4769
                     ? $table_obj->get_select_join_limit($limit)
4770
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4770
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4771 4771
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4772 4772
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4773 4773
                     ? $table_obj->get_select_join_limit_join($limit)
4774
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4774
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4775 4775
             }
4776 4776
         }
4777 4777
         return $SQL;
@@ -4841,7 +4841,7 @@  discard block
 block discarded – undo
4841 4841
         foreach ($this->field_settings() as $field_obj) {
4842 4842
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4843 4843
             /** @var $field_obj EE_Model_Field_Base */
4844
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4844
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4845 4845
         }
4846 4846
         return $data_types;
4847 4847
     }
@@ -4856,8 +4856,8 @@  discard block
 block discarded – undo
4856 4856
      */
4857 4857
     public function get_related_model_obj($model_name)
4858 4858
     {
4859
-        $model_classname = "EEM_" . $model_name;
4860
-        if (! class_exists($model_classname)) {
4859
+        $model_classname = "EEM_".$model_name;
4860
+        if ( ! class_exists($model_classname)) {
4861 4861
             throw new EE_Error(
4862 4862
                 sprintf(
4863 4863
                     esc_html__(
@@ -4869,7 +4869,7 @@  discard block
 block discarded – undo
4869 4869
                 )
4870 4870
             );
4871 4871
         }
4872
-        return call_user_func($model_classname . "::instance");
4872
+        return call_user_func($model_classname."::instance");
4873 4873
     }
4874 4874
 
4875 4875
 
@@ -4896,7 +4896,7 @@  discard block
 block discarded – undo
4896 4896
         $belongs_to_relations = [];
4897 4897
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4898 4898
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4899
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4899
+                $belongs_to_relations[$model_name] = $relation_obj;
4900 4900
             }
4901 4901
         }
4902 4902
         return $belongs_to_relations;
@@ -4913,7 +4913,7 @@  discard block
 block discarded – undo
4913 4913
     public function related_settings_for($relation_name)
4914 4914
     {
4915 4915
         $relatedModels = $this->relation_settings();
4916
-        if (! array_key_exists($relation_name, $relatedModels)) {
4916
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4917 4917
             throw new EE_Error(
4918 4918
                 sprintf(
4919 4919
                     esc_html__(
@@ -4926,7 +4926,7 @@  discard block
 block discarded – undo
4926 4926
                 )
4927 4927
             );
4928 4928
         }
4929
-        return $relatedModels[ $relation_name ];
4929
+        return $relatedModels[$relation_name];
4930 4930
     }
4931 4931
 
4932 4932
 
@@ -4942,7 +4942,7 @@  discard block
 block discarded – undo
4942 4942
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4943 4943
     {
4944 4944
         $fieldSettings = $this->field_settings($include_db_only_fields);
4945
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4945
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4946 4946
             throw new EE_Error(
4947 4947
                 sprintf(
4948 4948
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4951,7 +4951,7 @@  discard block
 block discarded – undo
4951 4951
                 )
4952 4952
             );
4953 4953
         }
4954
-        return $fieldSettings[ $fieldName ];
4954
+        return $fieldSettings[$fieldName];
4955 4955
     }
4956 4956
 
4957 4957
 
@@ -4964,7 +4964,7 @@  discard block
 block discarded – undo
4964 4964
     public function has_field($fieldName)
4965 4965
     {
4966 4966
         $fieldSettings = $this->field_settings(true);
4967
-        if (isset($fieldSettings[ $fieldName ])) {
4967
+        if (isset($fieldSettings[$fieldName])) {
4968 4968
             return true;
4969 4969
         }
4970 4970
         return false;
@@ -4980,7 +4980,7 @@  discard block
 block discarded – undo
4980 4980
     public function has_relation($relation_name)
4981 4981
     {
4982 4982
         $relations = $this->relation_settings();
4983
-        if (isset($relations[ $relation_name ])) {
4983
+        if (isset($relations[$relation_name])) {
4984 4984
             return true;
4985 4985
         }
4986 4986
         return false;
@@ -5016,7 +5016,7 @@  discard block
 block discarded – undo
5016 5016
                     break;
5017 5017
                 }
5018 5018
             }
5019
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5020 5020
                 throw new EE_Error(
5021 5021
                     sprintf(
5022 5022
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5076,17 +5076,17 @@  discard block
 block discarded – undo
5076 5076
      */
5077 5077
     public function get_foreign_key_to($model_name)
5078 5078
     {
5079
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5079
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5080 5080
             foreach ($this->field_settings() as $field) {
5081 5081
                 if (
5082 5082
                     $field instanceof EE_Foreign_Key_Field_Base
5083 5083
                     && in_array($model_name, $field->get_model_names_pointed_to())
5084 5084
                 ) {
5085
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5085
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5086 5086
                     break;
5087 5087
                 }
5088 5088
             }
5089
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5089
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5090 5090
                 throw new EE_Error(
5091 5091
                     sprintf(
5092 5092
                         esc_html__(
@@ -5099,7 +5099,7 @@  discard block
 block discarded – undo
5099 5099
                 );
5100 5100
             }
5101 5101
         }
5102
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5102
+        return $this->_cache_foreign_key_to_fields[$model_name];
5103 5103
     }
5104 5104
 
5105 5105
 
@@ -5115,7 +5115,7 @@  discard block
 block discarded – undo
5115 5115
     {
5116 5116
         $table_alias_sans_model_relation_chain_prefix =
5117 5117
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5118
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5118
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5119 5119
     }
5120 5120
 
5121 5121
 
@@ -5133,7 +5133,7 @@  discard block
 block discarded – undo
5133 5133
                 $this->_cached_fields = [];
5134 5134
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5135 5135
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5136
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5136
+                        $this->_cached_fields[$field_name] = $field_obj;
5137 5137
                     }
5138 5138
                 }
5139 5139
             }
@@ -5144,8 +5144,8 @@  discard block
 block discarded – undo
5144 5144
             foreach ($this->_fields as $fields_corresponding_to_table) {
5145 5145
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5146 5146
                     /** @var $field_obj EE_Model_Field_Base */
5147
-                    if (! $field_obj->is_db_only_field()) {
5148
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5147
+                    if ( ! $field_obj->is_db_only_field()) {
5148
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5149 5149
                     }
5150 5150
                 }
5151 5151
             }
@@ -5186,12 +5186,12 @@  discard block
 block discarded – undo
5186 5186
                     $primary_key_field->get_qualified_column(),
5187 5187
                     $primary_key_field->get_table_column()
5188 5188
                 );
5189
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5189
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5190 5190
                     continue;
5191 5191
                 }
5192 5192
             }
5193 5193
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5194
-            if (! $classInstance) {
5194
+            if ( ! $classInstance) {
5195 5195
                 throw new EE_Error(
5196 5196
                     sprintf(
5197 5197
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5204,7 +5204,7 @@  discard block
 block discarded – undo
5204 5204
             $classInstance->set_timezone($this->get_timezone(), true);
5205 5205
             // make sure if there is any timezone setting present that we set the timezone for the object
5206 5206
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5207
-            $array_of_objects[ $key ] = $classInstance;
5207
+            $array_of_objects[$key] = $classInstance;
5208 5208
             // also, for all the relations of type BelongsTo, see if we can cache
5209 5209
             // those related models
5210 5210
             // (we could do this for other relations too, but if there are conditions
@@ -5248,9 +5248,9 @@  discard block
 block discarded – undo
5248 5248
         $results = [];
5249 5249
         if ($this->_custom_selections instanceof CustomSelects) {
5250 5250
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5251
-                if (isset($db_results_row[ $alias ])) {
5252
-                    $results[ $alias ] = $this->convertValueToDataType(
5253
-                        $db_results_row[ $alias ],
5251
+                if (isset($db_results_row[$alias])) {
5252
+                    $results[$alias] = $this->convertValueToDataType(
5253
+                        $db_results_row[$alias],
5254 5254
                         $this->_custom_selections->getDataTypeForAlias($alias)
5255 5255
                     );
5256 5256
                 }
@@ -5295,7 +5295,7 @@  discard block
 block discarded – undo
5295 5295
         $this_model_fields_and_values = [];
5296 5296
         // setup the row using default values;
5297 5297
         foreach ($this->field_settings() as $field_name => $field_obj) {
5298
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5298
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5299 5299
         }
5300 5300
         $className = $this->_get_class_name();
5301 5301
         return EE_Registry::instance()->load_class(
@@ -5316,20 +5316,20 @@  discard block
 block discarded – undo
5316 5316
      */
5317 5317
     public function instantiate_class_from_array_or_object($cols_n_values)
5318 5318
     {
5319
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5319
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5320 5320
             $cols_n_values = get_object_vars($cols_n_values);
5321 5321
         }
5322 5322
         $primary_key = null;
5323 5323
         // make sure the array only has keys that are fields/columns on this model
5324 5324
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5325
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5326
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5325
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5326
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5327 5327
         }
5328 5328
         $className = $this->_get_class_name();
5329 5329
         // check we actually found results that we can use to build our model object
5330 5330
         // if not, return null
5331 5331
         if ($this->has_primary_key_field()) {
5332
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5332
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5333 5333
                 return null;
5334 5334
             }
5335 5335
         } elseif ($this->unique_indexes()) {
@@ -5341,7 +5341,7 @@  discard block
 block discarded – undo
5341 5341
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5342 5342
         if ($primary_key) {
5343 5343
             $classInstance = $this->get_from_entity_map($primary_key);
5344
-            if (! $classInstance) {
5344
+            if ( ! $classInstance) {
5345 5345
                 $classInstance = EE_Registry::instance()->load_class(
5346 5346
                     $className,
5347 5347
                     [$this_model_fields_n_values, $this->get_timezone()],
@@ -5371,8 +5371,8 @@  discard block
 block discarded – undo
5371 5371
      */
5372 5372
     public function get_from_entity_map($id)
5373 5373
     {
5374
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5375
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5374
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5375
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id]
5376 5376
             : null;
5377 5377
     }
5378 5378
 
@@ -5395,7 +5395,7 @@  discard block
 block discarded – undo
5395 5395
     public function add_to_entity_map(EE_Base_Class $object)
5396 5396
     {
5397 5397
         $className = $this->_get_class_name();
5398
-        if (! $object instanceof $className) {
5398
+        if ( ! $object instanceof $className) {
5399 5399
             throw new EE_Error(
5400 5400
                 sprintf(
5401 5401
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5404,7 +5404,7 @@  discard block
 block discarded – undo
5404 5404
                 )
5405 5405
             );
5406 5406
         }
5407
-        if (! $object->ID()) {
5407
+        if ( ! $object->ID()) {
5408 5408
             throw new EE_Error(
5409 5409
                 sprintf(
5410 5410
                     esc_html__(
@@ -5420,7 +5420,7 @@  discard block
 block discarded – undo
5420 5420
         if ($classInstance) {
5421 5421
             return $classInstance;
5422 5422
         }
5423
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5423
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5424 5424
         return $object;
5425 5425
     }
5426 5426
 
@@ -5435,11 +5435,11 @@  discard block
 block discarded – undo
5435 5435
     public function clear_entity_map($id = null)
5436 5436
     {
5437 5437
         if (empty($id)) {
5438
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5438
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5439 5439
             return true;
5440 5440
         }
5441
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5442
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5441
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5442
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5443 5443
             return true;
5444 5444
         }
5445 5445
         return false;
@@ -5480,18 +5480,18 @@  discard block
 block discarded – undo
5480 5480
             // there is a primary key on this table and its not set. Use defaults for all its columns
5481 5481
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5482 5482
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5483
-                    if (! $field_obj->is_db_only_field()) {
5483
+                    if ( ! $field_obj->is_db_only_field()) {
5484 5484
                         // prepare field as if its coming from db
5485 5485
                         $prepared_value                            =
5486 5486
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5487
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5487
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5488 5488
                     }
5489 5489
                 }
5490 5490
             } else {
5491 5491
                 // the table's rows existed. Use their values
5492 5492
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5493
-                    if (! $field_obj->is_db_only_field()) {
5494
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5493
+                    if ( ! $field_obj->is_db_only_field()) {
5494
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5495 5495
                             $cols_n_values,
5496 5496
                             $field_obj->get_qualified_column(),
5497 5497
                             $field_obj->get_table_column()
@@ -5516,17 +5516,17 @@  discard block
 block discarded – undo
5516 5516
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5517 5517
         // does the field on the model relate to this column retrieved from the db?
5518 5518
         // or is it a db-only field? (not relating to the model)
5519
-        if (isset($cols_n_values[ $qualified_column ])) {
5520
-            $value = $cols_n_values[ $qualified_column ];
5521
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5522
-            $value = $cols_n_values[ $regular_column ];
5523
-        } elseif (! empty($this->foreign_key_aliases)) {
5519
+        if (isset($cols_n_values[$qualified_column])) {
5520
+            $value = $cols_n_values[$qualified_column];
5521
+        } elseif (isset($cols_n_values[$regular_column])) {
5522
+            $value = $cols_n_values[$regular_column];
5523
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5524 5524
             // no PK?  ok check if there is a foreign key alias set for this table
5525 5525
             // then check if that alias exists in the incoming data
5526 5526
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5527 5527
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5528
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5529
-                    $value = $cols_n_values[ $FK_alias ];
5528
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5529
+                    $value = $cols_n_values[$FK_alias];
5530 5530
                     break;
5531 5531
                 }
5532 5532
             }
@@ -5562,7 +5562,7 @@  discard block
 block discarded – undo
5562 5562
                     $obj_in_map->clear_cache($relation_name, null, true);
5563 5563
                 }
5564 5564
             }
5565
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5565
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5566 5566
             return $obj_in_map;
5567 5567
         }
5568 5568
         return $this->get_one_by_ID($id);
@@ -5614,7 +5614,7 @@  discard block
 block discarded – undo
5614 5614
      */
5615 5615
     private function _get_class_name()
5616 5616
     {
5617
-        return "EE_" . $this->get_this_model_name();
5617
+        return "EE_".$this->get_this_model_name();
5618 5618
     }
5619 5619
 
5620 5620
 
@@ -5660,7 +5660,7 @@  discard block
 block discarded – undo
5660 5660
     {
5661 5661
         $className = get_class($this);
5662 5662
         $tagName   = "FHEE__{$className}__{$methodName}";
5663
-        if (! has_filter($tagName)) {
5663
+        if ( ! has_filter($tagName)) {
5664 5664
             throw new EE_Error(
5665 5665
                 sprintf(
5666 5666
                     esc_html__(
@@ -5829,7 +5829,7 @@  discard block
 block discarded – undo
5829 5829
         $unique_indexes = [];
5830 5830
         foreach ($this->_indexes as $name => $index) {
5831 5831
             if ($index instanceof EE_Unique_Index) {
5832
-                $unique_indexes [ $name ] = $index;
5832
+                $unique_indexes [$name] = $index;
5833 5833
             }
5834 5834
         }
5835 5835
         return $unique_indexes;
@@ -5893,7 +5893,7 @@  discard block
 block discarded – undo
5893 5893
         $key_values_in_combined_pk = [];
5894 5894
         parse_str($index_primary_key_string, $key_values_in_combined_pk);
5895 5895
         foreach ($key_fields as $key_field_name => $field_obj) {
5896
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5896
+            if ( ! isset($key_values_in_combined_pk[$key_field_name])) {
5897 5897
                 return null;
5898 5898
             }
5899 5899
         }
@@ -5913,7 +5913,7 @@  discard block
 block discarded – undo
5913 5913
     {
5914 5914
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915 5915
         foreach ($keys_it_should_have as $key) {
5916
-            if (! isset($key_values[ $key ])) {
5916
+            if ( ! isset($key_values[$key])) {
5917 5917
                 return false;
5918 5918
             }
5919 5919
         }
@@ -5952,8 +5952,8 @@  discard block
 block discarded – undo
5952 5952
         }
5953 5953
         // even copies obviously won't have the same ID, so remove the primary key
5954 5954
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5955
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5956
+            unset($attributes_array[$this->primary_key_name()]);
5957 5957
         }
5958 5958
         if (isset($query_params[0])) {
5959 5959
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5975,7 +5975,7 @@  discard block
 block discarded – undo
5975 5975
      */
5976 5976
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5977 5977
     {
5978
-        if (! is_array($query_params)) {
5978
+        if ( ! is_array($query_params)) {
5979 5979
             EE_Error::doing_it_wrong(
5980 5980
                 'EEM_Base::get_one_copy',
5981 5981
                 sprintf(
@@ -6025,7 +6025,7 @@  discard block
 block discarded – undo
6025 6025
     private function _prepare_operator_for_sql($operator_supplied)
6026 6026
     {
6027 6027
         $sql_operator =
6028
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6028
+            isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6029 6029
                 : null;
6030 6030
         if ($sql_operator) {
6031 6031
             return $sql_operator;
@@ -6124,7 +6124,7 @@  discard block
 block discarded – undo
6124 6124
         $objs  = $this->get_all($query_params);
6125 6125
         $names = [];
6126 6126
         foreach ($objs as $obj) {
6127
-            $names[ $obj->ID() ] = $obj->name();
6127
+            $names[$obj->ID()] = $obj->name();
6128 6128
         }
6129 6129
         return $names;
6130 6130
     }
@@ -6144,7 +6144,7 @@  discard block
 block discarded – undo
6144 6144
      */
6145 6145
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6146 6146
     {
6147
-        if (! $this->has_primary_key_field()) {
6147
+        if ( ! $this->has_primary_key_field()) {
6148 6148
             if (WP_DEBUG) {
6149 6149
                 EE_Error::add_error(
6150 6150
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6157,7 +6157,7 @@  discard block
 block discarded – undo
6157 6157
         $IDs = [];
6158 6158
         foreach ($model_objects as $model_object) {
6159 6159
             $id = $model_object->ID();
6160
-            if (! $id) {
6160
+            if ( ! $id) {
6161 6161
                 if ($filter_out_empty_ids) {
6162 6162
                     continue;
6163 6163
                 }
@@ -6207,22 +6207,22 @@  discard block
 block discarded – undo
6207 6207
         EEM_Base::verify_is_valid_cap_context($context);
6208 6208
         // check if we ought to run the restriction generator first
6209 6209
         if (
6210
-            isset($this->_cap_restriction_generators[ $context ])
6211
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6212
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6210
+            isset($this->_cap_restriction_generators[$context])
6211
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6212
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6213 6213
         ) {
6214
-            $this->_cap_restrictions[ $context ] = array_merge(
6215
-                $this->_cap_restrictions[ $context ],
6216
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6214
+            $this->_cap_restrictions[$context] = array_merge(
6215
+                $this->_cap_restrictions[$context],
6216
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6217 6217
             );
6218 6218
         }
6219 6219
         // and make sure we've finalized the construction of each restriction
6220
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6220
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6221 6221
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6222 6222
                 $where_conditions_obj->_finalize_construct($this);
6223 6223
             }
6224 6224
         }
6225
-        return $this->_cap_restrictions[ $context ];
6225
+        return $this->_cap_restrictions[$context];
6226 6226
     }
6227 6227
 
6228 6228
 
@@ -6252,9 +6252,9 @@  discard block
 block discarded – undo
6252 6252
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6253 6253
             if (
6254 6254
             ! EE_Capabilities::instance()
6255
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6255
+                             ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6256 6256
             ) {
6257
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6257
+                $missing_caps[$cap] = $restriction_if_no_cap;
6258 6258
             }
6259 6259
         }
6260 6260
         return $missing_caps;
@@ -6287,8 +6287,8 @@  discard block
 block discarded – undo
6287 6287
     public function cap_action_for_context($context)
6288 6288
     {
6289 6289
         $mapping = $this->cap_contexts_to_cap_action_map();
6290
-        if (isset($mapping[ $context ])) {
6291
-            return $mapping[ $context ];
6290
+        if (isset($mapping[$context])) {
6291
+            return $mapping[$context];
6292 6292
         }
6293 6293
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6294 6294
             return $action;
@@ -6409,7 +6409,7 @@  discard block
 block discarded – undo
6409 6409
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6410 6410
             if (
6411 6411
                 $query_param_key === $logic_query_param_key
6412
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6412
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6413 6413
             ) {
6414 6414
                 return true;
6415 6415
             }
@@ -6467,7 +6467,7 @@  discard block
 block discarded – undo
6467 6467
         if ($password_field instanceof EE_Password_Field) {
6468 6468
             $field_names = $password_field->protectedFields();
6469 6469
             foreach ($field_names as $field_name) {
6470
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6470
+                $fields[$field_name] = $this->field_settings_for($field_name);
6471 6471
             }
6472 6472
         }
6473 6473
         return $fields;
@@ -6493,7 +6493,7 @@  discard block
 block discarded – undo
6493 6493
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6494 6494
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6495 6495
         }
6496
-        if (! is_array($model_obj_or_fields_n_values)) {
6496
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6497 6497
             throw new UnexpectedEntityException(
6498 6498
                 $model_obj_or_fields_n_values,
6499 6499
                 'EE_Base_Class',
@@ -6573,7 +6573,7 @@  discard block
 block discarded – undo
6573 6573
                 )
6574 6574
             );
6575 6575
         }
6576
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6576
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6577 6577
     }
6578 6578
 
6579 6579
 
Please login to merge, or discard this patch.