Completed
Pull Request — master (#802)
by Darren
09:33
created
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6226 added lines, -6226 removed lines patch added patch discarded remove patch
@@ -34,6232 +34,6232 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error(
520
-                sprintf(
521
-                    __(
522
-                        '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.',
523
-                        'event_espresso'
524
-                    ),
525
-                    get_class($this)
526
-                )
527
-            );
528
-        }
529
-        /**
530
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
-         */
532
-        if (empty(EEM_Base::$_model_query_blog_id)) {
533
-            EEM_Base::set_model_query_blog_id();
534
-        }
535
-        /**
536
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
-         * just use EE_Register_Model_Extension
538
-         *
539
-         * @var EE_Table_Base[] $_tables
540
-         */
541
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
-        foreach ($this->_tables as $table_alias => $table_obj) {
543
-            /** @var $table_obj EE_Table_Base */
544
-            $table_obj->_construct_finalize_with_alias($table_alias);
545
-            if ($table_obj instanceof EE_Secondary_Table) {
546
-                /** @var $table_obj EE_Secondary_Table */
547
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
-            }
549
-        }
550
-        /**
551
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
-         * EE_Register_Model_Extension
553
-         *
554
-         * @param EE_Model_Field_Base[] $_fields
555
-         */
556
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
-        $this->_invalidate_field_caches();
558
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
559
-            if (! array_key_exists($table_alias, $this->_tables)) {
560
-                throw new EE_Error(sprintf(__(
561
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
-                    'event_espresso'
563
-                ), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                // primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            // make extra meta related to everything, but don't block deleting things just
575
-            // because they have related extra meta info. For now just orphan those extra meta
576
-            // in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        // and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = (array) apply_filters(
590
-            'FHEE__' . get_class($this) . '__construct__model_relations',
591
-            $this->_model_relations
592
-        );
593
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
594
-            /** @var $relation_obj EE_Model_Relation_Base */
595
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
-        }
597
-        foreach ($this->_indexes as $index_name => $index_obj) {
598
-            /** @var $index_obj EE_Index */
599
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
-        }
601
-        $this->set_timezone($timezone);
602
-        // finalize default where condition strategy, or set default
603
-        if (! $this->_default_where_conditions_strategy) {
604
-            // nothing was set during child constructor, so set default
605
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
608
-        if (! $this->_minimum_where_conditions_strategy) {
609
-            // nothing was set during child constructor, so set default
610
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
-        }
612
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
614
-        // to indicate to NOT set it, set it to the logical default
615
-        if ($this->_caps_slug === null) {
616
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
-        }
618
-        // initialize the standard cap restriction generators if none were specified by the child constructor
619
-        if ($this->_cap_restriction_generators !== false) {
620
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
-                        new EE_Restriction_Generator_Protected(),
625
-                        $cap_context,
626
-                        $this
627
-                    );
628
-                }
629
-            }
630
-        }
631
-        // if there are cap restriction generators, use them to make the default cap restrictions
632
-        if ($this->_cap_restriction_generators !== false) {
633
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
-                if (! $generator_object) {
635
-                    continue;
636
-                }
637
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
-                    throw new EE_Error(
639
-                        sprintf(
640
-                            __(
641
-                                '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.',
642
-                                'event_espresso'
643
-                            ),
644
-                            $context,
645
-                            $this->get_this_model_name()
646
-                        )
647
-                    );
648
-                }
649
-                $action = $this->cap_action_for_context($context);
650
-                if (! $generator_object->construction_finalized()) {
651
-                    $generator_object->_construct_finalize($this, $action);
652
-                }
653
-            }
654
-        }
655
-        do_action('AHEE__' . get_class($this) . '__construct__end');
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     * Used to set the $_model_query_blog_id static property.
662
-     *
663
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
-     *                      value for get_current_blog_id() will be used.
665
-     */
666
-    public static function set_model_query_blog_id($blog_id = 0)
667
-    {
668
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * Returns whatever is set as the internal $model_query_blog_id.
675
-     *
676
-     * @return int
677
-     */
678
-    public static function get_model_query_blog_id()
679
-    {
680
-        return EEM_Base::$_model_query_blog_id;
681
-    }
682
-
683
-
684
-
685
-    /**
686
-     * This function is a singleton method used to instantiate the Espresso_model object
687
-     *
688
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
-     *                                (and any incoming timezone data that gets saved).
690
-     *                                Note this just sends the timezone info to the date time model field objects.
691
-     *                                Default is NULL
692
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
-     * @return static (as in the concrete child class)
694
-     * @throws EE_Error
695
-     * @throws InvalidArgumentException
696
-     * @throws InvalidDataTypeException
697
-     * @throws InvalidInterfaceException
698
-     */
699
-    public static function instance($timezone = null)
700
-    {
701
-        // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
703
-            // instantiate Espresso_model
704
-            static::$_instance = new static(
705
-                $timezone,
706
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
-            );
708
-        }
709
-        // we might have a timezone set, let set_timezone decide what to do with it
710
-        static::$_instance->set_timezone($timezone);
711
-        // Espresso_model object
712
-        return static::$_instance;
713
-    }
714
-
715
-
716
-
717
-    /**
718
-     * resets the model and returns it
719
-     *
720
-     * @param null | string $timezone
721
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
-     * all its properties reset; if it wasn't instantiated, returns null)
723
-     * @throws EE_Error
724
-     * @throws ReflectionException
725
-     * @throws InvalidArgumentException
726
-     * @throws InvalidDataTypeException
727
-     * @throws InvalidInterfaceException
728
-     */
729
-    public static function reset($timezone = null)
730
-    {
731
-        if (static::$_instance instanceof EEM_Base) {
732
-            // let's try to NOT swap out the current instance for a new one
733
-            // because if someone has a reference to it, we can't remove their reference
734
-            // so it's best to keep using the same reference, but change the original object
735
-            // reset all its properties to their original values as defined in the class
736
-            $r = new ReflectionClass(get_class(static::$_instance));
737
-            $static_properties = $r->getStaticProperties();
738
-            foreach ($r->getDefaultProperties() as $property => $value) {
739
-                // don't set instance to null like it was originally,
740
-                // but it's static anyways, and we're ignoring static properties (for now at least)
741
-                if (! isset($static_properties[ $property ])) {
742
-                    static::$_instance->{$property} = $value;
743
-                }
744
-            }
745
-            // and then directly call its constructor again, like we would if we were creating a new one
746
-            static::$_instance->__construct(
747
-                $timezone,
748
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
-            );
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * @return LoaderInterface
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     */
763
-    private static function getLoader()
764
-    {
765
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
766
-            EEM_Base::$loader = LoaderFactory::getLoader();
767
-        }
768
-        return EEM_Base::$loader;
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
-     *
776
-     * @param  boolean $translated return localized strings or JUST the array.
777
-     * @return array
778
-     * @throws EE_Error
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidDataTypeException
781
-     * @throws InvalidInterfaceException
782
-     */
783
-    public function status_array($translated = false)
784
-    {
785
-        if (! array_key_exists('Status', $this->_model_relations)) {
786
-            return array();
787
-        }
788
-        $model_name = $this->get_this_model_name();
789
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
-        $status_array = array();
792
-        foreach ($stati as $status) {
793
-            $status_array[ $status->ID() ] = $status->get('STS_code');
794
-        }
795
-        return $translated
796
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
-            : $status_array;
798
-    }
799
-
800
-
801
-
802
-    /**
803
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
-     *
805
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/eem-base-get-all.md
806
-     *                             or if you have the development copy of EE you can view this at the path:
807
-     *                             /docs/G--Model-System/eem-base-get-all.md
808
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
809
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
810
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
811
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
812
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
813
-     *                                        array( array(
814
-     *                                        'OR'=>array(
815
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
816
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
817
-     *                                        )
818
-     *                                        ),
819
-     *                                        'limit'=>10,
820
-     *                                        'group_by'=>'TXN_ID'
821
-     *                                        ));
822
-     *                                        get all the answers to the question titled "shirt size" for event with id
823
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
824
-     *                                        'Question.QST_display_text'=>'shirt size',
825
-     *                                        'Registration.Event.EVT_ID'=>12
826
-     *                                        ),
827
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
828
-     *                                        ));
829
-     * @throws EE_Error
830
-     */
831
-    public function get_all($query_params = array())
832
-    {
833
-        if (isset($query_params['limit'])
834
-            && ! isset($query_params['group_by'])
835
-        ) {
836
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
837
-        }
838
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
839
-    }
840
-
841
-
842
-
843
-    /**
844
-     * Modifies the query parameters so we only get back model objects
845
-     * that "belong" to the current user
846
-     *
847
-     * @param array $query_params @see EEM_Base::get_all()
848
-     * @return array like EEM_Base::get_all
849
-     */
850
-    public function alter_query_params_to_only_include_mine($query_params = array())
851
-    {
852
-        $wp_user_field_name = $this->wp_user_field_name();
853
-        if ($wp_user_field_name) {
854
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
855
-        }
856
-        return $query_params;
857
-    }
858
-
859
-
860
-
861
-    /**
862
-     * Returns the name of the field's name that points to the WP_User table
863
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
864
-     * foreign key to the WP_User table)
865
-     *
866
-     * @return string|boolean string on success, boolean false when there is no
867
-     * foreign key to the WP_User table
868
-     */
869
-    public function wp_user_field_name()
870
-    {
871
-        try {
872
-            if (! empty($this->_model_chain_to_wp_user)) {
873
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
874
-                $last_model_name = end($models_to_follow_to_wp_users);
875
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
876
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
877
-            } else {
878
-                $model_with_fk_to_wp_users = $this;
879
-                $model_chain_to_wp_user = '';
880
-            }
881
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
882
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
883
-        } catch (EE_Error $e) {
884
-            return false;
885
-        }
886
-    }
887
-
888
-
889
-
890
-    /**
891
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
892
-     * (or transiently-related model) has a foreign key to the wp_users table;
893
-     * useful for finding if model objects of this type are 'owned' by the current user.
894
-     * This is an empty string when the foreign key is on this model and when it isn't,
895
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
896
-     * (or transiently-related model)
897
-     *
898
-     * @return string
899
-     */
900
-    public function model_chain_to_wp_user()
901
-    {
902
-        return $this->_model_chain_to_wp_user;
903
-    }
904
-
905
-
906
-
907
-    /**
908
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
909
-     * like how registrations don't have a foreign key to wp_users, but the
910
-     * events they are for are), or is unrelated to wp users.
911
-     * generally available
912
-     *
913
-     * @return boolean
914
-     */
915
-    public function is_owned()
916
-    {
917
-        if ($this->model_chain_to_wp_user()) {
918
-            return true;
919
-        }
920
-        try {
921
-            $this->get_foreign_key_to('WP_User');
922
-            return true;
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-    /**
930
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
931
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
932
-     * the model)
933
-     *
934
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
935
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
936
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
937
-     *                                  fields on the model, and the models we joined to in the query. However, you can
938
-     *                                  override this and set the select to "*", or a specific column name, like
939
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
940
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
941
-     *                                  the aliases used to refer to this selection, and values are to be
942
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
943
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
944
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
945
-     * @throws EE_Error
946
-     * @throws InvalidArgumentException
947
-     */
948
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
949
-    {
950
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
951
-        ;
952
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
953
-        $select_expressions = $columns_to_select === null
954
-            ? $this->_construct_default_select_sql($model_query_info)
955
-            : '';
956
-        if ($this->_custom_selections instanceof CustomSelects) {
957
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
958
-            $select_expressions .= $select_expressions
959
-                ? ', ' . $custom_expressions
960
-                : $custom_expressions;
961
-        }
962
-
963
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
964
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
965
-    }
966
-
967
-
968
-    /**
969
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
970
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
971
-     * method of including extra select information.
972
-     *
973
-     * @param array             $query_params
974
-     * @param null|array|string $columns_to_select
975
-     * @return null|CustomSelects
976
-     * @throws InvalidArgumentException
977
-     */
978
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
979
-    {
980
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
981
-            return null;
982
-        }
983
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
984
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
985
-        return new CustomSelects($selects);
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * Gets an array of rows from the database just like $wpdb->get_results would,
992
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
993
-     * take care of joins, field preparation etc.
994
-     *
995
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
996
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
997
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
998
-     *                                  fields on the model, and the models we joined to in the query. However, you can
999
-     *                                  override this and set the select to "*", or a specific column name, like
1000
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1001
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1002
-     *                                  the aliases used to refer to this selection, and values are to be
1003
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1004
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1005
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1006
-     * @throws EE_Error
1007
-     */
1008
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1009
-    {
1010
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1011
-    }
1012
-
1013
-
1014
-
1015
-    /**
1016
-     * For creating a custom select statement
1017
-     *
1018
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1019
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1020
-     *                                 SQL, and 1=>is the datatype
1021
-     * @throws EE_Error
1022
-     * @return string
1023
-     */
1024
-    private function _construct_select_from_input($columns_to_select)
1025
-    {
1026
-        if (is_array($columns_to_select)) {
1027
-            $select_sql_array = array();
1028
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1029
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1030
-                    throw new EE_Error(
1031
-                        sprintf(
1032
-                            __(
1033
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1034
-                                'event_espresso'
1035
-                            ),
1036
-                            $selection_and_datatype,
1037
-                            $alias
1038
-                        )
1039
-                    );
1040
-                }
1041
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1042
-                    throw new EE_Error(
1043
-                        sprintf(
1044
-                            esc_html__(
1045
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1046
-                                'event_espresso'
1047
-                            ),
1048
-                            $selection_and_datatype[1],
1049
-                            $selection_and_datatype[0],
1050
-                            $alias,
1051
-                            implode(', ', $this->_valid_wpdb_data_types)
1052
-                        )
1053
-                    );
1054
-                }
1055
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1056
-            }
1057
-            $columns_to_select_string = implode(', ', $select_sql_array);
1058
-        } else {
1059
-            $columns_to_select_string = $columns_to_select;
1060
-        }
1061
-        return $columns_to_select_string;
1062
-    }
1063
-
1064
-
1065
-
1066
-    /**
1067
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1068
-     *
1069
-     * @return string
1070
-     * @throws EE_Error
1071
-     */
1072
-    public function primary_key_name()
1073
-    {
1074
-        return $this->get_primary_key_field()->get_name();
1075
-    }
1076
-
1077
-
1078
-
1079
-    /**
1080
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1081
-     * If there is no primary key on this model, $id is treated as primary key string
1082
-     *
1083
-     * @param mixed $id int or string, depending on the type of the model's primary key
1084
-     * @return EE_Base_Class
1085
-     */
1086
-    public function get_one_by_ID($id)
1087
-    {
1088
-        if ($this->get_from_entity_map($id)) {
1089
-            return $this->get_from_entity_map($id);
1090
-        }
1091
-        return $this->get_one(
1092
-            $this->alter_query_params_to_restrict_by_ID(
1093
-                $id,
1094
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1095
-            )
1096
-        );
1097
-    }
1098
-
1099
-
1100
-
1101
-    /**
1102
-     * Alters query parameters to only get items with this ID are returned.
1103
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1104
-     * or could just be a simple primary key ID
1105
-     *
1106
-     * @param int   $id
1107
-     * @param array $query_params
1108
-     * @return array of normal query params, @see EEM_Base::get_all
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1112
-    {
1113
-        if (! isset($query_params[0])) {
1114
-            $query_params[0] = array();
1115
-        }
1116
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1117
-        if ($conditions_from_id === null) {
1118
-            $query_params[0][ $this->primary_key_name() ] = $id;
1119
-        } else {
1120
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1121
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1122
-        }
1123
-        return $query_params;
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1130
-     * array. If no item is found, null is returned.
1131
-     *
1132
-     * @param array $query_params like EEM_Base's $query_params variable.
1133
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1134
-     * @throws EE_Error
1135
-     */
1136
-    public function get_one($query_params = array())
1137
-    {
1138
-        if (! is_array($query_params)) {
1139
-            EE_Error::doing_it_wrong(
1140
-                'EEM_Base::get_one',
1141
-                sprintf(
1142
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1143
-                    gettype($query_params)
1144
-                ),
1145
-                '4.6.0'
1146
-            );
1147
-            $query_params = array();
1148
-        }
1149
-        $query_params['limit'] = 1;
1150
-        $items = $this->get_all($query_params);
1151
-        if (empty($items)) {
1152
-            return null;
1153
-        }
1154
-        return array_shift($items);
1155
-    }
1156
-
1157
-
1158
-
1159
-    /**
1160
-     * Returns the next x number of items in sequence from the given value as
1161
-     * found in the database matching the given query conditions.
1162
-     *
1163
-     * @param mixed $current_field_value    Value used for the reference point.
1164
-     * @param null  $field_to_order_by      What field is used for the
1165
-     *                                      reference point.
1166
-     * @param int   $limit                  How many to return.
1167
-     * @param array $query_params           Extra conditions on the query.
1168
-     * @param null  $columns_to_select      If left null, then an array of
1169
-     *                                      EE_Base_Class objects is returned,
1170
-     *                                      otherwise you can indicate just the
1171
-     *                                      columns you want returned.
1172
-     * @return EE_Base_Class[]|array
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function next_x(
1176
-        $current_field_value,
1177
-        $field_to_order_by = null,
1178
-        $limit = 1,
1179
-        $query_params = array(),
1180
-        $columns_to_select = null
1181
-    ) {
1182
-        return $this->_get_consecutive(
1183
-            $current_field_value,
1184
-            '>',
1185
-            $field_to_order_by,
1186
-            $limit,
1187
-            $query_params,
1188
-            $columns_to_select
1189
-        );
1190
-    }
1191
-
1192
-
1193
-
1194
-    /**
1195
-     * Returns the previous x number of items in sequence from the given value
1196
-     * as found in the database matching the given query conditions.
1197
-     *
1198
-     * @param mixed $current_field_value    Value used for the reference point.
1199
-     * @param null  $field_to_order_by      What field is used for the
1200
-     *                                      reference point.
1201
-     * @param int   $limit                  How many to return.
1202
-     * @param array $query_params           Extra conditions on the query.
1203
-     * @param null  $columns_to_select      If left null, then an array of
1204
-     *                                      EE_Base_Class objects is returned,
1205
-     *                                      otherwise you can indicate just the
1206
-     *                                      columns you want returned.
1207
-     * @return EE_Base_Class[]|array
1208
-     * @throws EE_Error
1209
-     */
1210
-    public function previous_x(
1211
-        $current_field_value,
1212
-        $field_to_order_by = null,
1213
-        $limit = 1,
1214
-        $query_params = array(),
1215
-        $columns_to_select = null
1216
-    ) {
1217
-        return $this->_get_consecutive(
1218
-            $current_field_value,
1219
-            '<',
1220
-            $field_to_order_by,
1221
-            $limit,
1222
-            $query_params,
1223
-            $columns_to_select
1224
-        );
1225
-    }
1226
-
1227
-
1228
-
1229
-    /**
1230
-     * Returns the next item in sequence from the given value as found in the
1231
-     * database matching the given query conditions.
1232
-     *
1233
-     * @param mixed $current_field_value    Value used for the reference point.
1234
-     * @param null  $field_to_order_by      What field is used for the
1235
-     *                                      reference point.
1236
-     * @param array $query_params           Extra conditions on the query.
1237
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1238
-     *                                      object is returned, otherwise you
1239
-     *                                      can indicate just the columns you
1240
-     *                                      want and a single array indexed by
1241
-     *                                      the columns will be returned.
1242
-     * @return EE_Base_Class|null|array()
1243
-     * @throws EE_Error
1244
-     */
1245
-    public function next(
1246
-        $current_field_value,
1247
-        $field_to_order_by = null,
1248
-        $query_params = array(),
1249
-        $columns_to_select = null
1250
-    ) {
1251
-        $results = $this->_get_consecutive(
1252
-            $current_field_value,
1253
-            '>',
1254
-            $field_to_order_by,
1255
-            1,
1256
-            $query_params,
1257
-            $columns_to_select
1258
-        );
1259
-        return empty($results) ? null : reset($results);
1260
-    }
1261
-
1262
-
1263
-
1264
-    /**
1265
-     * Returns the previous item in sequence from the given value as found in
1266
-     * the database matching the given query conditions.
1267
-     *
1268
-     * @param mixed $current_field_value    Value used for the reference point.
1269
-     * @param null  $field_to_order_by      What field is used for the
1270
-     *                                      reference point.
1271
-     * @param array $query_params           Extra conditions on the query.
1272
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1273
-     *                                      object is returned, otherwise you
1274
-     *                                      can indicate just the columns you
1275
-     *                                      want and a single array indexed by
1276
-     *                                      the columns will be returned.
1277
-     * @return EE_Base_Class|null|array()
1278
-     * @throws EE_Error
1279
-     */
1280
-    public function previous(
1281
-        $current_field_value,
1282
-        $field_to_order_by = null,
1283
-        $query_params = array(),
1284
-        $columns_to_select = null
1285
-    ) {
1286
-        $results = $this->_get_consecutive(
1287
-            $current_field_value,
1288
-            '<',
1289
-            $field_to_order_by,
1290
-            1,
1291
-            $query_params,
1292
-            $columns_to_select
1293
-        );
1294
-        return empty($results) ? null : reset($results);
1295
-    }
1296
-
1297
-
1298
-
1299
-    /**
1300
-     * Returns the a consecutive number of items in sequence from the given
1301
-     * value as found in the database matching the given query conditions.
1302
-     *
1303
-     * @param mixed  $current_field_value   Value used for the reference point.
1304
-     * @param string $operand               What operand is used for the sequence.
1305
-     * @param string $field_to_order_by     What field is used for the reference point.
1306
-     * @param int    $limit                 How many to return.
1307
-     * @param array  $query_params          Extra conditions on the query.
1308
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1309
-     *                                      otherwise you can indicate just the columns you want returned.
1310
-     * @return EE_Base_Class[]|array
1311
-     * @throws EE_Error
1312
-     */
1313
-    protected function _get_consecutive(
1314
-        $current_field_value,
1315
-        $operand = '>',
1316
-        $field_to_order_by = null,
1317
-        $limit = 1,
1318
-        $query_params = array(),
1319
-        $columns_to_select = null
1320
-    ) {
1321
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1322
-        if (empty($field_to_order_by)) {
1323
-            if ($this->has_primary_key_field()) {
1324
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1325
-            } else {
1326
-                if (WP_DEBUG) {
1327
-                    throw new EE_Error(__(
1328
-                        '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).',
1329
-                        'event_espresso'
1330
-                    ));
1331
-                }
1332
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1333
-                return array();
1334
-            }
1335
-        }
1336
-        if (! is_array($query_params)) {
1337
-            EE_Error::doing_it_wrong(
1338
-                'EEM_Base::_get_consecutive',
1339
-                sprintf(
1340
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1341
-                    gettype($query_params)
1342
-                ),
1343
-                '4.6.0'
1344
-            );
1345
-            $query_params = array();
1346
-        }
1347
-        // let's add the where query param for consecutive look up.
1348
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1349
-        $query_params['limit'] = $limit;
1350
-        // set direction
1351
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1352
-        $query_params['order_by'] = $operand === '>'
1353
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1354
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1355
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1356
-        if (empty($columns_to_select)) {
1357
-            return $this->get_all($query_params);
1358
-        }
1359
-        // getting just the fields
1360
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1361
-    }
1362
-
1363
-
1364
-
1365
-    /**
1366
-     * This sets the _timezone property after model object has been instantiated.
1367
-     *
1368
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1369
-     */
1370
-    public function set_timezone($timezone)
1371
-    {
1372
-        if ($timezone !== null) {
1373
-            $this->_timezone = $timezone;
1374
-        }
1375
-        // note we need to loop through relations and set the timezone on those objects as well.
1376
-        foreach ($this->_model_relations as $relation) {
1377
-            $relation->set_timezone($timezone);
1378
-        }
1379
-        // and finally we do the same for any datetime fields
1380
-        foreach ($this->_fields as $field) {
1381
-            if ($field instanceof EE_Datetime_Field) {
1382
-                $field->set_timezone($timezone);
1383
-            }
1384
-        }
1385
-    }
1386
-
1387
-
1388
-
1389
-    /**
1390
-     * This just returns whatever is set for the current timezone.
1391
-     *
1392
-     * @access public
1393
-     * @return string
1394
-     */
1395
-    public function get_timezone()
1396
-    {
1397
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1398
-        if (empty($this->_timezone)) {
1399
-            foreach ($this->_fields as $field) {
1400
-                if ($field instanceof EE_Datetime_Field) {
1401
-                    $this->set_timezone($field->get_timezone());
1402
-                    break;
1403
-                }
1404
-            }
1405
-        }
1406
-        // if timezone STILL empty then return the default timezone for the site.
1407
-        if (empty($this->_timezone)) {
1408
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1409
-        }
1410
-        return $this->_timezone;
1411
-    }
1412
-
1413
-
1414
-
1415
-    /**
1416
-     * This returns the date formats set for the given field name and also ensures that
1417
-     * $this->_timezone property is set correctly.
1418
-     *
1419
-     * @since 4.6.x
1420
-     * @param string $field_name The name of the field the formats are being retrieved for.
1421
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1422
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1423
-     * @return array formats in an array with the date format first, and the time format last.
1424
-     */
1425
-    public function get_formats_for($field_name, $pretty = false)
1426
-    {
1427
-        $field_settings = $this->field_settings_for($field_name);
1428
-        // if not a valid EE_Datetime_Field then throw error
1429
-        if (! $field_settings instanceof EE_Datetime_Field) {
1430
-            throw new EE_Error(sprintf(__(
1431
-                '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.',
1432
-                'event_espresso'
1433
-            ), $field_name));
1434
-        }
1435
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1436
-        // the field.
1437
-        $this->_timezone = $field_settings->get_timezone();
1438
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1439
-    }
1440
-
1441
-
1442
-
1443
-    /**
1444
-     * This returns the current time in a format setup for a query on this model.
1445
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1446
-     * it will return:
1447
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1448
-     *  NOW
1449
-     *  - or a unix timestamp (equivalent to time())
1450
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1451
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1452
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1453
-     * @since 4.6.x
1454
-     * @param string $field_name       The field the current time is needed for.
1455
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1456
-     *                                 formatted string matching the set format for the field in the set timezone will
1457
-     *                                 be returned.
1458
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1459
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1460
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1461
-     *                                 exception is triggered.
1462
-     */
1463
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1464
-    {
1465
-        $formats = $this->get_formats_for($field_name);
1466
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1467
-        if ($timestamp) {
1468
-            return $DateTime->format('U');
1469
-        }
1470
-        // not returning timestamp, so return formatted string in timezone.
1471
-        switch ($what) {
1472
-            case 'time':
1473
-                return $DateTime->format($formats[1]);
1474
-                break;
1475
-            case 'date':
1476
-                return $DateTime->format($formats[0]);
1477
-                break;
1478
-            default:
1479
-                return $DateTime->format(implode(' ', $formats));
1480
-                break;
1481
-        }
1482
-    }
1483
-
1484
-
1485
-
1486
-    /**
1487
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1488
-     * for the model are.  Returns a DateTime object.
1489
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1490
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1491
-     * ignored.
1492
-     *
1493
-     * @param string $field_name      The field being setup.
1494
-     * @param string $timestring      The date time string being used.
1495
-     * @param string $incoming_format The format for the time string.
1496
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1497
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1498
-     *                                format is
1499
-     *                                'U', this is ignored.
1500
-     * @return DateTime
1501
-     * @throws EE_Error
1502
-     */
1503
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1504
-    {
1505
-        // just using this to ensure the timezone is set correctly internally
1506
-        $this->get_formats_for($field_name);
1507
-        // load EEH_DTT_Helper
1508
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1509
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1510
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1511
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1512
-    }
1513
-
1514
-
1515
-
1516
-    /**
1517
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1518
-     *
1519
-     * @return EE_Table_Base[]
1520
-     */
1521
-    public function get_tables()
1522
-    {
1523
-        return $this->_tables;
1524
-    }
1525
-
1526
-
1527
-
1528
-    /**
1529
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1530
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1531
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1532
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1533
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1534
-     * model object with EVT_ID = 1
1535
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1536
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1537
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1538
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1539
-     * are not specified)
1540
-     *
1541
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1542
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1543
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1544
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1545
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1546
-     *                                         ID=34, we'd use this method as follows:
1547
-     *                                         EEM_Transaction::instance()->update(
1548
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1549
-     *                                         array(array('TXN_ID'=>34)));
1550
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1551
-     *                                         in client code into what's expected to be stored on each field. Eg,
1552
-     *                                         consider updating Question's QST_admin_label field is of type
1553
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1554
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1555
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1556
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1557
-     *                                         TRUE, it is assumed that you've already called
1558
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1559
-     *                                         malicious javascript. However, if
1560
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1561
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1562
-     *                                         and every other field, before insertion. We provide this parameter
1563
-     *                                         because model objects perform their prepare_for_set function on all
1564
-     *                                         their values, and so don't need to be called again (and in many cases,
1565
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1566
-     *                                         prepare_for_set method...)
1567
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1568
-     *                                         in this model's entity map according to $fields_n_values that match
1569
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1570
-     *                                         by setting this to FALSE, but be aware that model objects being used
1571
-     *                                         could get out-of-sync with the database
1572
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1573
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1574
-     *                                         bad)
1575
-     * @throws EE_Error
1576
-     */
1577
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1578
-    {
1579
-        if (! is_array($query_params)) {
1580
-            EE_Error::doing_it_wrong(
1581
-                'EEM_Base::update',
1582
-                sprintf(
1583
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1584
-                    gettype($query_params)
1585
-                ),
1586
-                '4.6.0'
1587
-            );
1588
-            $query_params = array();
1589
-        }
1590
-        /**
1591
-         * Action called before a model update call has been made.
1592
-         *
1593
-         * @param EEM_Base $model
1594
-         * @param array    $fields_n_values the updated fields and their new values
1595
-         * @param array    $query_params    @see EEM_Base::get_all()
1596
-         */
1597
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1598
-        /**
1599
-         * Filters the fields about to be updated given the query parameters. You can provide the
1600
-         * $query_params to $this->get_all() to find exactly which records will be updated
1601
-         *
1602
-         * @param array    $fields_n_values fields and their new values
1603
-         * @param EEM_Base $model           the model being queried
1604
-         * @param array    $query_params    see EEM_Base::get_all()
1605
-         */
1606
-        $fields_n_values = (array) apply_filters(
1607
-            'FHEE__EEM_Base__update__fields_n_values',
1608
-            $fields_n_values,
1609
-            $this,
1610
-            $query_params
1611
-        );
1612
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1613
-        // to do that, for each table, verify that it's PK isn't null.
1614
-        $tables = $this->get_tables();
1615
-        // 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
1616
-        // NOTE: we should make this code more efficient by NOT querying twice
1617
-        // before the real update, but that needs to first go through ALPHA testing
1618
-        // as it's dangerous. says Mike August 8 2014
1619
-        // we want to make sure the default_where strategy is ignored
1620
-        $this->_ignore_where_strategy = true;
1621
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1622
-        foreach ($wpdb_select_results as $wpdb_result) {
1623
-            // type cast stdClass as array
1624
-            $wpdb_result = (array) $wpdb_result;
1625
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1626
-            if ($this->has_primary_key_field()) {
1627
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1628
-            } else {
1629
-                // 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)
1630
-                $main_table_pk_value = null;
1631
-            }
1632
-            // 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
1633
-            // 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
1634
-            if (count($tables) > 1) {
1635
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1636
-                // in that table, and so we'll want to insert one
1637
-                foreach ($tables as $table_obj) {
1638
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1639
-                    // if there is no private key for this table on the results, it means there's no entry
1640
-                    // in this table, right? so insert a row in the current table, using any fields available
1641
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1642
-                           && $wpdb_result[ $this_table_pk_column ])
1643
-                    ) {
1644
-                        $success = $this->_insert_into_specific_table(
1645
-                            $table_obj,
1646
-                            $fields_n_values,
1647
-                            $main_table_pk_value
1648
-                        );
1649
-                        // if we died here, report the error
1650
-                        if (! $success) {
1651
-                            return false;
1652
-                        }
1653
-                    }
1654
-                }
1655
-            }
1656
-            //              //and now check that if we have cached any models by that ID on the model, that
1657
-            //              //they also get updated properly
1658
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1659
-            //              if( $model_object ){
1660
-            //                  foreach( $fields_n_values as $field => $value ){
1661
-            //                      $model_object->set($field, $value);
1662
-            // let's make sure default_where strategy is followed now
1663
-            $this->_ignore_where_strategy = false;
1664
-        }
1665
-        // if we want to keep model objects in sync, AND
1666
-        // if this wasn't called from a model object (to update itself)
1667
-        // then we want to make sure we keep all the existing
1668
-        // model objects in sync with the db
1669
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1670
-            if ($this->has_primary_key_field()) {
1671
-                $model_objs_affected_ids = $this->get_col($query_params);
1672
-            } else {
1673
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1674
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1675
-                $model_objs_affected_ids = array();
1676
-                foreach ($models_affected_key_columns as $row) {
1677
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1678
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1679
-                }
1680
-            }
1681
-            if (! $model_objs_affected_ids) {
1682
-                // wait wait wait- if nothing was affected let's stop here
1683
-                return 0;
1684
-            }
1685
-            foreach ($model_objs_affected_ids as $id) {
1686
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1687
-                if ($model_obj_in_entity_map) {
1688
-                    foreach ($fields_n_values as $field => $new_value) {
1689
-                        $model_obj_in_entity_map->set($field, $new_value);
1690
-                    }
1691
-                }
1692
-            }
1693
-            // if there is a primary key on this model, we can now do a slight optimization
1694
-            if ($this->has_primary_key_field()) {
1695
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1696
-                $query_params = array(
1697
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1698
-                    'limit'                    => count($model_objs_affected_ids),
1699
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1700
-                );
1701
-            }
1702
-        }
1703
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1704
-        $SQL = "UPDATE "
1705
-               . $model_query_info->get_full_join_sql()
1706
-               . " SET "
1707
-               . $this->_construct_update_sql($fields_n_values)
1708
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1709
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1710
-        /**
1711
-         * Action called after a model update call has been made.
1712
-         *
1713
-         * @param EEM_Base $model
1714
-         * @param array    $fields_n_values the updated fields and their new values
1715
-         * @param array    $query_params    @see EEM_Base::get_all()
1716
-         * @param int      $rows_affected
1717
-         */
1718
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1719
-        return $rows_affected;// how many supposedly got updated
1720
-    }
1721
-
1722
-
1723
-
1724
-    /**
1725
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1726
-     * are teh values of the field specified (or by default the primary key field)
1727
-     * that matched the query params. Note that you should pass the name of the
1728
-     * model FIELD, not the database table's column name.
1729
-     *
1730
-     * @param array  $query_params @see EEM_Base::get_all()
1731
-     * @param string $field_to_select
1732
-     * @return array just like $wpdb->get_col()
1733
-     * @throws EE_Error
1734
-     */
1735
-    public function get_col($query_params = array(), $field_to_select = null)
1736
-    {
1737
-        if ($field_to_select) {
1738
-            $field = $this->field_settings_for($field_to_select);
1739
-        } elseif ($this->has_primary_key_field()) {
1740
-            $field = $this->get_primary_key_field();
1741
-        } else {
1742
-            // no primary key, just grab the first column
1743
-            $field = reset($this->field_settings());
1744
-        }
1745
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1746
-        $select_expressions = $field->get_qualified_column();
1747
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1748
-        return $this->_do_wpdb_query('get_col', array($SQL));
1749
-    }
1750
-
1751
-
1752
-
1753
-    /**
1754
-     * Returns a single column value for a single row from the database
1755
-     *
1756
-     * @param array  $query_params    @see EEM_Base::get_all()
1757
-     * @param string $field_to_select @see EEM_Base::get_col()
1758
-     * @return string
1759
-     * @throws EE_Error
1760
-     */
1761
-    public function get_var($query_params = array(), $field_to_select = null)
1762
-    {
1763
-        $query_params['limit'] = 1;
1764
-        $col = $this->get_col($query_params, $field_to_select);
1765
-        if (! empty($col)) {
1766
-            return reset($col);
1767
-        }
1768
-        return null;
1769
-    }
1770
-
1771
-
1772
-
1773
-    /**
1774
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1775
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1776
-     * injection, but currently no further filtering is done
1777
-     *
1778
-     * @global      $wpdb
1779
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1780
-     *                               be updated to in the DB
1781
-     * @return string of SQL
1782
-     * @throws EE_Error
1783
-     */
1784
-    public function _construct_update_sql($fields_n_values)
1785
-    {
1786
-        /** @type WPDB $wpdb */
1787
-        global $wpdb;
1788
-        $cols_n_values = array();
1789
-        foreach ($fields_n_values as $field_name => $value) {
1790
-            $field_obj = $this->field_settings_for($field_name);
1791
-            // if the value is NULL, we want to assign the value to that.
1792
-            // wpdb->prepare doesn't really handle that properly
1793
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1794
-            $value_sql = $prepared_value === null ? 'NULL'
1795
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1796
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1797
-        }
1798
-        return implode(",", $cols_n_values);
1799
-    }
1800
-
1801
-
1802
-
1803
-    /**
1804
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1805
-     * Performs a HARD delete, meaning the database row should always be removed,
1806
-     * not just have a flag field on it switched
1807
-     * Wrapper for EEM_Base::delete_permanently()
1808
-     *
1809
-     * @param mixed $id
1810
-     * @param boolean $allow_blocking
1811
-     * @return int the number of rows deleted
1812
-     * @throws EE_Error
1813
-     */
1814
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1815
-    {
1816
-        return $this->delete_permanently(
1817
-            array(
1818
-                array($this->get_primary_key_field()->get_name() => $id),
1819
-                'limit' => 1,
1820
-            ),
1821
-            $allow_blocking
1822
-        );
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
-     * Wrapper for EEM_Base::delete()
1830
-     *
1831
-     * @param mixed $id
1832
-     * @param boolean $allow_blocking
1833
-     * @return int the number of rows deleted
1834
-     * @throws EE_Error
1835
-     */
1836
-    public function delete_by_ID($id, $allow_blocking = true)
1837
-    {
1838
-        return $this->delete(
1839
-            array(
1840
-                array($this->get_primary_key_field()->get_name() => $id),
1841
-                'limit' => 1,
1842
-            ),
1843
-            $allow_blocking
1844
-        );
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1851
-     * meaning if the model has a field that indicates its been "trashed" or
1852
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1853
-     *
1854
-     * @see EEM_Base::delete_permanently
1855
-     * @param array   $query_params
1856
-     * @param boolean $allow_blocking
1857
-     * @return int how many rows got deleted
1858
-     * @throws EE_Error
1859
-     */
1860
-    public function delete($query_params, $allow_blocking = true)
1861
-    {
1862
-        return $this->delete_permanently($query_params, $allow_blocking);
1863
-    }
1864
-
1865
-
1866
-
1867
-    /**
1868
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1869
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1870
-     * as archived, not actually deleted
1871
-     *
1872
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1873
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1874
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1875
-     *                                deletes regardless of other objects which may depend on it. Its generally
1876
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1877
-     *                                DB
1878
-     * @return int how many rows got deleted
1879
-     * @throws EE_Error
1880
-     */
1881
-    public function delete_permanently($query_params, $allow_blocking = true)
1882
-    {
1883
-        /**
1884
-         * Action called just before performing a real deletion query. You can use the
1885
-         * model and its $query_params to find exactly which items will be deleted
1886
-         *
1887
-         * @param EEM_Base $model
1888
-         * @param array    $query_params   @see EEM_Base::get_all()
1889
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1890
-         *                                 to block (prevent) this deletion
1891
-         */
1892
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1893
-        // some MySQL databases may be running safe mode, which may restrict
1894
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1895
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1896
-        // to delete them
1897
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1898
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1899
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1900
-            $columns_and_ids_for_deleting
1901
-        );
1902
-        /**
1903
-         * Allows client code to act on the items being deleted before the query is actually executed.
1904
-         *
1905
-         * @param EEM_Base $this  The model instance being acted on.
1906
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1907
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1908
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1909
-         *                                                  derived from the incoming query parameters.
1910
-         *                                                  @see details on the structure of this array in the phpdocs
1911
-         *                                                  for the `_get_ids_for_delete_method`
1912
-         *
1913
-         */
1914
-        do_action(
1915
-            'AHEE__EEM_Base__delete__before_query',
1916
-            $this,
1917
-            $query_params,
1918
-            $allow_blocking,
1919
-            $columns_and_ids_for_deleting
1920
-        );
1921
-        if ($deletion_where_query_part) {
1922
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1923
-            $table_aliases = array_keys($this->_tables);
1924
-            $SQL = "DELETE "
1925
-                   . implode(", ", $table_aliases)
1926
-                   . " FROM "
1927
-                   . $model_query_info->get_full_join_sql()
1928
-                   . " WHERE "
1929
-                   . $deletion_where_query_part;
1930
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1931
-        } else {
1932
-            $rows_deleted = 0;
1933
-        }
1934
-
1935
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1936
-        // there was no error with the delete query.
1937
-        if ($this->has_primary_key_field()
1938
-            && $rows_deleted !== false
1939
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1940
-        ) {
1941
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1942
-            foreach ($ids_for_removal as $id) {
1943
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1944
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1945
-                }
1946
-            }
1947
-
1948
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1949
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1950
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1951
-            // (although it is possible).
1952
-            // Note this can be skipped by using the provided filter and returning false.
1953
-            if (apply_filters(
1954
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1955
-                ! $this instanceof EEM_Extra_Meta,
1956
-                $this
1957
-            )) {
1958
-                EEM_Extra_Meta::instance()->delete_permanently(array(
1959
-                    0 => array(
1960
-                        'EXM_type' => $this->get_this_model_name(),
1961
-                        'OBJ_ID'   => array(
1962
-                            'IN',
1963
-                            $ids_for_removal
1964
-                        )
1965
-                    )
1966
-                ));
1967
-            }
1968
-        }
1969
-
1970
-        /**
1971
-         * Action called just after performing a real deletion query. Although at this point the
1972
-         * items should have been deleted
1973
-         *
1974
-         * @param EEM_Base $model
1975
-         * @param array    $query_params @see EEM_Base::get_all()
1976
-         * @param int      $rows_deleted
1977
-         */
1978
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1979
-        return $rows_deleted;// how many supposedly got deleted
1980
-    }
1981
-
1982
-
1983
-
1984
-    /**
1985
-     * Checks all the relations that throw error messages when there are blocking related objects
1986
-     * for related model objects. If there are any related model objects on those relations,
1987
-     * adds an EE_Error, and return true
1988
-     *
1989
-     * @param EE_Base_Class|int $this_model_obj_or_id
1990
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1991
-     *                                                 should be ignored when determining whether there are related
1992
-     *                                                 model objects which block this model object's deletion. Useful
1993
-     *                                                 if you know A is related to B and are considering deleting A,
1994
-     *                                                 but want to see if A has any other objects blocking its deletion
1995
-     *                                                 before removing the relation between A and B
1996
-     * @return boolean
1997
-     * @throws EE_Error
1998
-     */
1999
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2000
-    {
2001
-        // first, if $ignore_this_model_obj was supplied, get its model
2002
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2003
-            $ignored_model = $ignore_this_model_obj->get_model();
2004
-        } else {
2005
-            $ignored_model = null;
2006
-        }
2007
-        // now check all the relations of $this_model_obj_or_id and see if there
2008
-        // are any related model objects blocking it?
2009
-        $is_blocked = false;
2010
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2011
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2012
-                // if $ignore_this_model_obj was supplied, then for the query
2013
-                // on that model needs to be told to ignore $ignore_this_model_obj
2014
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2015
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2016
-                        array(
2017
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2018
-                                '!=',
2019
-                                $ignore_this_model_obj->ID(),
2020
-                            ),
2021
-                        ),
2022
-                    ));
2023
-                } else {
2024
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2025
-                }
2026
-                if ($related_model_objects) {
2027
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2028
-                    $is_blocked = true;
2029
-                }
2030
-            }
2031
-        }
2032
-        return $is_blocked;
2033
-    }
2034
-
2035
-
2036
-    /**
2037
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2038
-     * @param array $row_results_for_deleting
2039
-     * @param bool  $allow_blocking
2040
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2041
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2042
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2043
-     *                 deleted. Example:
2044
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2045
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2046
-     *                 where each element is a group of columns and values that get deleted. Example:
2047
-     *                      array(
2048
-     *                          0 => array(
2049
-     *                              'Term_Relationship.object_id' => 1
2050
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2051
-     *                          ),
2052
-     *                          1 => array(
2053
-     *                              'Term_Relationship.object_id' => 1
2054
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2055
-     *                          )
2056
-     *                      )
2057
-     * @throws EE_Error
2058
-     */
2059
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2060
-    {
2061
-        $ids_to_delete_indexed_by_column = array();
2062
-        if ($this->has_primary_key_field()) {
2063
-            $primary_table = $this->_get_main_table();
2064
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2065
-            $other_tables = $this->_get_other_tables();
2066
-            $ids_to_delete_indexed_by_column = $query = array();
2067
-            foreach ($row_results_for_deleting as $item_to_delete) {
2068
-                // before we mark this item for deletion,
2069
-                // make sure there's no related entities blocking its deletion (if we're checking)
2070
-                if ($allow_blocking
2071
-                    && $this->delete_is_blocked_by_related_models(
2072
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2073
-                    )
2074
-                ) {
2075
-                    continue;
2076
-                }
2077
-                // primary table deletes
2078
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2079
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2080
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2081
-                }
2082
-            }
2083
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2084
-            $fields = $this->get_combined_primary_key_fields();
2085
-            foreach ($row_results_for_deleting as $item_to_delete) {
2086
-                $ids_to_delete_indexed_by_column_for_row = array();
2087
-                foreach ($fields as $cpk_field) {
2088
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2089
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2090
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2091
-                    }
2092
-                }
2093
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2094
-            }
2095
-        } else {
2096
-            // so there's no primary key and no combined key...
2097
-            // sorry, can't help you
2098
-            throw new EE_Error(
2099
-                sprintf(
2100
-                    __(
2101
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2102
-                        "event_espresso"
2103
-                    ),
2104
-                    get_class($this)
2105
-                )
2106
-            );
2107
-        }
2108
-        return $ids_to_delete_indexed_by_column;
2109
-    }
2110
-
2111
-
2112
-    /**
2113
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2114
-     * the corresponding query_part for the query performing the delete.
2115
-     *
2116
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2117
-     * @return string
2118
-     * @throws EE_Error
2119
-     */
2120
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2121
-    {
2122
-        $query_part = '';
2123
-        if (empty($ids_to_delete_indexed_by_column)) {
2124
-            return $query_part;
2125
-        } elseif ($this->has_primary_key_field()) {
2126
-            $query = array();
2127
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2128
-                // make sure we have unique $ids
2129
-                $ids = array_unique($ids);
2130
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2131
-            }
2132
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2133
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2134
-            $ways_to_identify_a_row = array();
2135
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2136
-                $values_for_each_combined_primary_key_for_a_row = array();
2137
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2138
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2139
-                }
2140
-                $ways_to_identify_a_row[] = '('
2141
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2142
-                                            . ')';
2143
-            }
2144
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2145
-        }
2146
-        return $query_part;
2147
-    }
2148
-
2149
-
2150
-
2151
-    /**
2152
-     * Gets the model field by the fully qualified name
2153
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2154
-     * @return EE_Model_Field_Base
2155
-     */
2156
-    public function get_field_by_column($qualified_column_name)
2157
-    {
2158
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2159
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2160
-                return $field_obj;
2161
-            }
2162
-        }
2163
-        throw new EE_Error(
2164
-            sprintf(
2165
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2166
-                $this->get_this_model_name(),
2167
-                $qualified_column_name
2168
-            )
2169
-        );
2170
-    }
2171
-
2172
-
2173
-
2174
-    /**
2175
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2176
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2177
-     * column
2178
-     *
2179
-     * @param array  $query_params   like EEM_Base::get_all's
2180
-     * @param string $field_to_count field on model to count by (not column name)
2181
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2182
-     *                               that by the setting $distinct to TRUE;
2183
-     * @return int
2184
-     * @throws EE_Error
2185
-     */
2186
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2187
-    {
2188
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2189
-        if ($field_to_count) {
2190
-            $field_obj = $this->field_settings_for($field_to_count);
2191
-            $column_to_count = $field_obj->get_qualified_column();
2192
-        } elseif ($this->has_primary_key_field()) {
2193
-            $pk_field_obj = $this->get_primary_key_field();
2194
-            $column_to_count = $pk_field_obj->get_qualified_column();
2195
-        } else {
2196
-            // there's no primary key
2197
-            // if we're counting distinct items, and there's no primary key,
2198
-            // we need to list out the columns for distinction;
2199
-            // otherwise we can just use star
2200
-            if ($distinct) {
2201
-                $columns_to_use = array();
2202
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2203
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2204
-                }
2205
-                $column_to_count = implode(',', $columns_to_use);
2206
-            } else {
2207
-                $column_to_count = '*';
2208
-            }
2209
-        }
2210
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2211
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2212
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2213
-    }
2214
-
2215
-
2216
-
2217
-    /**
2218
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2219
-     *
2220
-     * @param array  $query_params like EEM_Base::get_all
2221
-     * @param string $field_to_sum name of field (array key in $_fields array)
2222
-     * @return float
2223
-     * @throws EE_Error
2224
-     */
2225
-    public function sum($query_params, $field_to_sum = null)
2226
-    {
2227
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2228
-        if ($field_to_sum) {
2229
-            $field_obj = $this->field_settings_for($field_to_sum);
2230
-        } else {
2231
-            $field_obj = $this->get_primary_key_field();
2232
-        }
2233
-        $column_to_count = $field_obj->get_qualified_column();
2234
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2235
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2236
-        $data_type = $field_obj->get_wpdb_data_type();
2237
-        if ($data_type === '%d' || $data_type === '%s') {
2238
-            return (float) $return_value;
2239
-        }
2240
-        // must be %f
2241
-        return (float) $return_value;
2242
-    }
2243
-
2244
-
2245
-
2246
-    /**
2247
-     * Just calls the specified method on $wpdb with the given arguments
2248
-     * Consolidates a little extra error handling code
2249
-     *
2250
-     * @param string $wpdb_method
2251
-     * @param array  $arguments_to_provide
2252
-     * @throws EE_Error
2253
-     * @global wpdb  $wpdb
2254
-     * @return mixed
2255
-     */
2256
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2257
-    {
2258
-        // if we're in maintenance mode level 2, DON'T run any queries
2259
-        // because level 2 indicates the database needs updating and
2260
-        // is probably out of sync with the code
2261
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2262
-            throw new EE_Error(sprintf(__(
2263
-                "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.",
2264
-                "event_espresso"
2265
-            )));
2266
-        }
2267
-        /** @type WPDB $wpdb */
2268
-        global $wpdb;
2269
-        if (! method_exists($wpdb, $wpdb_method)) {
2270
-            throw new EE_Error(sprintf(__(
2271
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2272
-                'event_espresso'
2273
-            ), $wpdb_method));
2274
-        }
2275
-        if (WP_DEBUG) {
2276
-            $old_show_errors_value = $wpdb->show_errors;
2277
-            $wpdb->show_errors(false);
2278
-        }
2279
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2280
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2281
-        if (WP_DEBUG) {
2282
-            $wpdb->show_errors($old_show_errors_value);
2283
-            if (! empty($wpdb->last_error)) {
2284
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2285
-            }
2286
-            if ($result === false) {
2287
-                throw new EE_Error(sprintf(__(
2288
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2289
-                    'event_espresso'
2290
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2291
-            }
2292
-        } elseif ($result === false) {
2293
-            EE_Error::add_error(
2294
-                sprintf(
2295
-                    __(
2296
-                        '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"',
2297
-                        'event_espresso'
2298
-                    ),
2299
-                    $wpdb_method,
2300
-                    var_export($arguments_to_provide, true),
2301
-                    $wpdb->last_error
2302
-                ),
2303
-                __FILE__,
2304
-                __FUNCTION__,
2305
-                __LINE__
2306
-            );
2307
-        }
2308
-        return $result;
2309
-    }
2310
-
2311
-
2312
-
2313
-    /**
2314
-     * Attempts to run the indicated WPDB method with the provided arguments,
2315
-     * and if there's an error tries to verify the DB is correct. Uses
2316
-     * the static property EEM_Base::$_db_verification_level to determine whether
2317
-     * we should try to fix the EE core db, the addons, or just give up
2318
-     *
2319
-     * @param string $wpdb_method
2320
-     * @param array  $arguments_to_provide
2321
-     * @return mixed
2322
-     */
2323
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2324
-    {
2325
-        /** @type WPDB $wpdb */
2326
-        global $wpdb;
2327
-        $wpdb->last_error = null;
2328
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2329
-        // was there an error running the query? but we don't care on new activations
2330
-        // (we're going to setup the DB anyway on new activations)
2331
-        if (($result === false || ! empty($wpdb->last_error))
2332
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2333
-        ) {
2334
-            switch (EEM_Base::$_db_verification_level) {
2335
-                case EEM_Base::db_verified_none:
2336
-                    // let's double-check core's DB
2337
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2338
-                    break;
2339
-                case EEM_Base::db_verified_core:
2340
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2341
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2342
-                    break;
2343
-                case EEM_Base::db_verified_addons:
2344
-                    // ummmm... you in trouble
2345
-                    return $result;
2346
-                    break;
2347
-            }
2348
-            if (! empty($error_message)) {
2349
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2350
-                trigger_error($error_message);
2351
-            }
2352
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2353
-        }
2354
-        return $result;
2355
-    }
2356
-
2357
-
2358
-
2359
-    /**
2360
-     * Verifies the EE core database is up-to-date and records that we've done it on
2361
-     * EEM_Base::$_db_verification_level
2362
-     *
2363
-     * @param string $wpdb_method
2364
-     * @param array  $arguments_to_provide
2365
-     * @return string
2366
-     */
2367
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2368
-    {
2369
-        /** @type WPDB $wpdb */
2370
-        global $wpdb;
2371
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2372
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2373
-        $error_message = sprintf(
2374
-            __(
2375
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2376
-                'event_espresso'
2377
-            ),
2378
-            $wpdb->last_error,
2379
-            $wpdb_method,
2380
-            wp_json_encode($arguments_to_provide)
2381
-        );
2382
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2383
-        return $error_message;
2384
-    }
2385
-
2386
-
2387
-
2388
-    /**
2389
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2390
-     * EEM_Base::$_db_verification_level
2391
-     *
2392
-     * @param $wpdb_method
2393
-     * @param $arguments_to_provide
2394
-     * @return string
2395
-     */
2396
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2397
-    {
2398
-        /** @type WPDB $wpdb */
2399
-        global $wpdb;
2400
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2401
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2402
-        $error_message = sprintf(
2403
-            __(
2404
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2405
-                'event_espresso'
2406
-            ),
2407
-            $wpdb->last_error,
2408
-            $wpdb_method,
2409
-            wp_json_encode($arguments_to_provide)
2410
-        );
2411
-        EE_System::instance()->initialize_addons();
2412
-        return $error_message;
2413
-    }
2414
-
2415
-
2416
-
2417
-    /**
2418
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2419
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2420
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2421
-     * ..."
2422
-     *
2423
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2424
-     * @return string
2425
-     */
2426
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2427
-    {
2428
-        return " FROM " . $model_query_info->get_full_join_sql() .
2429
-               $model_query_info->get_where_sql() .
2430
-               $model_query_info->get_group_by_sql() .
2431
-               $model_query_info->get_having_sql() .
2432
-               $model_query_info->get_order_by_sql() .
2433
-               $model_query_info->get_limit_sql();
2434
-    }
2435
-
2436
-
2437
-
2438
-    /**
2439
-     * Set to easily debug the next X queries ran from this model.
2440
-     *
2441
-     * @param int $count
2442
-     */
2443
-    public function show_next_x_db_queries($count = 1)
2444
-    {
2445
-        $this->_show_next_x_db_queries = $count;
2446
-    }
2447
-
2448
-
2449
-
2450
-    /**
2451
-     * @param $sql_query
2452
-     */
2453
-    public function show_db_query_if_previously_requested($sql_query)
2454
-    {
2455
-        if ($this->_show_next_x_db_queries > 0) {
2456
-            echo $sql_query;
2457
-            $this->_show_next_x_db_queries--;
2458
-        }
2459
-    }
2460
-
2461
-
2462
-
2463
-    /**
2464
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2465
-     * There are the 3 cases:
2466
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2467
-     * $otherModelObject has no ID, it is first saved.
2468
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2469
-     * has no ID, it is first saved.
2470
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2471
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2472
-     * join table
2473
-     *
2474
-     * @param        EE_Base_Class                     /int $thisModelObject
2475
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2476
-     * @param string $relationName                     , key in EEM_Base::_relations
2477
-     *                                                 an attendee to a group, you also want to specify which role they
2478
-     *                                                 will have in that group. So you would use this parameter to
2479
-     *                                                 specify array('role-column-name'=>'role-id')
2480
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2481
-     *                                                 to for relation to methods that allow you to further specify
2482
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2483
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2484
-     *                                                 because these will be inserted in any new rows created as well.
2485
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2486
-     * @throws EE_Error
2487
-     */
2488
-    public function add_relationship_to(
2489
-        $id_or_obj,
2490
-        $other_model_id_or_obj,
2491
-        $relationName,
2492
-        $extra_join_model_fields_n_values = array()
2493
-    ) {
2494
-        $relation_obj = $this->related_settings_for($relationName);
2495
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2502
-     * There are the 3 cases:
2503
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2504
-     * error
2505
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2506
-     * an error
2507
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2508
-     *
2509
-     * @param        EE_Base_Class /int $id_or_obj
2510
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2511
-     * @param string $relationName key in EEM_Base::_relations
2512
-     * @return boolean of success
2513
-     * @throws EE_Error
2514
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2515
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2516
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2517
-     *                             because these will be inserted in any new rows created as well.
2518
-     */
2519
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2520
-    {
2521
-        $relation_obj = $this->related_settings_for($relationName);
2522
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2523
-    }
2524
-
2525
-
2526
-
2527
-    /**
2528
-     * @param mixed           $id_or_obj
2529
-     * @param string          $relationName
2530
-     * @param array           $where_query_params
2531
-     * @param EE_Base_Class[] objects to which relations were removed
2532
-     * @return \EE_Base_Class[]
2533
-     * @throws EE_Error
2534
-     */
2535
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2536
-    {
2537
-        $relation_obj = $this->related_settings_for($relationName);
2538
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2539
-    }
2540
-
2541
-
2542
-
2543
-    /**
2544
-     * Gets all the related items of the specified $model_name, using $query_params.
2545
-     * Note: by default, we remove the "default query params"
2546
-     * because we want to get even deleted items etc.
2547
-     *
2548
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2549
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2550
-     * @param array  $query_params like EEM_Base::get_all
2551
-     * @return EE_Base_Class[]
2552
-     * @throws EE_Error
2553
-     */
2554
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2555
-    {
2556
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2557
-        $relation_settings = $this->related_settings_for($model_name);
2558
-        return $relation_settings->get_all_related($model_obj, $query_params);
2559
-    }
2560
-
2561
-
2562
-
2563
-    /**
2564
-     * Deletes all the model objects across the relation indicated by $model_name
2565
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2566
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2567
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2568
-     *
2569
-     * @param EE_Base_Class|int|string $id_or_obj
2570
-     * @param string                   $model_name
2571
-     * @param array                    $query_params
2572
-     * @return int how many deleted
2573
-     * @throws EE_Error
2574
-     */
2575
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2576
-    {
2577
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2578
-        $relation_settings = $this->related_settings_for($model_name);
2579
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2580
-    }
2581
-
2582
-
2583
-
2584
-    /**
2585
-     * Hard deletes all the model objects across the relation indicated by $model_name
2586
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2587
-     * the model objects can't be hard deleted because of blocking related model objects,
2588
-     * just does a soft-delete on them instead.
2589
-     *
2590
-     * @param EE_Base_Class|int|string $id_or_obj
2591
-     * @param string                   $model_name
2592
-     * @param array                    $query_params
2593
-     * @return int how many deleted
2594
-     * @throws EE_Error
2595
-     */
2596
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2597
-    {
2598
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2599
-        $relation_settings = $this->related_settings_for($model_name);
2600
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2601
-    }
2602
-
2603
-
2604
-
2605
-    /**
2606
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2607
-     * unless otherwise specified in the $query_params
2608
-     *
2609
-     * @param        int             /EE_Base_Class $id_or_obj
2610
-     * @param string $model_name     like 'Event', or 'Registration'
2611
-     * @param array  $query_params   like EEM_Base::get_all's
2612
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2613
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2614
-     *                               that by the setting $distinct to TRUE;
2615
-     * @return int
2616
-     * @throws EE_Error
2617
-     */
2618
-    public function count_related(
2619
-        $id_or_obj,
2620
-        $model_name,
2621
-        $query_params = array(),
2622
-        $field_to_count = null,
2623
-        $distinct = false
2624
-    ) {
2625
-        $related_model = $this->get_related_model_obj($model_name);
2626
-        // we're just going to use the query params on the related model's normal get_all query,
2627
-        // except add a condition to say to match the current mod
2628
-        if (! isset($query_params['default_where_conditions'])) {
2629
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2630
-        }
2631
-        $this_model_name = $this->get_this_model_name();
2632
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2633
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2634
-        return $related_model->count($query_params, $field_to_count, $distinct);
2635
-    }
2636
-
2637
-
2638
-
2639
-    /**
2640
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2641
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2642
-     *
2643
-     * @param        int           /EE_Base_Class $id_or_obj
2644
-     * @param string $model_name   like 'Event', or 'Registration'
2645
-     * @param array  $query_params like EEM_Base::get_all's
2646
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2647
-     * @return float
2648
-     * @throws EE_Error
2649
-     */
2650
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2651
-    {
2652
-        $related_model = $this->get_related_model_obj($model_name);
2653
-        if (! is_array($query_params)) {
2654
-            EE_Error::doing_it_wrong(
2655
-                'EEM_Base::sum_related',
2656
-                sprintf(
2657
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2658
-                    gettype($query_params)
2659
-                ),
2660
-                '4.6.0'
2661
-            );
2662
-            $query_params = array();
2663
-        }
2664
-        // we're just going to use the query params on the related model's normal get_all query,
2665
-        // except add a condition to say to match the current mod
2666
-        if (! isset($query_params['default_where_conditions'])) {
2667
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2668
-        }
2669
-        $this_model_name = $this->get_this_model_name();
2670
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2671
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2672
-        return $related_model->sum($query_params, $field_to_sum);
2673
-    }
2674
-
2675
-
2676
-
2677
-    /**
2678
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2679
-     * $modelObject
2680
-     *
2681
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2682
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2683
-     * @param array               $query_params     like EEM_Base::get_all's
2684
-     * @return EE_Base_Class
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2688
-    {
2689
-        $query_params['limit'] = 1;
2690
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2691
-        if ($results) {
2692
-            return array_shift($results);
2693
-        }
2694
-        return null;
2695
-    }
2696
-
2697
-
2698
-
2699
-    /**
2700
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2701
-     *
2702
-     * @return string
2703
-     */
2704
-    public function get_this_model_name()
2705
-    {
2706
-        return str_replace("EEM_", "", get_class($this));
2707
-    }
2708
-
2709
-
2710
-
2711
-    /**
2712
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2713
-     *
2714
-     * @return EE_Any_Foreign_Model_Name_Field
2715
-     * @throws EE_Error
2716
-     */
2717
-    public function get_field_containing_related_model_name()
2718
-    {
2719
-        foreach ($this->field_settings(true) as $field) {
2720
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2721
-                $field_with_model_name = $field;
2722
-            }
2723
-        }
2724
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2725
-            throw new EE_Error(sprintf(
2726
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2727
-                $this->get_this_model_name()
2728
-            ));
2729
-        }
2730
-        return $field_with_model_name;
2731
-    }
2732
-
2733
-
2734
-
2735
-    /**
2736
-     * Inserts a new entry into the database, for each table.
2737
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2738
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2739
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2740
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2741
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2742
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2743
-     *
2744
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2745
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2746
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2747
-     *                              of EEM_Base)
2748
-     * @return int new primary key on main table that got inserted
2749
-     * @throws EE_Error
2750
-     */
2751
-    public function insert($field_n_values)
2752
-    {
2753
-        /**
2754
-         * Filters the fields and their values before inserting an item using the models
2755
-         *
2756
-         * @param array    $fields_n_values keys are the fields and values are their new values
2757
-         * @param EEM_Base $model           the model used
2758
-         */
2759
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2760
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2761
-            $main_table = $this->_get_main_table();
2762
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2763
-            if ($new_id !== false) {
2764
-                foreach ($this->_get_other_tables() as $other_table) {
2765
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2766
-                }
2767
-            }
2768
-            /**
2769
-             * Done just after attempting to insert a new model object
2770
-             *
2771
-             * @param EEM_Base   $model           used
2772
-             * @param array      $fields_n_values fields and their values
2773
-             * @param int|string the              ID of the newly-inserted model object
2774
-             */
2775
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2776
-            return $new_id;
2777
-        }
2778
-        return false;
2779
-    }
2780
-
2781
-
2782
-
2783
-    /**
2784
-     * Checks that the result would satisfy the unique indexes on this model
2785
-     *
2786
-     * @param array  $field_n_values
2787
-     * @param string $action
2788
-     * @return boolean
2789
-     * @throws EE_Error
2790
-     */
2791
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2792
-    {
2793
-        foreach ($this->unique_indexes() as $index_name => $index) {
2794
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2795
-            if ($this->exists(array($uniqueness_where_params))) {
2796
-                EE_Error::add_error(
2797
-                    sprintf(
2798
-                        __(
2799
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2800
-                            "event_espresso"
2801
-                        ),
2802
-                        $action,
2803
-                        $this->_get_class_name(),
2804
-                        $index_name,
2805
-                        implode(",", $index->field_names()),
2806
-                        http_build_query($uniqueness_where_params)
2807
-                    ),
2808
-                    __FILE__,
2809
-                    __FUNCTION__,
2810
-                    __LINE__
2811
-                );
2812
-                return false;
2813
-            }
2814
-        }
2815
-        return true;
2816
-    }
2817
-
2818
-
2819
-
2820
-    /**
2821
-     * Checks the database for an item that conflicts (ie, if this item were
2822
-     * saved to the DB would break some uniqueness requirement, like a primary key
2823
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2824
-     * can be either an EE_Base_Class or an array of fields n values
2825
-     *
2826
-     * @param EE_Base_Class|array $obj_or_fields_array
2827
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2828
-     *                                                 when looking for conflicts
2829
-     *                                                 (ie, if false, we ignore the model object's primary key
2830
-     *                                                 when finding "conflicts". If true, it's also considered).
2831
-     *                                                 Only works for INT primary key,
2832
-     *                                                 STRING primary keys cannot be ignored
2833
-     * @throws EE_Error
2834
-     * @return EE_Base_Class|array
2835
-     */
2836
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2837
-    {
2838
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2839
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2840
-        } elseif (is_array($obj_or_fields_array)) {
2841
-            $fields_n_values = $obj_or_fields_array;
2842
-        } else {
2843
-            throw new EE_Error(
2844
-                sprintf(
2845
-                    __(
2846
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2847
-                        "event_espresso"
2848
-                    ),
2849
-                    get_class($this),
2850
-                    $obj_or_fields_array
2851
-                )
2852
-            );
2853
-        }
2854
-        $query_params = array();
2855
-        if ($this->has_primary_key_field()
2856
-            && ($include_primary_key
2857
-                || $this->get_primary_key_field()
2858
-                   instanceof
2859
-                   EE_Primary_Key_String_Field)
2860
-            && isset($fields_n_values[ $this->primary_key_name() ])
2861
-        ) {
2862
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2863
-        }
2864
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2865
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2866
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2867
-        }
2868
-        // if there is nothing to base this search on, then we shouldn't find anything
2869
-        if (empty($query_params)) {
2870
-            return array();
2871
-        }
2872
-        return $this->get_one($query_params);
2873
-    }
2874
-
2875
-
2876
-
2877
-    /**
2878
-     * Like count, but is optimized and returns a boolean instead of an int
2879
-     *
2880
-     * @param array $query_params
2881
-     * @return boolean
2882
-     * @throws EE_Error
2883
-     */
2884
-    public function exists($query_params)
2885
-    {
2886
-        $query_params['limit'] = 1;
2887
-        return $this->count($query_params) > 0;
2888
-    }
2889
-
2890
-
2891
-
2892
-    /**
2893
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2894
-     *
2895
-     * @param int|string $id
2896
-     * @return boolean
2897
-     * @throws EE_Error
2898
-     */
2899
-    public function exists_by_ID($id)
2900
-    {
2901
-        return $this->exists(
2902
-            array(
2903
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2904
-                array(
2905
-                    $this->primary_key_name() => $id,
2906
-                ),
2907
-            )
2908
-        );
2909
-    }
2910
-
2911
-
2912
-
2913
-    /**
2914
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2915
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2916
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2917
-     * on the main table)
2918
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2919
-     * cases where we want to call it directly rather than via insert().
2920
-     *
2921
-     * @access   protected
2922
-     * @param EE_Table_Base $table
2923
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2924
-     *                                       float
2925
-     * @param int           $new_id          for now we assume only int keys
2926
-     * @throws EE_Error
2927
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2928
-     * @return int ID of new row inserted, or FALSE on failure
2929
-     */
2930
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2931
-    {
2932
-        global $wpdb;
2933
-        $insertion_col_n_values = array();
2934
-        $format_for_insertion = array();
2935
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2936
-        foreach ($fields_on_table as $field_name => $field_obj) {
2937
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2938
-            if ($field_obj->is_auto_increment()) {
2939
-                continue;
2940
-            }
2941
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2942
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2943
-            if ($prepared_value !== null) {
2944
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2945
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2946
-            }
2947
-        }
2948
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2949
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2950
-            // so add the fk to the main table as a column
2951
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2952
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2953
-        }
2954
-        // insert the new entry
2955
-        $result = $this->_do_wpdb_query(
2956
-            'insert',
2957
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
2958
-        );
2959
-        if ($result === false) {
2960
-            return false;
2961
-        }
2962
-        // ok, now what do we return for the ID of the newly-inserted thing?
2963
-        if ($this->has_primary_key_field()) {
2964
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2965
-                return $wpdb->insert_id;
2966
-            }
2967
-            // it's not an auto-increment primary key, so
2968
-            // it must have been supplied
2969
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
2970
-        }
2971
-        // we can't return a  primary key because there is none. instead return
2972
-        // a unique string indicating this model
2973
-        return $this->get_index_primary_key_string($fields_n_values);
2974
-    }
2975
-
2976
-
2977
-
2978
-    /**
2979
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2980
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2981
-     * and there is no default, we pass it along. WPDB will take care of it)
2982
-     *
2983
-     * @param EE_Model_Field_Base $field_obj
2984
-     * @param array               $fields_n_values
2985
-     * @return mixed string|int|float depending on what the table column will be expecting
2986
-     * @throws EE_Error
2987
-     */
2988
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2989
-    {
2990
-        // if this field doesn't allow nullable, don't allow it
2991
-        if (! $field_obj->is_nullable()
2992
-            && (
2993
-                ! isset($fields_n_values[ $field_obj->get_name() ])
2994
-                || $fields_n_values[ $field_obj->get_name() ] === null
2995
-            )
2996
-        ) {
2997
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2998
-        }
2999
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3000
-            ? $fields_n_values[ $field_obj->get_name() ]
3001
-            : null;
3002
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3003
-    }
3004
-
3005
-
3006
-
3007
-    /**
3008
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3009
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3010
-     * the field's prepare_for_set() method.
3011
-     *
3012
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3013
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3014
-     *                                   top of file)
3015
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3016
-     *                                   $value is a custom selection
3017
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3018
-     */
3019
-    private function _prepare_value_for_use_in_db($value, $field)
3020
-    {
3021
-        if ($field && $field instanceof EE_Model_Field_Base) {
3022
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3023
-            switch ($this->_values_already_prepared_by_model_object) {
3024
-                /** @noinspection PhpMissingBreakStatementInspection */
3025
-                case self::not_prepared_by_model_object:
3026
-                    $value = $field->prepare_for_set($value);
3027
-                // purposefully left out "return"
3028
-                case self::prepared_by_model_object:
3029
-                    /** @noinspection SuspiciousAssignmentsInspection */
3030
-                    $value = $field->prepare_for_use_in_db($value);
3031
-                case self::prepared_for_use_in_db:
3032
-                    // leave the value alone
3033
-            }
3034
-            return $value;
3035
-            // phpcs:enable
3036
-        }
3037
-        return $value;
3038
-    }
3039
-
3040
-
3041
-
3042
-    /**
3043
-     * Returns the main table on this model
3044
-     *
3045
-     * @return EE_Primary_Table
3046
-     * @throws EE_Error
3047
-     */
3048
-    protected function _get_main_table()
3049
-    {
3050
-        foreach ($this->_tables as $table) {
3051
-            if ($table instanceof EE_Primary_Table) {
3052
-                return $table;
3053
-            }
3054
-        }
3055
-        throw new EE_Error(sprintf(__(
3056
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3057
-            'event_espresso'
3058
-        ), get_class($this)));
3059
-    }
3060
-
3061
-
3062
-
3063
-    /**
3064
-     * table
3065
-     * returns EE_Primary_Table table name
3066
-     *
3067
-     * @return string
3068
-     * @throws EE_Error
3069
-     */
3070
-    public function table()
3071
-    {
3072
-        return $this->_get_main_table()->get_table_name();
3073
-    }
3074
-
3075
-
3076
-
3077
-    /**
3078
-     * table
3079
-     * returns first EE_Secondary_Table table name
3080
-     *
3081
-     * @return string
3082
-     */
3083
-    public function second_table()
3084
-    {
3085
-        // grab second table from tables array
3086
-        $second_table = end($this->_tables);
3087
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3088
-    }
3089
-
3090
-
3091
-
3092
-    /**
3093
-     * get_table_obj_by_alias
3094
-     * returns table name given it's alias
3095
-     *
3096
-     * @param string $table_alias
3097
-     * @return EE_Primary_Table | EE_Secondary_Table
3098
-     */
3099
-    public function get_table_obj_by_alias($table_alias = '')
3100
-    {
3101
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3102
-    }
3103
-
3104
-
3105
-
3106
-    /**
3107
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3108
-     *
3109
-     * @return EE_Secondary_Table[]
3110
-     */
3111
-    protected function _get_other_tables()
3112
-    {
3113
-        $other_tables = array();
3114
-        foreach ($this->_tables as $table_alias => $table) {
3115
-            if ($table instanceof EE_Secondary_Table) {
3116
-                $other_tables[ $table_alias ] = $table;
3117
-            }
3118
-        }
3119
-        return $other_tables;
3120
-    }
3121
-
3122
-
3123
-
3124
-    /**
3125
-     * Finds all the fields that correspond to the given table
3126
-     *
3127
-     * @param string $table_alias , array key in EEM_Base::_tables
3128
-     * @return EE_Model_Field_Base[]
3129
-     */
3130
-    public function _get_fields_for_table($table_alias)
3131
-    {
3132
-        return $this->_fields[ $table_alias ];
3133
-    }
3134
-
3135
-
3136
-
3137
-    /**
3138
-     * Recurses through all the where parameters, and finds all the related models we'll need
3139
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3140
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3141
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3142
-     * related Registration, Transaction, and Payment models.
3143
-     *
3144
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3145
-     * @return EE_Model_Query_Info_Carrier
3146
-     * @throws EE_Error
3147
-     */
3148
-    public function _extract_related_models_from_query($query_params)
3149
-    {
3150
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3151
-        if (array_key_exists(0, $query_params)) {
3152
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3153
-        }
3154
-        if (array_key_exists('group_by', $query_params)) {
3155
-            if (is_array($query_params['group_by'])) {
3156
-                $this->_extract_related_models_from_sub_params_array_values(
3157
-                    $query_params['group_by'],
3158
-                    $query_info_carrier,
3159
-                    'group_by'
3160
-                );
3161
-            } elseif (! empty($query_params['group_by'])) {
3162
-                $this->_extract_related_model_info_from_query_param(
3163
-                    $query_params['group_by'],
3164
-                    $query_info_carrier,
3165
-                    'group_by'
3166
-                );
3167
-            }
3168
-        }
3169
-        if (array_key_exists('having', $query_params)) {
3170
-            $this->_extract_related_models_from_sub_params_array_keys(
3171
-                $query_params[0],
3172
-                $query_info_carrier,
3173
-                'having'
3174
-            );
3175
-        }
3176
-        if (array_key_exists('order_by', $query_params)) {
3177
-            if (is_array($query_params['order_by'])) {
3178
-                $this->_extract_related_models_from_sub_params_array_keys(
3179
-                    $query_params['order_by'],
3180
-                    $query_info_carrier,
3181
-                    'order_by'
3182
-                );
3183
-            } elseif (! empty($query_params['order_by'])) {
3184
-                $this->_extract_related_model_info_from_query_param(
3185
-                    $query_params['order_by'],
3186
-                    $query_info_carrier,
3187
-                    'order_by'
3188
-                );
3189
-            }
3190
-        }
3191
-        if (array_key_exists('force_join', $query_params)) {
3192
-            $this->_extract_related_models_from_sub_params_array_values(
3193
-                $query_params['force_join'],
3194
-                $query_info_carrier,
3195
-                'force_join'
3196
-            );
3197
-        }
3198
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3199
-        return $query_info_carrier;
3200
-    }
3201
-
3202
-
3203
-
3204
-    /**
3205
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3206
-     *
3207
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3208
-     *                                                      $query_params['having']
3209
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3210
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3211
-     * @throws EE_Error
3212
-     * @return \EE_Model_Query_Info_Carrier
3213
-     */
3214
-    private function _extract_related_models_from_sub_params_array_keys(
3215
-        $sub_query_params,
3216
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3217
-        $query_param_type
3218
-    ) {
3219
-        if (! empty($sub_query_params)) {
3220
-            $sub_query_params = (array) $sub_query_params;
3221
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3222
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3223
-                $this->_extract_related_model_info_from_query_param(
3224
-                    $param,
3225
-                    $model_query_info_carrier,
3226
-                    $query_param_type
3227
-                );
3228
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3229
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3230
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3231
-                // of array('Registration.TXN_ID'=>23)
3232
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3233
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3234
-                    if (! is_array($possibly_array_of_params)) {
3235
-                        throw new EE_Error(sprintf(
3236
-                            __(
3237
-                                "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'))",
3238
-                                "event_espresso"
3239
-                            ),
3240
-                            $param,
3241
-                            $possibly_array_of_params
3242
-                        ));
3243
-                    }
3244
-                    $this->_extract_related_models_from_sub_params_array_keys(
3245
-                        $possibly_array_of_params,
3246
-                        $model_query_info_carrier,
3247
-                        $query_param_type
3248
-                    );
3249
-                } elseif ($query_param_type === 0 // ie WHERE
3250
-                          && is_array($possibly_array_of_params)
3251
-                          && isset($possibly_array_of_params[2])
3252
-                          && $possibly_array_of_params[2] == true
3253
-                ) {
3254
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3255
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3256
-                    // from which we should extract query parameters!
3257
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3258
-                        throw new EE_Error(sprintf(__(
3259
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3260
-                            "event_espresso"
3261
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3262
-                    }
3263
-                    $this->_extract_related_model_info_from_query_param(
3264
-                        $possibly_array_of_params[1],
3265
-                        $model_query_info_carrier,
3266
-                        $query_param_type
3267
-                    );
3268
-                }
3269
-            }
3270
-        }
3271
-        return $model_query_info_carrier;
3272
-    }
3273
-
3274
-
3275
-
3276
-    /**
3277
-     * For extracting related models from forced_joins, where the array values contain the info about what
3278
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3279
-     *
3280
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3281
-     *                                                      $query_params['having']
3282
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3283
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3284
-     * @throws EE_Error
3285
-     * @return \EE_Model_Query_Info_Carrier
3286
-     */
3287
-    private function _extract_related_models_from_sub_params_array_values(
3288
-        $sub_query_params,
3289
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3290
-        $query_param_type
3291
-    ) {
3292
-        if (! empty($sub_query_params)) {
3293
-            if (! is_array($sub_query_params)) {
3294
-                throw new EE_Error(sprintf(
3295
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3296
-                    $sub_query_params
3297
-                ));
3298
-            }
3299
-            foreach ($sub_query_params as $param) {
3300
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3301
-                $this->_extract_related_model_info_from_query_param(
3302
-                    $param,
3303
-                    $model_query_info_carrier,
3304
-                    $query_param_type
3305
-                );
3306
-            }
3307
-        }
3308
-        return $model_query_info_carrier;
3309
-    }
3310
-
3311
-
3312
-
3313
-    /**
3314
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3315
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3316
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3317
-     * but use them in a different order. Eg, we need to know what models we are querying
3318
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3319
-     * other models before we can finalize the where clause SQL.
3320
-     *
3321
-     * @param array $query_params
3322
-     * @throws EE_Error
3323
-     * @return EE_Model_Query_Info_Carrier
3324
-     */
3325
-    public function _create_model_query_info_carrier($query_params)
3326
-    {
3327
-        if (! is_array($query_params)) {
3328
-            EE_Error::doing_it_wrong(
3329
-                'EEM_Base::_create_model_query_info_carrier',
3330
-                sprintf(
3331
-                    __(
3332
-                        '$query_params should be an array, you passed a variable of type %s',
3333
-                        'event_espresso'
3334
-                    ),
3335
-                    gettype($query_params)
3336
-                ),
3337
-                '4.6.0'
3338
-            );
3339
-            $query_params = array();
3340
-        }
3341
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3342
-        // first check if we should alter the query to account for caps or not
3343
-        // because the caps might require us to do extra joins
3344
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3345
-            $query_params[0] = $where_query_params = array_replace_recursive(
3346
-                $where_query_params,
3347
-                $this->caps_where_conditions(
3348
-                    $query_params['caps']
3349
-                )
3350
-            );
3351
-        }
3352
-        $query_object = $this->_extract_related_models_from_query($query_params);
3353
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3354
-        foreach ($where_query_params as $key => $value) {
3355
-            if (is_int($key)) {
3356
-                throw new EE_Error(
3357
-                    sprintf(
3358
-                        __(
3359
-                            "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.",
3360
-                            "event_espresso"
3361
-                        ),
3362
-                        $key,
3363
-                        var_export($value, true),
3364
-                        var_export($query_params, true),
3365
-                        get_class($this)
3366
-                    )
3367
-                );
3368
-            }
3369
-        }
3370
-        if (array_key_exists('default_where_conditions', $query_params)
3371
-            && ! empty($query_params['default_where_conditions'])
3372
-        ) {
3373
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3374
-        } else {
3375
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3376
-        }
3377
-        $where_query_params = array_merge(
3378
-            $this->_get_default_where_conditions_for_models_in_query(
3379
-                $query_object,
3380
-                $use_default_where_conditions,
3381
-                $where_query_params
3382
-            ),
3383
-            $where_query_params
3384
-        );
3385
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3386
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3387
-        // So we need to setup a subquery and use that for the main join.
3388
-        // Note for now this only works on the primary table for the model.
3389
-        // So for instance, you could set the limit array like this:
3390
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3391
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3392
-            $query_object->set_main_model_join_sql(
3393
-                $this->_construct_limit_join_select(
3394
-                    $query_params['on_join_limit'][0],
3395
-                    $query_params['on_join_limit'][1]
3396
-                )
3397
-            );
3398
-        }
3399
-        // set limit
3400
-        if (array_key_exists('limit', $query_params)) {
3401
-            if (is_array($query_params['limit'])) {
3402
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3403
-                    $e = sprintf(
3404
-                        __(
3405
-                            "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)",
3406
-                            "event_espresso"
3407
-                        ),
3408
-                        http_build_query($query_params['limit'])
3409
-                    );
3410
-                    throw new EE_Error($e . "|" . $e);
3411
-                }
3412
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3413
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3414
-            } elseif (! empty($query_params['limit'])) {
3415
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3416
-            }
3417
-        }
3418
-        // set order by
3419
-        if (array_key_exists('order_by', $query_params)) {
3420
-            if (is_array($query_params['order_by'])) {
3421
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3422
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3423
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3424
-                if (array_key_exists('order', $query_params)) {
3425
-                    throw new EE_Error(
3426
-                        sprintf(
3427
-                            __(
3428
-                                "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 ",
3429
-                                "event_espresso"
3430
-                            ),
3431
-                            get_class($this),
3432
-                            implode(", ", array_keys($query_params['order_by'])),
3433
-                            implode(", ", $query_params['order_by']),
3434
-                            $query_params['order']
3435
-                        )
3436
-                    );
3437
-                }
3438
-                $this->_extract_related_models_from_sub_params_array_keys(
3439
-                    $query_params['order_by'],
3440
-                    $query_object,
3441
-                    'order_by'
3442
-                );
3443
-                // assume it's an array of fields to order by
3444
-                $order_array = array();
3445
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3446
-                    $order = $this->_extract_order($order);
3447
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3448
-                }
3449
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3450
-            } elseif (! empty($query_params['order_by'])) {
3451
-                $this->_extract_related_model_info_from_query_param(
3452
-                    $query_params['order_by'],
3453
-                    $query_object,
3454
-                    'order',
3455
-                    $query_params['order_by']
3456
-                );
3457
-                $order = isset($query_params['order'])
3458
-                    ? $this->_extract_order($query_params['order'])
3459
-                    : 'DESC';
3460
-                $query_object->set_order_by_sql(
3461
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3462
-                );
3463
-            }
3464
-        }
3465
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3466
-        if (! array_key_exists('order_by', $query_params)
3467
-            && array_key_exists('order', $query_params)
3468
-            && ! empty($query_params['order'])
3469
-        ) {
3470
-            $pk_field = $this->get_primary_key_field();
3471
-            $order = $this->_extract_order($query_params['order']);
3472
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3473
-        }
3474
-        // set group by
3475
-        if (array_key_exists('group_by', $query_params)) {
3476
-            if (is_array($query_params['group_by'])) {
3477
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3478
-                $group_by_array = array();
3479
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3480
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3481
-                }
3482
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3483
-            } elseif (! empty($query_params['group_by'])) {
3484
-                $query_object->set_group_by_sql(
3485
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3486
-                );
3487
-            }
3488
-        }
3489
-        // set having
3490
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3491
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3492
-        }
3493
-        // now, just verify they didn't pass anything wack
3494
-        foreach ($query_params as $query_key => $query_value) {
3495
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3496
-                throw new EE_Error(
3497
-                    sprintf(
3498
-                        __(
3499
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3500
-                            'event_espresso'
3501
-                        ),
3502
-                        $query_key,
3503
-                        get_class($this),
3504
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3505
-                        implode(',', $this->_allowed_query_params)
3506
-                    )
3507
-                );
3508
-            }
3509
-        }
3510
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3511
-        if (empty($main_model_join_sql)) {
3512
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3513
-        }
3514
-        return $query_object;
3515
-    }
3516
-
3517
-
3518
-
3519
-    /**
3520
-     * Gets the where conditions that should be imposed on the query based on the
3521
-     * context (eg reading frontend, backend, edit or delete).
3522
-     *
3523
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3524
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3525
-     * @throws EE_Error
3526
-     */
3527
-    public function caps_where_conditions($context = self::caps_read)
3528
-    {
3529
-        EEM_Base::verify_is_valid_cap_context($context);
3530
-        $cap_where_conditions = array();
3531
-        $cap_restrictions = $this->caps_missing($context);
3532
-        /**
3533
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3534
-         */
3535
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3536
-            $cap_where_conditions = array_replace_recursive(
3537
-                $cap_where_conditions,
3538
-                $restriction_if_no_cap->get_default_where_conditions()
3539
-            );
3540
-        }
3541
-        return apply_filters(
3542
-            'FHEE__EEM_Base__caps_where_conditions__return',
3543
-            $cap_where_conditions,
3544
-            $this,
3545
-            $context,
3546
-            $cap_restrictions
3547
-        );
3548
-    }
3549
-
3550
-
3551
-
3552
-    /**
3553
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3554
-     * otherwise throws an exception
3555
-     *
3556
-     * @param string $should_be_order_string
3557
-     * @return string either ASC, asc, DESC or desc
3558
-     * @throws EE_Error
3559
-     */
3560
-    private function _extract_order($should_be_order_string)
3561
-    {
3562
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3563
-            return $should_be_order_string;
3564
-        }
3565
-        throw new EE_Error(
3566
-            sprintf(
3567
-                __(
3568
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3569
-                    "event_espresso"
3570
-                ),
3571
-                get_class($this),
3572
-                $should_be_order_string
3573
-            )
3574
-        );
3575
-    }
3576
-
3577
-
3578
-
3579
-    /**
3580
-     * Looks at all the models which are included in this query, and asks each
3581
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3582
-     * so they can be merged
3583
-     *
3584
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3585
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3586
-     *                                                                  'none' means NO default where conditions will
3587
-     *                                                                  be used AT ALL during this query.
3588
-     *                                                                  'other_models_only' means default where
3589
-     *                                                                  conditions from other models will be used, but
3590
-     *                                                                  not for this primary model. 'all', the default,
3591
-     *                                                                  means default where conditions will apply as
3592
-     *                                                                  normal
3593
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3594
-     * @throws EE_Error
3595
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3596
-     */
3597
-    private function _get_default_where_conditions_for_models_in_query(
3598
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3599
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3600
-        $where_query_params = array()
3601
-    ) {
3602
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3603
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3604
-            throw new EE_Error(sprintf(
3605
-                __(
3606
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3607
-                    "event_espresso"
3608
-                ),
3609
-                $use_default_where_conditions,
3610
-                implode(", ", $allowed_used_default_where_conditions_values)
3611
-            ));
3612
-        }
3613
-        $universal_query_params = array();
3614
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3615
-            $universal_query_params = $this->_get_default_where_conditions();
3616
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3617
-            $universal_query_params = $this->_get_minimum_where_conditions();
3618
-        }
3619
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3620
-            $related_model = $this->get_related_model_obj($model_name);
3621
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3622
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3623
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3624
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3625
-            } else {
3626
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3627
-                continue;
3628
-            }
3629
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3630
-                $related_model_universal_where_params,
3631
-                $where_query_params,
3632
-                $related_model,
3633
-                $model_relation_path
3634
-            );
3635
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3636
-                $universal_query_params,
3637
-                $overrides
3638
-            );
3639
-        }
3640
-        return $universal_query_params;
3641
-    }
3642
-
3643
-
3644
-
3645
-    /**
3646
-     * Determines whether or not we should use default where conditions for the model in question
3647
-     * (this model, or other related models).
3648
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3649
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3650
-     * We should use default where conditions on related models when they requested to use default where conditions
3651
-     * on all models, or specifically just on other related models
3652
-     * @param      $default_where_conditions_value
3653
-     * @param bool $for_this_model false means this is for OTHER related models
3654
-     * @return bool
3655
-     */
3656
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3657
-    {
3658
-        return (
3659
-                   $for_this_model
3660
-                   && in_array(
3661
-                       $default_where_conditions_value,
3662
-                       array(
3663
-                           EEM_Base::default_where_conditions_all,
3664
-                           EEM_Base::default_where_conditions_this_only,
3665
-                           EEM_Base::default_where_conditions_minimum_others,
3666
-                       ),
3667
-                       true
3668
-                   )
3669
-               )
3670
-               || (
3671
-                   ! $for_this_model
3672
-                   && in_array(
3673
-                       $default_where_conditions_value,
3674
-                       array(
3675
-                           EEM_Base::default_where_conditions_all,
3676
-                           EEM_Base::default_where_conditions_others_only,
3677
-                       ),
3678
-                       true
3679
-                   )
3680
-               );
3681
-    }
3682
-
3683
-    /**
3684
-     * Determines whether or not we should use default minimum conditions for the model in question
3685
-     * (this model, or other related models).
3686
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3687
-     * where conditions.
3688
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3689
-     * on this model or others
3690
-     * @param      $default_where_conditions_value
3691
-     * @param bool $for_this_model false means this is for OTHER related models
3692
-     * @return bool
3693
-     */
3694
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3695
-    {
3696
-        return (
3697
-                   $for_this_model
3698
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3699
-               )
3700
-               || (
3701
-                   ! $for_this_model
3702
-                   && in_array(
3703
-                       $default_where_conditions_value,
3704
-                       array(
3705
-                           EEM_Base::default_where_conditions_minimum_others,
3706
-                           EEM_Base::default_where_conditions_minimum_all,
3707
-                       ),
3708
-                       true
3709
-                   )
3710
-               );
3711
-    }
3712
-
3713
-
3714
-    /**
3715
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3716
-     * then we also add a special where condition which allows for that model's primary key
3717
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3718
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3719
-     *
3720
-     * @param array    $default_where_conditions
3721
-     * @param array    $provided_where_conditions
3722
-     * @param EEM_Base $model
3723
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3724
-     * @return array like EEM_Base::get_all's $query_params[0]
3725
-     * @throws EE_Error
3726
-     */
3727
-    private function _override_defaults_or_make_null_friendly(
3728
-        $default_where_conditions,
3729
-        $provided_where_conditions,
3730
-        $model,
3731
-        $model_relation_path
3732
-    ) {
3733
-        $null_friendly_where_conditions = array();
3734
-        $none_overridden = true;
3735
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3736
-        foreach ($default_where_conditions as $key => $val) {
3737
-            if (isset($provided_where_conditions[ $key ])) {
3738
-                $none_overridden = false;
3739
-            } else {
3740
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3741
-            }
3742
-        }
3743
-        if ($none_overridden && $default_where_conditions) {
3744
-            if ($model->has_primary_key_field()) {
3745
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3746
-                                                                                . "."
3747
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3748
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error(
520
+				sprintf(
521
+					__(
522
+						'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.',
523
+						'event_espresso'
524
+					),
525
+					get_class($this)
526
+				)
527
+			);
528
+		}
529
+		/**
530
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
+		 */
532
+		if (empty(EEM_Base::$_model_query_blog_id)) {
533
+			EEM_Base::set_model_query_blog_id();
534
+		}
535
+		/**
536
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
+		 * just use EE_Register_Model_Extension
538
+		 *
539
+		 * @var EE_Table_Base[] $_tables
540
+		 */
541
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
+		foreach ($this->_tables as $table_alias => $table_obj) {
543
+			/** @var $table_obj EE_Table_Base */
544
+			$table_obj->_construct_finalize_with_alias($table_alias);
545
+			if ($table_obj instanceof EE_Secondary_Table) {
546
+				/** @var $table_obj EE_Secondary_Table */
547
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
+			}
549
+		}
550
+		/**
551
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
+		 * EE_Register_Model_Extension
553
+		 *
554
+		 * @param EE_Model_Field_Base[] $_fields
555
+		 */
556
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
+		$this->_invalidate_field_caches();
558
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
559
+			if (! array_key_exists($table_alias, $this->_tables)) {
560
+				throw new EE_Error(sprintf(__(
561
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
+					'event_espresso'
563
+				), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				// primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			// make extra meta related to everything, but don't block deleting things just
575
+			// because they have related extra meta info. For now just orphan those extra meta
576
+			// in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		// and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = (array) apply_filters(
590
+			'FHEE__' . get_class($this) . '__construct__model_relations',
591
+			$this->_model_relations
592
+		);
593
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
594
+			/** @var $relation_obj EE_Model_Relation_Base */
595
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
+		}
597
+		foreach ($this->_indexes as $index_name => $index_obj) {
598
+			/** @var $index_obj EE_Index */
599
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
+		}
601
+		$this->set_timezone($timezone);
602
+		// finalize default where condition strategy, or set default
603
+		if (! $this->_default_where_conditions_strategy) {
604
+			// nothing was set during child constructor, so set default
605
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
608
+		if (! $this->_minimum_where_conditions_strategy) {
609
+			// nothing was set during child constructor, so set default
610
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
+		}
612
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
614
+		// to indicate to NOT set it, set it to the logical default
615
+		if ($this->_caps_slug === null) {
616
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
+		}
618
+		// initialize the standard cap restriction generators if none were specified by the child constructor
619
+		if ($this->_cap_restriction_generators !== false) {
620
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
+						new EE_Restriction_Generator_Protected(),
625
+						$cap_context,
626
+						$this
627
+					);
628
+				}
629
+			}
630
+		}
631
+		// if there are cap restriction generators, use them to make the default cap restrictions
632
+		if ($this->_cap_restriction_generators !== false) {
633
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
+				if (! $generator_object) {
635
+					continue;
636
+				}
637
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
+					throw new EE_Error(
639
+						sprintf(
640
+							__(
641
+								'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.',
642
+								'event_espresso'
643
+							),
644
+							$context,
645
+							$this->get_this_model_name()
646
+						)
647
+					);
648
+				}
649
+				$action = $this->cap_action_for_context($context);
650
+				if (! $generator_object->construction_finalized()) {
651
+					$generator_object->_construct_finalize($this, $action);
652
+				}
653
+			}
654
+		}
655
+		do_action('AHEE__' . get_class($this) . '__construct__end');
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 * Used to set the $_model_query_blog_id static property.
662
+	 *
663
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
+	 *                      value for get_current_blog_id() will be used.
665
+	 */
666
+	public static function set_model_query_blog_id($blog_id = 0)
667
+	{
668
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * Returns whatever is set as the internal $model_query_blog_id.
675
+	 *
676
+	 * @return int
677
+	 */
678
+	public static function get_model_query_blog_id()
679
+	{
680
+		return EEM_Base::$_model_query_blog_id;
681
+	}
682
+
683
+
684
+
685
+	/**
686
+	 * This function is a singleton method used to instantiate the Espresso_model object
687
+	 *
688
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
+	 *                                (and any incoming timezone data that gets saved).
690
+	 *                                Note this just sends the timezone info to the date time model field objects.
691
+	 *                                Default is NULL
692
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
+	 * @return static (as in the concrete child class)
694
+	 * @throws EE_Error
695
+	 * @throws InvalidArgumentException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws InvalidInterfaceException
698
+	 */
699
+	public static function instance($timezone = null)
700
+	{
701
+		// check if instance of Espresso_model already exists
702
+		if (! static::$_instance instanceof static) {
703
+			// instantiate Espresso_model
704
+			static::$_instance = new static(
705
+				$timezone,
706
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
+			);
708
+		}
709
+		// we might have a timezone set, let set_timezone decide what to do with it
710
+		static::$_instance->set_timezone($timezone);
711
+		// Espresso_model object
712
+		return static::$_instance;
713
+	}
714
+
715
+
716
+
717
+	/**
718
+	 * resets the model and returns it
719
+	 *
720
+	 * @param null | string $timezone
721
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
+	 * all its properties reset; if it wasn't instantiated, returns null)
723
+	 * @throws EE_Error
724
+	 * @throws ReflectionException
725
+	 * @throws InvalidArgumentException
726
+	 * @throws InvalidDataTypeException
727
+	 * @throws InvalidInterfaceException
728
+	 */
729
+	public static function reset($timezone = null)
730
+	{
731
+		if (static::$_instance instanceof EEM_Base) {
732
+			// let's try to NOT swap out the current instance for a new one
733
+			// because if someone has a reference to it, we can't remove their reference
734
+			// so it's best to keep using the same reference, but change the original object
735
+			// reset all its properties to their original values as defined in the class
736
+			$r = new ReflectionClass(get_class(static::$_instance));
737
+			$static_properties = $r->getStaticProperties();
738
+			foreach ($r->getDefaultProperties() as $property => $value) {
739
+				// don't set instance to null like it was originally,
740
+				// but it's static anyways, and we're ignoring static properties (for now at least)
741
+				if (! isset($static_properties[ $property ])) {
742
+					static::$_instance->{$property} = $value;
743
+				}
744
+			}
745
+			// and then directly call its constructor again, like we would if we were creating a new one
746
+			static::$_instance->__construct(
747
+				$timezone,
748
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
+			);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * @return LoaderInterface
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 */
763
+	private static function getLoader()
764
+	{
765
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
766
+			EEM_Base::$loader = LoaderFactory::getLoader();
767
+		}
768
+		return EEM_Base::$loader;
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
+	 *
776
+	 * @param  boolean $translated return localized strings or JUST the array.
777
+	 * @return array
778
+	 * @throws EE_Error
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws InvalidInterfaceException
782
+	 */
783
+	public function status_array($translated = false)
784
+	{
785
+		if (! array_key_exists('Status', $this->_model_relations)) {
786
+			return array();
787
+		}
788
+		$model_name = $this->get_this_model_name();
789
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
+		$status_array = array();
792
+		foreach ($stati as $status) {
793
+			$status_array[ $status->ID() ] = $status->get('STS_code');
794
+		}
795
+		return $translated
796
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
+			: $status_array;
798
+	}
799
+
800
+
801
+
802
+	/**
803
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
+	 *
805
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/eem-base-get-all.md
806
+	 *                             or if you have the development copy of EE you can view this at the path:
807
+	 *                             /docs/G--Model-System/eem-base-get-all.md
808
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
809
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
810
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
811
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
812
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
813
+	 *                                        array( array(
814
+	 *                                        'OR'=>array(
815
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
816
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
817
+	 *                                        )
818
+	 *                                        ),
819
+	 *                                        'limit'=>10,
820
+	 *                                        'group_by'=>'TXN_ID'
821
+	 *                                        ));
822
+	 *                                        get all the answers to the question titled "shirt size" for event with id
823
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
824
+	 *                                        'Question.QST_display_text'=>'shirt size',
825
+	 *                                        'Registration.Event.EVT_ID'=>12
826
+	 *                                        ),
827
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
828
+	 *                                        ));
829
+	 * @throws EE_Error
830
+	 */
831
+	public function get_all($query_params = array())
832
+	{
833
+		if (isset($query_params['limit'])
834
+			&& ! isset($query_params['group_by'])
835
+		) {
836
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
837
+		}
838
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
839
+	}
840
+
841
+
842
+
843
+	/**
844
+	 * Modifies the query parameters so we only get back model objects
845
+	 * that "belong" to the current user
846
+	 *
847
+	 * @param array $query_params @see EEM_Base::get_all()
848
+	 * @return array like EEM_Base::get_all
849
+	 */
850
+	public function alter_query_params_to_only_include_mine($query_params = array())
851
+	{
852
+		$wp_user_field_name = $this->wp_user_field_name();
853
+		if ($wp_user_field_name) {
854
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
855
+		}
856
+		return $query_params;
857
+	}
858
+
859
+
860
+
861
+	/**
862
+	 * Returns the name of the field's name that points to the WP_User table
863
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
864
+	 * foreign key to the WP_User table)
865
+	 *
866
+	 * @return string|boolean string on success, boolean false when there is no
867
+	 * foreign key to the WP_User table
868
+	 */
869
+	public function wp_user_field_name()
870
+	{
871
+		try {
872
+			if (! empty($this->_model_chain_to_wp_user)) {
873
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
874
+				$last_model_name = end($models_to_follow_to_wp_users);
875
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
876
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
877
+			} else {
878
+				$model_with_fk_to_wp_users = $this;
879
+				$model_chain_to_wp_user = '';
880
+			}
881
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
882
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
883
+		} catch (EE_Error $e) {
884
+			return false;
885
+		}
886
+	}
887
+
888
+
889
+
890
+	/**
891
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
892
+	 * (or transiently-related model) has a foreign key to the wp_users table;
893
+	 * useful for finding if model objects of this type are 'owned' by the current user.
894
+	 * This is an empty string when the foreign key is on this model and when it isn't,
895
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
896
+	 * (or transiently-related model)
897
+	 *
898
+	 * @return string
899
+	 */
900
+	public function model_chain_to_wp_user()
901
+	{
902
+		return $this->_model_chain_to_wp_user;
903
+	}
904
+
905
+
906
+
907
+	/**
908
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
909
+	 * like how registrations don't have a foreign key to wp_users, but the
910
+	 * events they are for are), or is unrelated to wp users.
911
+	 * generally available
912
+	 *
913
+	 * @return boolean
914
+	 */
915
+	public function is_owned()
916
+	{
917
+		if ($this->model_chain_to_wp_user()) {
918
+			return true;
919
+		}
920
+		try {
921
+			$this->get_foreign_key_to('WP_User');
922
+			return true;
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+	/**
930
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
931
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
932
+	 * the model)
933
+	 *
934
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
935
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
936
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
937
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
938
+	 *                                  override this and set the select to "*", or a specific column name, like
939
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
940
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
941
+	 *                                  the aliases used to refer to this selection, and values are to be
942
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
943
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
944
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
945
+	 * @throws EE_Error
946
+	 * @throws InvalidArgumentException
947
+	 */
948
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
949
+	{
950
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
951
+		;
952
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
953
+		$select_expressions = $columns_to_select === null
954
+			? $this->_construct_default_select_sql($model_query_info)
955
+			: '';
956
+		if ($this->_custom_selections instanceof CustomSelects) {
957
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
958
+			$select_expressions .= $select_expressions
959
+				? ', ' . $custom_expressions
960
+				: $custom_expressions;
961
+		}
962
+
963
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
964
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
965
+	}
966
+
967
+
968
+	/**
969
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
970
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
971
+	 * method of including extra select information.
972
+	 *
973
+	 * @param array             $query_params
974
+	 * @param null|array|string $columns_to_select
975
+	 * @return null|CustomSelects
976
+	 * @throws InvalidArgumentException
977
+	 */
978
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
979
+	{
980
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
981
+			return null;
982
+		}
983
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
984
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
985
+		return new CustomSelects($selects);
986
+	}
987
+
988
+
989
+
990
+	/**
991
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
992
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
993
+	 * take care of joins, field preparation etc.
994
+	 *
995
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
996
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
997
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
998
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
999
+	 *                                  override this and set the select to "*", or a specific column name, like
1000
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1001
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1002
+	 *                                  the aliases used to refer to this selection, and values are to be
1003
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1004
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1005
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1006
+	 * @throws EE_Error
1007
+	 */
1008
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1009
+	{
1010
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1011
+	}
1012
+
1013
+
1014
+
1015
+	/**
1016
+	 * For creating a custom select statement
1017
+	 *
1018
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1019
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1020
+	 *                                 SQL, and 1=>is the datatype
1021
+	 * @throws EE_Error
1022
+	 * @return string
1023
+	 */
1024
+	private function _construct_select_from_input($columns_to_select)
1025
+	{
1026
+		if (is_array($columns_to_select)) {
1027
+			$select_sql_array = array();
1028
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1029
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1030
+					throw new EE_Error(
1031
+						sprintf(
1032
+							__(
1033
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1034
+								'event_espresso'
1035
+							),
1036
+							$selection_and_datatype,
1037
+							$alias
1038
+						)
1039
+					);
1040
+				}
1041
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1042
+					throw new EE_Error(
1043
+						sprintf(
1044
+							esc_html__(
1045
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1046
+								'event_espresso'
1047
+							),
1048
+							$selection_and_datatype[1],
1049
+							$selection_and_datatype[0],
1050
+							$alias,
1051
+							implode(', ', $this->_valid_wpdb_data_types)
1052
+						)
1053
+					);
1054
+				}
1055
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1056
+			}
1057
+			$columns_to_select_string = implode(', ', $select_sql_array);
1058
+		} else {
1059
+			$columns_to_select_string = $columns_to_select;
1060
+		}
1061
+		return $columns_to_select_string;
1062
+	}
1063
+
1064
+
1065
+
1066
+	/**
1067
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1068
+	 *
1069
+	 * @return string
1070
+	 * @throws EE_Error
1071
+	 */
1072
+	public function primary_key_name()
1073
+	{
1074
+		return $this->get_primary_key_field()->get_name();
1075
+	}
1076
+
1077
+
1078
+
1079
+	/**
1080
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1081
+	 * If there is no primary key on this model, $id is treated as primary key string
1082
+	 *
1083
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1084
+	 * @return EE_Base_Class
1085
+	 */
1086
+	public function get_one_by_ID($id)
1087
+	{
1088
+		if ($this->get_from_entity_map($id)) {
1089
+			return $this->get_from_entity_map($id);
1090
+		}
1091
+		return $this->get_one(
1092
+			$this->alter_query_params_to_restrict_by_ID(
1093
+				$id,
1094
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1095
+			)
1096
+		);
1097
+	}
1098
+
1099
+
1100
+
1101
+	/**
1102
+	 * Alters query parameters to only get items with this ID are returned.
1103
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1104
+	 * or could just be a simple primary key ID
1105
+	 *
1106
+	 * @param int   $id
1107
+	 * @param array $query_params
1108
+	 * @return array of normal query params, @see EEM_Base::get_all
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1112
+	{
1113
+		if (! isset($query_params[0])) {
1114
+			$query_params[0] = array();
1115
+		}
1116
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1117
+		if ($conditions_from_id === null) {
1118
+			$query_params[0][ $this->primary_key_name() ] = $id;
1119
+		} else {
1120
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1121
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1122
+		}
1123
+		return $query_params;
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1130
+	 * array. If no item is found, null is returned.
1131
+	 *
1132
+	 * @param array $query_params like EEM_Base's $query_params variable.
1133
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1134
+	 * @throws EE_Error
1135
+	 */
1136
+	public function get_one($query_params = array())
1137
+	{
1138
+		if (! is_array($query_params)) {
1139
+			EE_Error::doing_it_wrong(
1140
+				'EEM_Base::get_one',
1141
+				sprintf(
1142
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1143
+					gettype($query_params)
1144
+				),
1145
+				'4.6.0'
1146
+			);
1147
+			$query_params = array();
1148
+		}
1149
+		$query_params['limit'] = 1;
1150
+		$items = $this->get_all($query_params);
1151
+		if (empty($items)) {
1152
+			return null;
1153
+		}
1154
+		return array_shift($items);
1155
+	}
1156
+
1157
+
1158
+
1159
+	/**
1160
+	 * Returns the next x number of items in sequence from the given value as
1161
+	 * found in the database matching the given query conditions.
1162
+	 *
1163
+	 * @param mixed $current_field_value    Value used for the reference point.
1164
+	 * @param null  $field_to_order_by      What field is used for the
1165
+	 *                                      reference point.
1166
+	 * @param int   $limit                  How many to return.
1167
+	 * @param array $query_params           Extra conditions on the query.
1168
+	 * @param null  $columns_to_select      If left null, then an array of
1169
+	 *                                      EE_Base_Class objects is returned,
1170
+	 *                                      otherwise you can indicate just the
1171
+	 *                                      columns you want returned.
1172
+	 * @return EE_Base_Class[]|array
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function next_x(
1176
+		$current_field_value,
1177
+		$field_to_order_by = null,
1178
+		$limit = 1,
1179
+		$query_params = array(),
1180
+		$columns_to_select = null
1181
+	) {
1182
+		return $this->_get_consecutive(
1183
+			$current_field_value,
1184
+			'>',
1185
+			$field_to_order_by,
1186
+			$limit,
1187
+			$query_params,
1188
+			$columns_to_select
1189
+		);
1190
+	}
1191
+
1192
+
1193
+
1194
+	/**
1195
+	 * Returns the previous x number of items in sequence from the given value
1196
+	 * as found in the database matching the given query conditions.
1197
+	 *
1198
+	 * @param mixed $current_field_value    Value used for the reference point.
1199
+	 * @param null  $field_to_order_by      What field is used for the
1200
+	 *                                      reference point.
1201
+	 * @param int   $limit                  How many to return.
1202
+	 * @param array $query_params           Extra conditions on the query.
1203
+	 * @param null  $columns_to_select      If left null, then an array of
1204
+	 *                                      EE_Base_Class objects is returned,
1205
+	 *                                      otherwise you can indicate just the
1206
+	 *                                      columns you want returned.
1207
+	 * @return EE_Base_Class[]|array
1208
+	 * @throws EE_Error
1209
+	 */
1210
+	public function previous_x(
1211
+		$current_field_value,
1212
+		$field_to_order_by = null,
1213
+		$limit = 1,
1214
+		$query_params = array(),
1215
+		$columns_to_select = null
1216
+	) {
1217
+		return $this->_get_consecutive(
1218
+			$current_field_value,
1219
+			'<',
1220
+			$field_to_order_by,
1221
+			$limit,
1222
+			$query_params,
1223
+			$columns_to_select
1224
+		);
1225
+	}
1226
+
1227
+
1228
+
1229
+	/**
1230
+	 * Returns the next item in sequence from the given value as found in the
1231
+	 * database matching the given query conditions.
1232
+	 *
1233
+	 * @param mixed $current_field_value    Value used for the reference point.
1234
+	 * @param null  $field_to_order_by      What field is used for the
1235
+	 *                                      reference point.
1236
+	 * @param array $query_params           Extra conditions on the query.
1237
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1238
+	 *                                      object is returned, otherwise you
1239
+	 *                                      can indicate just the columns you
1240
+	 *                                      want and a single array indexed by
1241
+	 *                                      the columns will be returned.
1242
+	 * @return EE_Base_Class|null|array()
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	public function next(
1246
+		$current_field_value,
1247
+		$field_to_order_by = null,
1248
+		$query_params = array(),
1249
+		$columns_to_select = null
1250
+	) {
1251
+		$results = $this->_get_consecutive(
1252
+			$current_field_value,
1253
+			'>',
1254
+			$field_to_order_by,
1255
+			1,
1256
+			$query_params,
1257
+			$columns_to_select
1258
+		);
1259
+		return empty($results) ? null : reset($results);
1260
+	}
1261
+
1262
+
1263
+
1264
+	/**
1265
+	 * Returns the previous item in sequence from the given value as found in
1266
+	 * the database matching the given query conditions.
1267
+	 *
1268
+	 * @param mixed $current_field_value    Value used for the reference point.
1269
+	 * @param null  $field_to_order_by      What field is used for the
1270
+	 *                                      reference point.
1271
+	 * @param array $query_params           Extra conditions on the query.
1272
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1273
+	 *                                      object is returned, otherwise you
1274
+	 *                                      can indicate just the columns you
1275
+	 *                                      want and a single array indexed by
1276
+	 *                                      the columns will be returned.
1277
+	 * @return EE_Base_Class|null|array()
1278
+	 * @throws EE_Error
1279
+	 */
1280
+	public function previous(
1281
+		$current_field_value,
1282
+		$field_to_order_by = null,
1283
+		$query_params = array(),
1284
+		$columns_to_select = null
1285
+	) {
1286
+		$results = $this->_get_consecutive(
1287
+			$current_field_value,
1288
+			'<',
1289
+			$field_to_order_by,
1290
+			1,
1291
+			$query_params,
1292
+			$columns_to_select
1293
+		);
1294
+		return empty($results) ? null : reset($results);
1295
+	}
1296
+
1297
+
1298
+
1299
+	/**
1300
+	 * Returns the a consecutive number of items in sequence from the given
1301
+	 * value as found in the database matching the given query conditions.
1302
+	 *
1303
+	 * @param mixed  $current_field_value   Value used for the reference point.
1304
+	 * @param string $operand               What operand is used for the sequence.
1305
+	 * @param string $field_to_order_by     What field is used for the reference point.
1306
+	 * @param int    $limit                 How many to return.
1307
+	 * @param array  $query_params          Extra conditions on the query.
1308
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1309
+	 *                                      otherwise you can indicate just the columns you want returned.
1310
+	 * @return EE_Base_Class[]|array
1311
+	 * @throws EE_Error
1312
+	 */
1313
+	protected function _get_consecutive(
1314
+		$current_field_value,
1315
+		$operand = '>',
1316
+		$field_to_order_by = null,
1317
+		$limit = 1,
1318
+		$query_params = array(),
1319
+		$columns_to_select = null
1320
+	) {
1321
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1322
+		if (empty($field_to_order_by)) {
1323
+			if ($this->has_primary_key_field()) {
1324
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1325
+			} else {
1326
+				if (WP_DEBUG) {
1327
+					throw new EE_Error(__(
1328
+						'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).',
1329
+						'event_espresso'
1330
+					));
1331
+				}
1332
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1333
+				return array();
1334
+			}
1335
+		}
1336
+		if (! is_array($query_params)) {
1337
+			EE_Error::doing_it_wrong(
1338
+				'EEM_Base::_get_consecutive',
1339
+				sprintf(
1340
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1341
+					gettype($query_params)
1342
+				),
1343
+				'4.6.0'
1344
+			);
1345
+			$query_params = array();
1346
+		}
1347
+		// let's add the where query param for consecutive look up.
1348
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1349
+		$query_params['limit'] = $limit;
1350
+		// set direction
1351
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1352
+		$query_params['order_by'] = $operand === '>'
1353
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1354
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1355
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1356
+		if (empty($columns_to_select)) {
1357
+			return $this->get_all($query_params);
1358
+		}
1359
+		// getting just the fields
1360
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1361
+	}
1362
+
1363
+
1364
+
1365
+	/**
1366
+	 * This sets the _timezone property after model object has been instantiated.
1367
+	 *
1368
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1369
+	 */
1370
+	public function set_timezone($timezone)
1371
+	{
1372
+		if ($timezone !== null) {
1373
+			$this->_timezone = $timezone;
1374
+		}
1375
+		// note we need to loop through relations and set the timezone on those objects as well.
1376
+		foreach ($this->_model_relations as $relation) {
1377
+			$relation->set_timezone($timezone);
1378
+		}
1379
+		// and finally we do the same for any datetime fields
1380
+		foreach ($this->_fields as $field) {
1381
+			if ($field instanceof EE_Datetime_Field) {
1382
+				$field->set_timezone($timezone);
1383
+			}
1384
+		}
1385
+	}
1386
+
1387
+
1388
+
1389
+	/**
1390
+	 * This just returns whatever is set for the current timezone.
1391
+	 *
1392
+	 * @access public
1393
+	 * @return string
1394
+	 */
1395
+	public function get_timezone()
1396
+	{
1397
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1398
+		if (empty($this->_timezone)) {
1399
+			foreach ($this->_fields as $field) {
1400
+				if ($field instanceof EE_Datetime_Field) {
1401
+					$this->set_timezone($field->get_timezone());
1402
+					break;
1403
+				}
1404
+			}
1405
+		}
1406
+		// if timezone STILL empty then return the default timezone for the site.
1407
+		if (empty($this->_timezone)) {
1408
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1409
+		}
1410
+		return $this->_timezone;
1411
+	}
1412
+
1413
+
1414
+
1415
+	/**
1416
+	 * This returns the date formats set for the given field name and also ensures that
1417
+	 * $this->_timezone property is set correctly.
1418
+	 *
1419
+	 * @since 4.6.x
1420
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1421
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1422
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1423
+	 * @return array formats in an array with the date format first, and the time format last.
1424
+	 */
1425
+	public function get_formats_for($field_name, $pretty = false)
1426
+	{
1427
+		$field_settings = $this->field_settings_for($field_name);
1428
+		// if not a valid EE_Datetime_Field then throw error
1429
+		if (! $field_settings instanceof EE_Datetime_Field) {
1430
+			throw new EE_Error(sprintf(__(
1431
+				'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.',
1432
+				'event_espresso'
1433
+			), $field_name));
1434
+		}
1435
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1436
+		// the field.
1437
+		$this->_timezone = $field_settings->get_timezone();
1438
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1439
+	}
1440
+
1441
+
1442
+
1443
+	/**
1444
+	 * This returns the current time in a format setup for a query on this model.
1445
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1446
+	 * it will return:
1447
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1448
+	 *  NOW
1449
+	 *  - or a unix timestamp (equivalent to time())
1450
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1451
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1452
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1453
+	 * @since 4.6.x
1454
+	 * @param string $field_name       The field the current time is needed for.
1455
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1456
+	 *                                 formatted string matching the set format for the field in the set timezone will
1457
+	 *                                 be returned.
1458
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1459
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1460
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1461
+	 *                                 exception is triggered.
1462
+	 */
1463
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1464
+	{
1465
+		$formats = $this->get_formats_for($field_name);
1466
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1467
+		if ($timestamp) {
1468
+			return $DateTime->format('U');
1469
+		}
1470
+		// not returning timestamp, so return formatted string in timezone.
1471
+		switch ($what) {
1472
+			case 'time':
1473
+				return $DateTime->format($formats[1]);
1474
+				break;
1475
+			case 'date':
1476
+				return $DateTime->format($formats[0]);
1477
+				break;
1478
+			default:
1479
+				return $DateTime->format(implode(' ', $formats));
1480
+				break;
1481
+		}
1482
+	}
1483
+
1484
+
1485
+
1486
+	/**
1487
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1488
+	 * for the model are.  Returns a DateTime object.
1489
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1490
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1491
+	 * ignored.
1492
+	 *
1493
+	 * @param string $field_name      The field being setup.
1494
+	 * @param string $timestring      The date time string being used.
1495
+	 * @param string $incoming_format The format for the time string.
1496
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1497
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1498
+	 *                                format is
1499
+	 *                                'U', this is ignored.
1500
+	 * @return DateTime
1501
+	 * @throws EE_Error
1502
+	 */
1503
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1504
+	{
1505
+		// just using this to ensure the timezone is set correctly internally
1506
+		$this->get_formats_for($field_name);
1507
+		// load EEH_DTT_Helper
1508
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1509
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1510
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1511
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1512
+	}
1513
+
1514
+
1515
+
1516
+	/**
1517
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1518
+	 *
1519
+	 * @return EE_Table_Base[]
1520
+	 */
1521
+	public function get_tables()
1522
+	{
1523
+		return $this->_tables;
1524
+	}
1525
+
1526
+
1527
+
1528
+	/**
1529
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1530
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1531
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1532
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1533
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1534
+	 * model object with EVT_ID = 1
1535
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1536
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1537
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1538
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1539
+	 * are not specified)
1540
+	 *
1541
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1542
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1543
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1544
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1545
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1546
+	 *                                         ID=34, we'd use this method as follows:
1547
+	 *                                         EEM_Transaction::instance()->update(
1548
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1549
+	 *                                         array(array('TXN_ID'=>34)));
1550
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1551
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1552
+	 *                                         consider updating Question's QST_admin_label field is of type
1553
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1554
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1555
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1556
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1557
+	 *                                         TRUE, it is assumed that you've already called
1558
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1559
+	 *                                         malicious javascript. However, if
1560
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1561
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1562
+	 *                                         and every other field, before insertion. We provide this parameter
1563
+	 *                                         because model objects perform their prepare_for_set function on all
1564
+	 *                                         their values, and so don't need to be called again (and in many cases,
1565
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1566
+	 *                                         prepare_for_set method...)
1567
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1568
+	 *                                         in this model's entity map according to $fields_n_values that match
1569
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1570
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1571
+	 *                                         could get out-of-sync with the database
1572
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1573
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1574
+	 *                                         bad)
1575
+	 * @throws EE_Error
1576
+	 */
1577
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1578
+	{
1579
+		if (! is_array($query_params)) {
1580
+			EE_Error::doing_it_wrong(
1581
+				'EEM_Base::update',
1582
+				sprintf(
1583
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1584
+					gettype($query_params)
1585
+				),
1586
+				'4.6.0'
1587
+			);
1588
+			$query_params = array();
1589
+		}
1590
+		/**
1591
+		 * Action called before a model update call has been made.
1592
+		 *
1593
+		 * @param EEM_Base $model
1594
+		 * @param array    $fields_n_values the updated fields and their new values
1595
+		 * @param array    $query_params    @see EEM_Base::get_all()
1596
+		 */
1597
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1598
+		/**
1599
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1600
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1601
+		 *
1602
+		 * @param array    $fields_n_values fields and their new values
1603
+		 * @param EEM_Base $model           the model being queried
1604
+		 * @param array    $query_params    see EEM_Base::get_all()
1605
+		 */
1606
+		$fields_n_values = (array) apply_filters(
1607
+			'FHEE__EEM_Base__update__fields_n_values',
1608
+			$fields_n_values,
1609
+			$this,
1610
+			$query_params
1611
+		);
1612
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1613
+		// to do that, for each table, verify that it's PK isn't null.
1614
+		$tables = $this->get_tables();
1615
+		// 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
1616
+		// NOTE: we should make this code more efficient by NOT querying twice
1617
+		// before the real update, but that needs to first go through ALPHA testing
1618
+		// as it's dangerous. says Mike August 8 2014
1619
+		// we want to make sure the default_where strategy is ignored
1620
+		$this->_ignore_where_strategy = true;
1621
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1622
+		foreach ($wpdb_select_results as $wpdb_result) {
1623
+			// type cast stdClass as array
1624
+			$wpdb_result = (array) $wpdb_result;
1625
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1626
+			if ($this->has_primary_key_field()) {
1627
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1628
+			} else {
1629
+				// 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)
1630
+				$main_table_pk_value = null;
1631
+			}
1632
+			// 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
1633
+			// 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
1634
+			if (count($tables) > 1) {
1635
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1636
+				// in that table, and so we'll want to insert one
1637
+				foreach ($tables as $table_obj) {
1638
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1639
+					// if there is no private key for this table on the results, it means there's no entry
1640
+					// in this table, right? so insert a row in the current table, using any fields available
1641
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1642
+						   && $wpdb_result[ $this_table_pk_column ])
1643
+					) {
1644
+						$success = $this->_insert_into_specific_table(
1645
+							$table_obj,
1646
+							$fields_n_values,
1647
+							$main_table_pk_value
1648
+						);
1649
+						// if we died here, report the error
1650
+						if (! $success) {
1651
+							return false;
1652
+						}
1653
+					}
1654
+				}
1655
+			}
1656
+			//              //and now check that if we have cached any models by that ID on the model, that
1657
+			//              //they also get updated properly
1658
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1659
+			//              if( $model_object ){
1660
+			//                  foreach( $fields_n_values as $field => $value ){
1661
+			//                      $model_object->set($field, $value);
1662
+			// let's make sure default_where strategy is followed now
1663
+			$this->_ignore_where_strategy = false;
1664
+		}
1665
+		// if we want to keep model objects in sync, AND
1666
+		// if this wasn't called from a model object (to update itself)
1667
+		// then we want to make sure we keep all the existing
1668
+		// model objects in sync with the db
1669
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1670
+			if ($this->has_primary_key_field()) {
1671
+				$model_objs_affected_ids = $this->get_col($query_params);
1672
+			} else {
1673
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1674
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1675
+				$model_objs_affected_ids = array();
1676
+				foreach ($models_affected_key_columns as $row) {
1677
+					$combined_index_key = $this->get_index_primary_key_string($row);
1678
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1679
+				}
1680
+			}
1681
+			if (! $model_objs_affected_ids) {
1682
+				// wait wait wait- if nothing was affected let's stop here
1683
+				return 0;
1684
+			}
1685
+			foreach ($model_objs_affected_ids as $id) {
1686
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1687
+				if ($model_obj_in_entity_map) {
1688
+					foreach ($fields_n_values as $field => $new_value) {
1689
+						$model_obj_in_entity_map->set($field, $new_value);
1690
+					}
1691
+				}
1692
+			}
1693
+			// if there is a primary key on this model, we can now do a slight optimization
1694
+			if ($this->has_primary_key_field()) {
1695
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1696
+				$query_params = array(
1697
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1698
+					'limit'                    => count($model_objs_affected_ids),
1699
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1700
+				);
1701
+			}
1702
+		}
1703
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1704
+		$SQL = "UPDATE "
1705
+			   . $model_query_info->get_full_join_sql()
1706
+			   . " SET "
1707
+			   . $this->_construct_update_sql($fields_n_values)
1708
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1709
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1710
+		/**
1711
+		 * Action called after a model update call has been made.
1712
+		 *
1713
+		 * @param EEM_Base $model
1714
+		 * @param array    $fields_n_values the updated fields and their new values
1715
+		 * @param array    $query_params    @see EEM_Base::get_all()
1716
+		 * @param int      $rows_affected
1717
+		 */
1718
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1719
+		return $rows_affected;// how many supposedly got updated
1720
+	}
1721
+
1722
+
1723
+
1724
+	/**
1725
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1726
+	 * are teh values of the field specified (or by default the primary key field)
1727
+	 * that matched the query params. Note that you should pass the name of the
1728
+	 * model FIELD, not the database table's column name.
1729
+	 *
1730
+	 * @param array  $query_params @see EEM_Base::get_all()
1731
+	 * @param string $field_to_select
1732
+	 * @return array just like $wpdb->get_col()
1733
+	 * @throws EE_Error
1734
+	 */
1735
+	public function get_col($query_params = array(), $field_to_select = null)
1736
+	{
1737
+		if ($field_to_select) {
1738
+			$field = $this->field_settings_for($field_to_select);
1739
+		} elseif ($this->has_primary_key_field()) {
1740
+			$field = $this->get_primary_key_field();
1741
+		} else {
1742
+			// no primary key, just grab the first column
1743
+			$field = reset($this->field_settings());
1744
+		}
1745
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1746
+		$select_expressions = $field->get_qualified_column();
1747
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1748
+		return $this->_do_wpdb_query('get_col', array($SQL));
1749
+	}
1750
+
1751
+
1752
+
1753
+	/**
1754
+	 * Returns a single column value for a single row from the database
1755
+	 *
1756
+	 * @param array  $query_params    @see EEM_Base::get_all()
1757
+	 * @param string $field_to_select @see EEM_Base::get_col()
1758
+	 * @return string
1759
+	 * @throws EE_Error
1760
+	 */
1761
+	public function get_var($query_params = array(), $field_to_select = null)
1762
+	{
1763
+		$query_params['limit'] = 1;
1764
+		$col = $this->get_col($query_params, $field_to_select);
1765
+		if (! empty($col)) {
1766
+			return reset($col);
1767
+		}
1768
+		return null;
1769
+	}
1770
+
1771
+
1772
+
1773
+	/**
1774
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1775
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1776
+	 * injection, but currently no further filtering is done
1777
+	 *
1778
+	 * @global      $wpdb
1779
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1780
+	 *                               be updated to in the DB
1781
+	 * @return string of SQL
1782
+	 * @throws EE_Error
1783
+	 */
1784
+	public function _construct_update_sql($fields_n_values)
1785
+	{
1786
+		/** @type WPDB $wpdb */
1787
+		global $wpdb;
1788
+		$cols_n_values = array();
1789
+		foreach ($fields_n_values as $field_name => $value) {
1790
+			$field_obj = $this->field_settings_for($field_name);
1791
+			// if the value is NULL, we want to assign the value to that.
1792
+			// wpdb->prepare doesn't really handle that properly
1793
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1794
+			$value_sql = $prepared_value === null ? 'NULL'
1795
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1796
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1797
+		}
1798
+		return implode(",", $cols_n_values);
1799
+	}
1800
+
1801
+
1802
+
1803
+	/**
1804
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1805
+	 * Performs a HARD delete, meaning the database row should always be removed,
1806
+	 * not just have a flag field on it switched
1807
+	 * Wrapper for EEM_Base::delete_permanently()
1808
+	 *
1809
+	 * @param mixed $id
1810
+	 * @param boolean $allow_blocking
1811
+	 * @return int the number of rows deleted
1812
+	 * @throws EE_Error
1813
+	 */
1814
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1815
+	{
1816
+		return $this->delete_permanently(
1817
+			array(
1818
+				array($this->get_primary_key_field()->get_name() => $id),
1819
+				'limit' => 1,
1820
+			),
1821
+			$allow_blocking
1822
+		);
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
+	 * Wrapper for EEM_Base::delete()
1830
+	 *
1831
+	 * @param mixed $id
1832
+	 * @param boolean $allow_blocking
1833
+	 * @return int the number of rows deleted
1834
+	 * @throws EE_Error
1835
+	 */
1836
+	public function delete_by_ID($id, $allow_blocking = true)
1837
+	{
1838
+		return $this->delete(
1839
+			array(
1840
+				array($this->get_primary_key_field()->get_name() => $id),
1841
+				'limit' => 1,
1842
+			),
1843
+			$allow_blocking
1844
+		);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1851
+	 * meaning if the model has a field that indicates its been "trashed" or
1852
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1853
+	 *
1854
+	 * @see EEM_Base::delete_permanently
1855
+	 * @param array   $query_params
1856
+	 * @param boolean $allow_blocking
1857
+	 * @return int how many rows got deleted
1858
+	 * @throws EE_Error
1859
+	 */
1860
+	public function delete($query_params, $allow_blocking = true)
1861
+	{
1862
+		return $this->delete_permanently($query_params, $allow_blocking);
1863
+	}
1864
+
1865
+
1866
+
1867
+	/**
1868
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1869
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1870
+	 * as archived, not actually deleted
1871
+	 *
1872
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1873
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1874
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1875
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1876
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1877
+	 *                                DB
1878
+	 * @return int how many rows got deleted
1879
+	 * @throws EE_Error
1880
+	 */
1881
+	public function delete_permanently($query_params, $allow_blocking = true)
1882
+	{
1883
+		/**
1884
+		 * Action called just before performing a real deletion query. You can use the
1885
+		 * model and its $query_params to find exactly which items will be deleted
1886
+		 *
1887
+		 * @param EEM_Base $model
1888
+		 * @param array    $query_params   @see EEM_Base::get_all()
1889
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1890
+		 *                                 to block (prevent) this deletion
1891
+		 */
1892
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1893
+		// some MySQL databases may be running safe mode, which may restrict
1894
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1895
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1896
+		// to delete them
1897
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1898
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1899
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1900
+			$columns_and_ids_for_deleting
1901
+		);
1902
+		/**
1903
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1904
+		 *
1905
+		 * @param EEM_Base $this  The model instance being acted on.
1906
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1907
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1908
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1909
+		 *                                                  derived from the incoming query parameters.
1910
+		 *                                                  @see details on the structure of this array in the phpdocs
1911
+		 *                                                  for the `_get_ids_for_delete_method`
1912
+		 *
1913
+		 */
1914
+		do_action(
1915
+			'AHEE__EEM_Base__delete__before_query',
1916
+			$this,
1917
+			$query_params,
1918
+			$allow_blocking,
1919
+			$columns_and_ids_for_deleting
1920
+		);
1921
+		if ($deletion_where_query_part) {
1922
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1923
+			$table_aliases = array_keys($this->_tables);
1924
+			$SQL = "DELETE "
1925
+				   . implode(", ", $table_aliases)
1926
+				   . " FROM "
1927
+				   . $model_query_info->get_full_join_sql()
1928
+				   . " WHERE "
1929
+				   . $deletion_where_query_part;
1930
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1931
+		} else {
1932
+			$rows_deleted = 0;
1933
+		}
1934
+
1935
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1936
+		// there was no error with the delete query.
1937
+		if ($this->has_primary_key_field()
1938
+			&& $rows_deleted !== false
1939
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1940
+		) {
1941
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1942
+			foreach ($ids_for_removal as $id) {
1943
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1944
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1945
+				}
1946
+			}
1947
+
1948
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1949
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1950
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1951
+			// (although it is possible).
1952
+			// Note this can be skipped by using the provided filter and returning false.
1953
+			if (apply_filters(
1954
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1955
+				! $this instanceof EEM_Extra_Meta,
1956
+				$this
1957
+			)) {
1958
+				EEM_Extra_Meta::instance()->delete_permanently(array(
1959
+					0 => array(
1960
+						'EXM_type' => $this->get_this_model_name(),
1961
+						'OBJ_ID'   => array(
1962
+							'IN',
1963
+							$ids_for_removal
1964
+						)
1965
+					)
1966
+				));
1967
+			}
1968
+		}
1969
+
1970
+		/**
1971
+		 * Action called just after performing a real deletion query. Although at this point the
1972
+		 * items should have been deleted
1973
+		 *
1974
+		 * @param EEM_Base $model
1975
+		 * @param array    $query_params @see EEM_Base::get_all()
1976
+		 * @param int      $rows_deleted
1977
+		 */
1978
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1979
+		return $rows_deleted;// how many supposedly got deleted
1980
+	}
1981
+
1982
+
1983
+
1984
+	/**
1985
+	 * Checks all the relations that throw error messages when there are blocking related objects
1986
+	 * for related model objects. If there are any related model objects on those relations,
1987
+	 * adds an EE_Error, and return true
1988
+	 *
1989
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1990
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1991
+	 *                                                 should be ignored when determining whether there are related
1992
+	 *                                                 model objects which block this model object's deletion. Useful
1993
+	 *                                                 if you know A is related to B and are considering deleting A,
1994
+	 *                                                 but want to see if A has any other objects blocking its deletion
1995
+	 *                                                 before removing the relation between A and B
1996
+	 * @return boolean
1997
+	 * @throws EE_Error
1998
+	 */
1999
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2000
+	{
2001
+		// first, if $ignore_this_model_obj was supplied, get its model
2002
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2003
+			$ignored_model = $ignore_this_model_obj->get_model();
2004
+		} else {
2005
+			$ignored_model = null;
2006
+		}
2007
+		// now check all the relations of $this_model_obj_or_id and see if there
2008
+		// are any related model objects blocking it?
2009
+		$is_blocked = false;
2010
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2011
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2012
+				// if $ignore_this_model_obj was supplied, then for the query
2013
+				// on that model needs to be told to ignore $ignore_this_model_obj
2014
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2015
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2016
+						array(
2017
+							$ignored_model->get_primary_key_field()->get_name() => array(
2018
+								'!=',
2019
+								$ignore_this_model_obj->ID(),
2020
+							),
2021
+						),
2022
+					));
2023
+				} else {
2024
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2025
+				}
2026
+				if ($related_model_objects) {
2027
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2028
+					$is_blocked = true;
2029
+				}
2030
+			}
2031
+		}
2032
+		return $is_blocked;
2033
+	}
2034
+
2035
+
2036
+	/**
2037
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2038
+	 * @param array $row_results_for_deleting
2039
+	 * @param bool  $allow_blocking
2040
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2041
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2042
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2043
+	 *                 deleted. Example:
2044
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2045
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2046
+	 *                 where each element is a group of columns and values that get deleted. Example:
2047
+	 *                      array(
2048
+	 *                          0 => array(
2049
+	 *                              'Term_Relationship.object_id' => 1
2050
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2051
+	 *                          ),
2052
+	 *                          1 => array(
2053
+	 *                              'Term_Relationship.object_id' => 1
2054
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2055
+	 *                          )
2056
+	 *                      )
2057
+	 * @throws EE_Error
2058
+	 */
2059
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2060
+	{
2061
+		$ids_to_delete_indexed_by_column = array();
2062
+		if ($this->has_primary_key_field()) {
2063
+			$primary_table = $this->_get_main_table();
2064
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2065
+			$other_tables = $this->_get_other_tables();
2066
+			$ids_to_delete_indexed_by_column = $query = array();
2067
+			foreach ($row_results_for_deleting as $item_to_delete) {
2068
+				// before we mark this item for deletion,
2069
+				// make sure there's no related entities blocking its deletion (if we're checking)
2070
+				if ($allow_blocking
2071
+					&& $this->delete_is_blocked_by_related_models(
2072
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2073
+					)
2074
+				) {
2075
+					continue;
2076
+				}
2077
+				// primary table deletes
2078
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2079
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2080
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2081
+				}
2082
+			}
2083
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2084
+			$fields = $this->get_combined_primary_key_fields();
2085
+			foreach ($row_results_for_deleting as $item_to_delete) {
2086
+				$ids_to_delete_indexed_by_column_for_row = array();
2087
+				foreach ($fields as $cpk_field) {
2088
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2089
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2090
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2091
+					}
2092
+				}
2093
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2094
+			}
2095
+		} else {
2096
+			// so there's no primary key and no combined key...
2097
+			// sorry, can't help you
2098
+			throw new EE_Error(
2099
+				sprintf(
2100
+					__(
2101
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2102
+						"event_espresso"
2103
+					),
2104
+					get_class($this)
2105
+				)
2106
+			);
2107
+		}
2108
+		return $ids_to_delete_indexed_by_column;
2109
+	}
2110
+
2111
+
2112
+	/**
2113
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2114
+	 * the corresponding query_part for the query performing the delete.
2115
+	 *
2116
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2117
+	 * @return string
2118
+	 * @throws EE_Error
2119
+	 */
2120
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2121
+	{
2122
+		$query_part = '';
2123
+		if (empty($ids_to_delete_indexed_by_column)) {
2124
+			return $query_part;
2125
+		} elseif ($this->has_primary_key_field()) {
2126
+			$query = array();
2127
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2128
+				// make sure we have unique $ids
2129
+				$ids = array_unique($ids);
2130
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2131
+			}
2132
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2133
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2134
+			$ways_to_identify_a_row = array();
2135
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2136
+				$values_for_each_combined_primary_key_for_a_row = array();
2137
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2138
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2139
+				}
2140
+				$ways_to_identify_a_row[] = '('
2141
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2142
+											. ')';
2143
+			}
2144
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2145
+		}
2146
+		return $query_part;
2147
+	}
2148
+
2149
+
2150
+
2151
+	/**
2152
+	 * Gets the model field by the fully qualified name
2153
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2154
+	 * @return EE_Model_Field_Base
2155
+	 */
2156
+	public function get_field_by_column($qualified_column_name)
2157
+	{
2158
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2159
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2160
+				return $field_obj;
2161
+			}
2162
+		}
2163
+		throw new EE_Error(
2164
+			sprintf(
2165
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2166
+				$this->get_this_model_name(),
2167
+				$qualified_column_name
2168
+			)
2169
+		);
2170
+	}
2171
+
2172
+
2173
+
2174
+	/**
2175
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2176
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2177
+	 * column
2178
+	 *
2179
+	 * @param array  $query_params   like EEM_Base::get_all's
2180
+	 * @param string $field_to_count field on model to count by (not column name)
2181
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2182
+	 *                               that by the setting $distinct to TRUE;
2183
+	 * @return int
2184
+	 * @throws EE_Error
2185
+	 */
2186
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2187
+	{
2188
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2189
+		if ($field_to_count) {
2190
+			$field_obj = $this->field_settings_for($field_to_count);
2191
+			$column_to_count = $field_obj->get_qualified_column();
2192
+		} elseif ($this->has_primary_key_field()) {
2193
+			$pk_field_obj = $this->get_primary_key_field();
2194
+			$column_to_count = $pk_field_obj->get_qualified_column();
2195
+		} else {
2196
+			// there's no primary key
2197
+			// if we're counting distinct items, and there's no primary key,
2198
+			// we need to list out the columns for distinction;
2199
+			// otherwise we can just use star
2200
+			if ($distinct) {
2201
+				$columns_to_use = array();
2202
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2203
+					$columns_to_use[] = $field_obj->get_qualified_column();
2204
+				}
2205
+				$column_to_count = implode(',', $columns_to_use);
2206
+			} else {
2207
+				$column_to_count = '*';
2208
+			}
2209
+		}
2210
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2211
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2212
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2213
+	}
2214
+
2215
+
2216
+
2217
+	/**
2218
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2219
+	 *
2220
+	 * @param array  $query_params like EEM_Base::get_all
2221
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2222
+	 * @return float
2223
+	 * @throws EE_Error
2224
+	 */
2225
+	public function sum($query_params, $field_to_sum = null)
2226
+	{
2227
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2228
+		if ($field_to_sum) {
2229
+			$field_obj = $this->field_settings_for($field_to_sum);
2230
+		} else {
2231
+			$field_obj = $this->get_primary_key_field();
2232
+		}
2233
+		$column_to_count = $field_obj->get_qualified_column();
2234
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2235
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2236
+		$data_type = $field_obj->get_wpdb_data_type();
2237
+		if ($data_type === '%d' || $data_type === '%s') {
2238
+			return (float) $return_value;
2239
+		}
2240
+		// must be %f
2241
+		return (float) $return_value;
2242
+	}
2243
+
2244
+
2245
+
2246
+	/**
2247
+	 * Just calls the specified method on $wpdb with the given arguments
2248
+	 * Consolidates a little extra error handling code
2249
+	 *
2250
+	 * @param string $wpdb_method
2251
+	 * @param array  $arguments_to_provide
2252
+	 * @throws EE_Error
2253
+	 * @global wpdb  $wpdb
2254
+	 * @return mixed
2255
+	 */
2256
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2257
+	{
2258
+		// if we're in maintenance mode level 2, DON'T run any queries
2259
+		// because level 2 indicates the database needs updating and
2260
+		// is probably out of sync with the code
2261
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2262
+			throw new EE_Error(sprintf(__(
2263
+				"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.",
2264
+				"event_espresso"
2265
+			)));
2266
+		}
2267
+		/** @type WPDB $wpdb */
2268
+		global $wpdb;
2269
+		if (! method_exists($wpdb, $wpdb_method)) {
2270
+			throw new EE_Error(sprintf(__(
2271
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2272
+				'event_espresso'
2273
+			), $wpdb_method));
2274
+		}
2275
+		if (WP_DEBUG) {
2276
+			$old_show_errors_value = $wpdb->show_errors;
2277
+			$wpdb->show_errors(false);
2278
+		}
2279
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2280
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2281
+		if (WP_DEBUG) {
2282
+			$wpdb->show_errors($old_show_errors_value);
2283
+			if (! empty($wpdb->last_error)) {
2284
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2285
+			}
2286
+			if ($result === false) {
2287
+				throw new EE_Error(sprintf(__(
2288
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2289
+					'event_espresso'
2290
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2291
+			}
2292
+		} elseif ($result === false) {
2293
+			EE_Error::add_error(
2294
+				sprintf(
2295
+					__(
2296
+						'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"',
2297
+						'event_espresso'
2298
+					),
2299
+					$wpdb_method,
2300
+					var_export($arguments_to_provide, true),
2301
+					$wpdb->last_error
2302
+				),
2303
+				__FILE__,
2304
+				__FUNCTION__,
2305
+				__LINE__
2306
+			);
2307
+		}
2308
+		return $result;
2309
+	}
2310
+
2311
+
2312
+
2313
+	/**
2314
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2315
+	 * and if there's an error tries to verify the DB is correct. Uses
2316
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2317
+	 * we should try to fix the EE core db, the addons, or just give up
2318
+	 *
2319
+	 * @param string $wpdb_method
2320
+	 * @param array  $arguments_to_provide
2321
+	 * @return mixed
2322
+	 */
2323
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2324
+	{
2325
+		/** @type WPDB $wpdb */
2326
+		global $wpdb;
2327
+		$wpdb->last_error = null;
2328
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2329
+		// was there an error running the query? but we don't care on new activations
2330
+		// (we're going to setup the DB anyway on new activations)
2331
+		if (($result === false || ! empty($wpdb->last_error))
2332
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2333
+		) {
2334
+			switch (EEM_Base::$_db_verification_level) {
2335
+				case EEM_Base::db_verified_none:
2336
+					// let's double-check core's DB
2337
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2338
+					break;
2339
+				case EEM_Base::db_verified_core:
2340
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2341
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2342
+					break;
2343
+				case EEM_Base::db_verified_addons:
2344
+					// ummmm... you in trouble
2345
+					return $result;
2346
+					break;
2347
+			}
2348
+			if (! empty($error_message)) {
2349
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2350
+				trigger_error($error_message);
2351
+			}
2352
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2353
+		}
2354
+		return $result;
2355
+	}
2356
+
2357
+
2358
+
2359
+	/**
2360
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2361
+	 * EEM_Base::$_db_verification_level
2362
+	 *
2363
+	 * @param string $wpdb_method
2364
+	 * @param array  $arguments_to_provide
2365
+	 * @return string
2366
+	 */
2367
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2368
+	{
2369
+		/** @type WPDB $wpdb */
2370
+		global $wpdb;
2371
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2372
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2373
+		$error_message = sprintf(
2374
+			__(
2375
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2376
+				'event_espresso'
2377
+			),
2378
+			$wpdb->last_error,
2379
+			$wpdb_method,
2380
+			wp_json_encode($arguments_to_provide)
2381
+		);
2382
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2383
+		return $error_message;
2384
+	}
2385
+
2386
+
2387
+
2388
+	/**
2389
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2390
+	 * EEM_Base::$_db_verification_level
2391
+	 *
2392
+	 * @param $wpdb_method
2393
+	 * @param $arguments_to_provide
2394
+	 * @return string
2395
+	 */
2396
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2397
+	{
2398
+		/** @type WPDB $wpdb */
2399
+		global $wpdb;
2400
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2401
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2402
+		$error_message = sprintf(
2403
+			__(
2404
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2405
+				'event_espresso'
2406
+			),
2407
+			$wpdb->last_error,
2408
+			$wpdb_method,
2409
+			wp_json_encode($arguments_to_provide)
2410
+		);
2411
+		EE_System::instance()->initialize_addons();
2412
+		return $error_message;
2413
+	}
2414
+
2415
+
2416
+
2417
+	/**
2418
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2419
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2420
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2421
+	 * ..."
2422
+	 *
2423
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2424
+	 * @return string
2425
+	 */
2426
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2427
+	{
2428
+		return " FROM " . $model_query_info->get_full_join_sql() .
2429
+			   $model_query_info->get_where_sql() .
2430
+			   $model_query_info->get_group_by_sql() .
2431
+			   $model_query_info->get_having_sql() .
2432
+			   $model_query_info->get_order_by_sql() .
2433
+			   $model_query_info->get_limit_sql();
2434
+	}
2435
+
2436
+
2437
+
2438
+	/**
2439
+	 * Set to easily debug the next X queries ran from this model.
2440
+	 *
2441
+	 * @param int $count
2442
+	 */
2443
+	public function show_next_x_db_queries($count = 1)
2444
+	{
2445
+		$this->_show_next_x_db_queries = $count;
2446
+	}
2447
+
2448
+
2449
+
2450
+	/**
2451
+	 * @param $sql_query
2452
+	 */
2453
+	public function show_db_query_if_previously_requested($sql_query)
2454
+	{
2455
+		if ($this->_show_next_x_db_queries > 0) {
2456
+			echo $sql_query;
2457
+			$this->_show_next_x_db_queries--;
2458
+		}
2459
+	}
2460
+
2461
+
2462
+
2463
+	/**
2464
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2465
+	 * There are the 3 cases:
2466
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2467
+	 * $otherModelObject has no ID, it is first saved.
2468
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2469
+	 * has no ID, it is first saved.
2470
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2471
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2472
+	 * join table
2473
+	 *
2474
+	 * @param        EE_Base_Class                     /int $thisModelObject
2475
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2476
+	 * @param string $relationName                     , key in EEM_Base::_relations
2477
+	 *                                                 an attendee to a group, you also want to specify which role they
2478
+	 *                                                 will have in that group. So you would use this parameter to
2479
+	 *                                                 specify array('role-column-name'=>'role-id')
2480
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2481
+	 *                                                 to for relation to methods that allow you to further specify
2482
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2483
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2484
+	 *                                                 because these will be inserted in any new rows created as well.
2485
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2486
+	 * @throws EE_Error
2487
+	 */
2488
+	public function add_relationship_to(
2489
+		$id_or_obj,
2490
+		$other_model_id_or_obj,
2491
+		$relationName,
2492
+		$extra_join_model_fields_n_values = array()
2493
+	) {
2494
+		$relation_obj = $this->related_settings_for($relationName);
2495
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2502
+	 * There are the 3 cases:
2503
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2504
+	 * error
2505
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2506
+	 * an error
2507
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2508
+	 *
2509
+	 * @param        EE_Base_Class /int $id_or_obj
2510
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2511
+	 * @param string $relationName key in EEM_Base::_relations
2512
+	 * @return boolean of success
2513
+	 * @throws EE_Error
2514
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2515
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2516
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2517
+	 *                             because these will be inserted in any new rows created as well.
2518
+	 */
2519
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2520
+	{
2521
+		$relation_obj = $this->related_settings_for($relationName);
2522
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2523
+	}
2524
+
2525
+
2526
+
2527
+	/**
2528
+	 * @param mixed           $id_or_obj
2529
+	 * @param string          $relationName
2530
+	 * @param array           $where_query_params
2531
+	 * @param EE_Base_Class[] objects to which relations were removed
2532
+	 * @return \EE_Base_Class[]
2533
+	 * @throws EE_Error
2534
+	 */
2535
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2536
+	{
2537
+		$relation_obj = $this->related_settings_for($relationName);
2538
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2539
+	}
2540
+
2541
+
2542
+
2543
+	/**
2544
+	 * Gets all the related items of the specified $model_name, using $query_params.
2545
+	 * Note: by default, we remove the "default query params"
2546
+	 * because we want to get even deleted items etc.
2547
+	 *
2548
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2549
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2550
+	 * @param array  $query_params like EEM_Base::get_all
2551
+	 * @return EE_Base_Class[]
2552
+	 * @throws EE_Error
2553
+	 */
2554
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2555
+	{
2556
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2557
+		$relation_settings = $this->related_settings_for($model_name);
2558
+		return $relation_settings->get_all_related($model_obj, $query_params);
2559
+	}
2560
+
2561
+
2562
+
2563
+	/**
2564
+	 * Deletes all the model objects across the relation indicated by $model_name
2565
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2566
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2567
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2568
+	 *
2569
+	 * @param EE_Base_Class|int|string $id_or_obj
2570
+	 * @param string                   $model_name
2571
+	 * @param array                    $query_params
2572
+	 * @return int how many deleted
2573
+	 * @throws EE_Error
2574
+	 */
2575
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2576
+	{
2577
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2578
+		$relation_settings = $this->related_settings_for($model_name);
2579
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2580
+	}
2581
+
2582
+
2583
+
2584
+	/**
2585
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2586
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2587
+	 * the model objects can't be hard deleted because of blocking related model objects,
2588
+	 * just does a soft-delete on them instead.
2589
+	 *
2590
+	 * @param EE_Base_Class|int|string $id_or_obj
2591
+	 * @param string                   $model_name
2592
+	 * @param array                    $query_params
2593
+	 * @return int how many deleted
2594
+	 * @throws EE_Error
2595
+	 */
2596
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2597
+	{
2598
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2599
+		$relation_settings = $this->related_settings_for($model_name);
2600
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2601
+	}
2602
+
2603
+
2604
+
2605
+	/**
2606
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2607
+	 * unless otherwise specified in the $query_params
2608
+	 *
2609
+	 * @param        int             /EE_Base_Class $id_or_obj
2610
+	 * @param string $model_name     like 'Event', or 'Registration'
2611
+	 * @param array  $query_params   like EEM_Base::get_all's
2612
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2613
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2614
+	 *                               that by the setting $distinct to TRUE;
2615
+	 * @return int
2616
+	 * @throws EE_Error
2617
+	 */
2618
+	public function count_related(
2619
+		$id_or_obj,
2620
+		$model_name,
2621
+		$query_params = array(),
2622
+		$field_to_count = null,
2623
+		$distinct = false
2624
+	) {
2625
+		$related_model = $this->get_related_model_obj($model_name);
2626
+		// we're just going to use the query params on the related model's normal get_all query,
2627
+		// except add a condition to say to match the current mod
2628
+		if (! isset($query_params['default_where_conditions'])) {
2629
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2630
+		}
2631
+		$this_model_name = $this->get_this_model_name();
2632
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2633
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2634
+		return $related_model->count($query_params, $field_to_count, $distinct);
2635
+	}
2636
+
2637
+
2638
+
2639
+	/**
2640
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2641
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2642
+	 *
2643
+	 * @param        int           /EE_Base_Class $id_or_obj
2644
+	 * @param string $model_name   like 'Event', or 'Registration'
2645
+	 * @param array  $query_params like EEM_Base::get_all's
2646
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2647
+	 * @return float
2648
+	 * @throws EE_Error
2649
+	 */
2650
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2651
+	{
2652
+		$related_model = $this->get_related_model_obj($model_name);
2653
+		if (! is_array($query_params)) {
2654
+			EE_Error::doing_it_wrong(
2655
+				'EEM_Base::sum_related',
2656
+				sprintf(
2657
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2658
+					gettype($query_params)
2659
+				),
2660
+				'4.6.0'
2661
+			);
2662
+			$query_params = array();
2663
+		}
2664
+		// we're just going to use the query params on the related model's normal get_all query,
2665
+		// except add a condition to say to match the current mod
2666
+		if (! isset($query_params['default_where_conditions'])) {
2667
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2668
+		}
2669
+		$this_model_name = $this->get_this_model_name();
2670
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2671
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2672
+		return $related_model->sum($query_params, $field_to_sum);
2673
+	}
2674
+
2675
+
2676
+
2677
+	/**
2678
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2679
+	 * $modelObject
2680
+	 *
2681
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2682
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2683
+	 * @param array               $query_params     like EEM_Base::get_all's
2684
+	 * @return EE_Base_Class
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2688
+	{
2689
+		$query_params['limit'] = 1;
2690
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2691
+		if ($results) {
2692
+			return array_shift($results);
2693
+		}
2694
+		return null;
2695
+	}
2696
+
2697
+
2698
+
2699
+	/**
2700
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2701
+	 *
2702
+	 * @return string
2703
+	 */
2704
+	public function get_this_model_name()
2705
+	{
2706
+		return str_replace("EEM_", "", get_class($this));
2707
+	}
2708
+
2709
+
2710
+
2711
+	/**
2712
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2713
+	 *
2714
+	 * @return EE_Any_Foreign_Model_Name_Field
2715
+	 * @throws EE_Error
2716
+	 */
2717
+	public function get_field_containing_related_model_name()
2718
+	{
2719
+		foreach ($this->field_settings(true) as $field) {
2720
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2721
+				$field_with_model_name = $field;
2722
+			}
2723
+		}
2724
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2725
+			throw new EE_Error(sprintf(
2726
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2727
+				$this->get_this_model_name()
2728
+			));
2729
+		}
2730
+		return $field_with_model_name;
2731
+	}
2732
+
2733
+
2734
+
2735
+	/**
2736
+	 * Inserts a new entry into the database, for each table.
2737
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2738
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2739
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2740
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2741
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2742
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2743
+	 *
2744
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2745
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2746
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2747
+	 *                              of EEM_Base)
2748
+	 * @return int new primary key on main table that got inserted
2749
+	 * @throws EE_Error
2750
+	 */
2751
+	public function insert($field_n_values)
2752
+	{
2753
+		/**
2754
+		 * Filters the fields and their values before inserting an item using the models
2755
+		 *
2756
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2757
+		 * @param EEM_Base $model           the model used
2758
+		 */
2759
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2760
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2761
+			$main_table = $this->_get_main_table();
2762
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2763
+			if ($new_id !== false) {
2764
+				foreach ($this->_get_other_tables() as $other_table) {
2765
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2766
+				}
2767
+			}
2768
+			/**
2769
+			 * Done just after attempting to insert a new model object
2770
+			 *
2771
+			 * @param EEM_Base   $model           used
2772
+			 * @param array      $fields_n_values fields and their values
2773
+			 * @param int|string the              ID of the newly-inserted model object
2774
+			 */
2775
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2776
+			return $new_id;
2777
+		}
2778
+		return false;
2779
+	}
2780
+
2781
+
2782
+
2783
+	/**
2784
+	 * Checks that the result would satisfy the unique indexes on this model
2785
+	 *
2786
+	 * @param array  $field_n_values
2787
+	 * @param string $action
2788
+	 * @return boolean
2789
+	 * @throws EE_Error
2790
+	 */
2791
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2792
+	{
2793
+		foreach ($this->unique_indexes() as $index_name => $index) {
2794
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2795
+			if ($this->exists(array($uniqueness_where_params))) {
2796
+				EE_Error::add_error(
2797
+					sprintf(
2798
+						__(
2799
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2800
+							"event_espresso"
2801
+						),
2802
+						$action,
2803
+						$this->_get_class_name(),
2804
+						$index_name,
2805
+						implode(",", $index->field_names()),
2806
+						http_build_query($uniqueness_where_params)
2807
+					),
2808
+					__FILE__,
2809
+					__FUNCTION__,
2810
+					__LINE__
2811
+				);
2812
+				return false;
2813
+			}
2814
+		}
2815
+		return true;
2816
+	}
2817
+
2818
+
2819
+
2820
+	/**
2821
+	 * Checks the database for an item that conflicts (ie, if this item were
2822
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2823
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2824
+	 * can be either an EE_Base_Class or an array of fields n values
2825
+	 *
2826
+	 * @param EE_Base_Class|array $obj_or_fields_array
2827
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2828
+	 *                                                 when looking for conflicts
2829
+	 *                                                 (ie, if false, we ignore the model object's primary key
2830
+	 *                                                 when finding "conflicts". If true, it's also considered).
2831
+	 *                                                 Only works for INT primary key,
2832
+	 *                                                 STRING primary keys cannot be ignored
2833
+	 * @throws EE_Error
2834
+	 * @return EE_Base_Class|array
2835
+	 */
2836
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2837
+	{
2838
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2839
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2840
+		} elseif (is_array($obj_or_fields_array)) {
2841
+			$fields_n_values = $obj_or_fields_array;
2842
+		} else {
2843
+			throw new EE_Error(
2844
+				sprintf(
2845
+					__(
2846
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2847
+						"event_espresso"
2848
+					),
2849
+					get_class($this),
2850
+					$obj_or_fields_array
2851
+				)
2852
+			);
2853
+		}
2854
+		$query_params = array();
2855
+		if ($this->has_primary_key_field()
2856
+			&& ($include_primary_key
2857
+				|| $this->get_primary_key_field()
2858
+				   instanceof
2859
+				   EE_Primary_Key_String_Field)
2860
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2861
+		) {
2862
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2863
+		}
2864
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2865
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2866
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2867
+		}
2868
+		// if there is nothing to base this search on, then we shouldn't find anything
2869
+		if (empty($query_params)) {
2870
+			return array();
2871
+		}
2872
+		return $this->get_one($query_params);
2873
+	}
2874
+
2875
+
2876
+
2877
+	/**
2878
+	 * Like count, but is optimized and returns a boolean instead of an int
2879
+	 *
2880
+	 * @param array $query_params
2881
+	 * @return boolean
2882
+	 * @throws EE_Error
2883
+	 */
2884
+	public function exists($query_params)
2885
+	{
2886
+		$query_params['limit'] = 1;
2887
+		return $this->count($query_params) > 0;
2888
+	}
2889
+
2890
+
2891
+
2892
+	/**
2893
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2894
+	 *
2895
+	 * @param int|string $id
2896
+	 * @return boolean
2897
+	 * @throws EE_Error
2898
+	 */
2899
+	public function exists_by_ID($id)
2900
+	{
2901
+		return $this->exists(
2902
+			array(
2903
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2904
+				array(
2905
+					$this->primary_key_name() => $id,
2906
+				),
2907
+			)
2908
+		);
2909
+	}
2910
+
2911
+
2912
+
2913
+	/**
2914
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2915
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2916
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2917
+	 * on the main table)
2918
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2919
+	 * cases where we want to call it directly rather than via insert().
2920
+	 *
2921
+	 * @access   protected
2922
+	 * @param EE_Table_Base $table
2923
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2924
+	 *                                       float
2925
+	 * @param int           $new_id          for now we assume only int keys
2926
+	 * @throws EE_Error
2927
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2928
+	 * @return int ID of new row inserted, or FALSE on failure
2929
+	 */
2930
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2931
+	{
2932
+		global $wpdb;
2933
+		$insertion_col_n_values = array();
2934
+		$format_for_insertion = array();
2935
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2936
+		foreach ($fields_on_table as $field_name => $field_obj) {
2937
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2938
+			if ($field_obj->is_auto_increment()) {
2939
+				continue;
2940
+			}
2941
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2942
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2943
+			if ($prepared_value !== null) {
2944
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2945
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2946
+			}
2947
+		}
2948
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2949
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2950
+			// so add the fk to the main table as a column
2951
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2952
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2953
+		}
2954
+		// insert the new entry
2955
+		$result = $this->_do_wpdb_query(
2956
+			'insert',
2957
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
2958
+		);
2959
+		if ($result === false) {
2960
+			return false;
2961
+		}
2962
+		// ok, now what do we return for the ID of the newly-inserted thing?
2963
+		if ($this->has_primary_key_field()) {
2964
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2965
+				return $wpdb->insert_id;
2966
+			}
2967
+			// it's not an auto-increment primary key, so
2968
+			// it must have been supplied
2969
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
2970
+		}
2971
+		// we can't return a  primary key because there is none. instead return
2972
+		// a unique string indicating this model
2973
+		return $this->get_index_primary_key_string($fields_n_values);
2974
+	}
2975
+
2976
+
2977
+
2978
+	/**
2979
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2980
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2981
+	 * and there is no default, we pass it along. WPDB will take care of it)
2982
+	 *
2983
+	 * @param EE_Model_Field_Base $field_obj
2984
+	 * @param array               $fields_n_values
2985
+	 * @return mixed string|int|float depending on what the table column will be expecting
2986
+	 * @throws EE_Error
2987
+	 */
2988
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2989
+	{
2990
+		// if this field doesn't allow nullable, don't allow it
2991
+		if (! $field_obj->is_nullable()
2992
+			&& (
2993
+				! isset($fields_n_values[ $field_obj->get_name() ])
2994
+				|| $fields_n_values[ $field_obj->get_name() ] === null
2995
+			)
2996
+		) {
2997
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2998
+		}
2999
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3000
+			? $fields_n_values[ $field_obj->get_name() ]
3001
+			: null;
3002
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3003
+	}
3004
+
3005
+
3006
+
3007
+	/**
3008
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3009
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3010
+	 * the field's prepare_for_set() method.
3011
+	 *
3012
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3013
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3014
+	 *                                   top of file)
3015
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3016
+	 *                                   $value is a custom selection
3017
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3018
+	 */
3019
+	private function _prepare_value_for_use_in_db($value, $field)
3020
+	{
3021
+		if ($field && $field instanceof EE_Model_Field_Base) {
3022
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3023
+			switch ($this->_values_already_prepared_by_model_object) {
3024
+				/** @noinspection PhpMissingBreakStatementInspection */
3025
+				case self::not_prepared_by_model_object:
3026
+					$value = $field->prepare_for_set($value);
3027
+				// purposefully left out "return"
3028
+				case self::prepared_by_model_object:
3029
+					/** @noinspection SuspiciousAssignmentsInspection */
3030
+					$value = $field->prepare_for_use_in_db($value);
3031
+				case self::prepared_for_use_in_db:
3032
+					// leave the value alone
3033
+			}
3034
+			return $value;
3035
+			// phpcs:enable
3036
+		}
3037
+		return $value;
3038
+	}
3039
+
3040
+
3041
+
3042
+	/**
3043
+	 * Returns the main table on this model
3044
+	 *
3045
+	 * @return EE_Primary_Table
3046
+	 * @throws EE_Error
3047
+	 */
3048
+	protected function _get_main_table()
3049
+	{
3050
+		foreach ($this->_tables as $table) {
3051
+			if ($table instanceof EE_Primary_Table) {
3052
+				return $table;
3053
+			}
3054
+		}
3055
+		throw new EE_Error(sprintf(__(
3056
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3057
+			'event_espresso'
3058
+		), get_class($this)));
3059
+	}
3060
+
3061
+
3062
+
3063
+	/**
3064
+	 * table
3065
+	 * returns EE_Primary_Table table name
3066
+	 *
3067
+	 * @return string
3068
+	 * @throws EE_Error
3069
+	 */
3070
+	public function table()
3071
+	{
3072
+		return $this->_get_main_table()->get_table_name();
3073
+	}
3074
+
3075
+
3076
+
3077
+	/**
3078
+	 * table
3079
+	 * returns first EE_Secondary_Table table name
3080
+	 *
3081
+	 * @return string
3082
+	 */
3083
+	public function second_table()
3084
+	{
3085
+		// grab second table from tables array
3086
+		$second_table = end($this->_tables);
3087
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3088
+	}
3089
+
3090
+
3091
+
3092
+	/**
3093
+	 * get_table_obj_by_alias
3094
+	 * returns table name given it's alias
3095
+	 *
3096
+	 * @param string $table_alias
3097
+	 * @return EE_Primary_Table | EE_Secondary_Table
3098
+	 */
3099
+	public function get_table_obj_by_alias($table_alias = '')
3100
+	{
3101
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3102
+	}
3103
+
3104
+
3105
+
3106
+	/**
3107
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3108
+	 *
3109
+	 * @return EE_Secondary_Table[]
3110
+	 */
3111
+	protected function _get_other_tables()
3112
+	{
3113
+		$other_tables = array();
3114
+		foreach ($this->_tables as $table_alias => $table) {
3115
+			if ($table instanceof EE_Secondary_Table) {
3116
+				$other_tables[ $table_alias ] = $table;
3117
+			}
3118
+		}
3119
+		return $other_tables;
3120
+	}
3121
+
3122
+
3123
+
3124
+	/**
3125
+	 * Finds all the fields that correspond to the given table
3126
+	 *
3127
+	 * @param string $table_alias , array key in EEM_Base::_tables
3128
+	 * @return EE_Model_Field_Base[]
3129
+	 */
3130
+	public function _get_fields_for_table($table_alias)
3131
+	{
3132
+		return $this->_fields[ $table_alias ];
3133
+	}
3134
+
3135
+
3136
+
3137
+	/**
3138
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3139
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3140
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3141
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3142
+	 * related Registration, Transaction, and Payment models.
3143
+	 *
3144
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3145
+	 * @return EE_Model_Query_Info_Carrier
3146
+	 * @throws EE_Error
3147
+	 */
3148
+	public function _extract_related_models_from_query($query_params)
3149
+	{
3150
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3151
+		if (array_key_exists(0, $query_params)) {
3152
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3153
+		}
3154
+		if (array_key_exists('group_by', $query_params)) {
3155
+			if (is_array($query_params['group_by'])) {
3156
+				$this->_extract_related_models_from_sub_params_array_values(
3157
+					$query_params['group_by'],
3158
+					$query_info_carrier,
3159
+					'group_by'
3160
+				);
3161
+			} elseif (! empty($query_params['group_by'])) {
3162
+				$this->_extract_related_model_info_from_query_param(
3163
+					$query_params['group_by'],
3164
+					$query_info_carrier,
3165
+					'group_by'
3166
+				);
3167
+			}
3168
+		}
3169
+		if (array_key_exists('having', $query_params)) {
3170
+			$this->_extract_related_models_from_sub_params_array_keys(
3171
+				$query_params[0],
3172
+				$query_info_carrier,
3173
+				'having'
3174
+			);
3175
+		}
3176
+		if (array_key_exists('order_by', $query_params)) {
3177
+			if (is_array($query_params['order_by'])) {
3178
+				$this->_extract_related_models_from_sub_params_array_keys(
3179
+					$query_params['order_by'],
3180
+					$query_info_carrier,
3181
+					'order_by'
3182
+				);
3183
+			} elseif (! empty($query_params['order_by'])) {
3184
+				$this->_extract_related_model_info_from_query_param(
3185
+					$query_params['order_by'],
3186
+					$query_info_carrier,
3187
+					'order_by'
3188
+				);
3189
+			}
3190
+		}
3191
+		if (array_key_exists('force_join', $query_params)) {
3192
+			$this->_extract_related_models_from_sub_params_array_values(
3193
+				$query_params['force_join'],
3194
+				$query_info_carrier,
3195
+				'force_join'
3196
+			);
3197
+		}
3198
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3199
+		return $query_info_carrier;
3200
+	}
3201
+
3202
+
3203
+
3204
+	/**
3205
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3206
+	 *
3207
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3208
+	 *                                                      $query_params['having']
3209
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3210
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3211
+	 * @throws EE_Error
3212
+	 * @return \EE_Model_Query_Info_Carrier
3213
+	 */
3214
+	private function _extract_related_models_from_sub_params_array_keys(
3215
+		$sub_query_params,
3216
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3217
+		$query_param_type
3218
+	) {
3219
+		if (! empty($sub_query_params)) {
3220
+			$sub_query_params = (array) $sub_query_params;
3221
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3222
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3223
+				$this->_extract_related_model_info_from_query_param(
3224
+					$param,
3225
+					$model_query_info_carrier,
3226
+					$query_param_type
3227
+				);
3228
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3229
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3230
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3231
+				// of array('Registration.TXN_ID'=>23)
3232
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3233
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3234
+					if (! is_array($possibly_array_of_params)) {
3235
+						throw new EE_Error(sprintf(
3236
+							__(
3237
+								"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'))",
3238
+								"event_espresso"
3239
+							),
3240
+							$param,
3241
+							$possibly_array_of_params
3242
+						));
3243
+					}
3244
+					$this->_extract_related_models_from_sub_params_array_keys(
3245
+						$possibly_array_of_params,
3246
+						$model_query_info_carrier,
3247
+						$query_param_type
3248
+					);
3249
+				} elseif ($query_param_type === 0 // ie WHERE
3250
+						  && is_array($possibly_array_of_params)
3251
+						  && isset($possibly_array_of_params[2])
3252
+						  && $possibly_array_of_params[2] == true
3253
+				) {
3254
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3255
+					// indicating that $possible_array_of_params[1] is actually a field name,
3256
+					// from which we should extract query parameters!
3257
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3258
+						throw new EE_Error(sprintf(__(
3259
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3260
+							"event_espresso"
3261
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3262
+					}
3263
+					$this->_extract_related_model_info_from_query_param(
3264
+						$possibly_array_of_params[1],
3265
+						$model_query_info_carrier,
3266
+						$query_param_type
3267
+					);
3268
+				}
3269
+			}
3270
+		}
3271
+		return $model_query_info_carrier;
3272
+	}
3273
+
3274
+
3275
+
3276
+	/**
3277
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3278
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3279
+	 *
3280
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3281
+	 *                                                      $query_params['having']
3282
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3283
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3284
+	 * @throws EE_Error
3285
+	 * @return \EE_Model_Query_Info_Carrier
3286
+	 */
3287
+	private function _extract_related_models_from_sub_params_array_values(
3288
+		$sub_query_params,
3289
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3290
+		$query_param_type
3291
+	) {
3292
+		if (! empty($sub_query_params)) {
3293
+			if (! is_array($sub_query_params)) {
3294
+				throw new EE_Error(sprintf(
3295
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3296
+					$sub_query_params
3297
+				));
3298
+			}
3299
+			foreach ($sub_query_params as $param) {
3300
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3301
+				$this->_extract_related_model_info_from_query_param(
3302
+					$param,
3303
+					$model_query_info_carrier,
3304
+					$query_param_type
3305
+				);
3306
+			}
3307
+		}
3308
+		return $model_query_info_carrier;
3309
+	}
3310
+
3311
+
3312
+
3313
+	/**
3314
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3315
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3316
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3317
+	 * but use them in a different order. Eg, we need to know what models we are querying
3318
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3319
+	 * other models before we can finalize the where clause SQL.
3320
+	 *
3321
+	 * @param array $query_params
3322
+	 * @throws EE_Error
3323
+	 * @return EE_Model_Query_Info_Carrier
3324
+	 */
3325
+	public function _create_model_query_info_carrier($query_params)
3326
+	{
3327
+		if (! is_array($query_params)) {
3328
+			EE_Error::doing_it_wrong(
3329
+				'EEM_Base::_create_model_query_info_carrier',
3330
+				sprintf(
3331
+					__(
3332
+						'$query_params should be an array, you passed a variable of type %s',
3333
+						'event_espresso'
3334
+					),
3335
+					gettype($query_params)
3336
+				),
3337
+				'4.6.0'
3338
+			);
3339
+			$query_params = array();
3340
+		}
3341
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3342
+		// first check if we should alter the query to account for caps or not
3343
+		// because the caps might require us to do extra joins
3344
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3345
+			$query_params[0] = $where_query_params = array_replace_recursive(
3346
+				$where_query_params,
3347
+				$this->caps_where_conditions(
3348
+					$query_params['caps']
3349
+				)
3350
+			);
3351
+		}
3352
+		$query_object = $this->_extract_related_models_from_query($query_params);
3353
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3354
+		foreach ($where_query_params as $key => $value) {
3355
+			if (is_int($key)) {
3356
+				throw new EE_Error(
3357
+					sprintf(
3358
+						__(
3359
+							"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.",
3360
+							"event_espresso"
3361
+						),
3362
+						$key,
3363
+						var_export($value, true),
3364
+						var_export($query_params, true),
3365
+						get_class($this)
3366
+					)
3367
+				);
3368
+			}
3369
+		}
3370
+		if (array_key_exists('default_where_conditions', $query_params)
3371
+			&& ! empty($query_params['default_where_conditions'])
3372
+		) {
3373
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3374
+		} else {
3375
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3376
+		}
3377
+		$where_query_params = array_merge(
3378
+			$this->_get_default_where_conditions_for_models_in_query(
3379
+				$query_object,
3380
+				$use_default_where_conditions,
3381
+				$where_query_params
3382
+			),
3383
+			$where_query_params
3384
+		);
3385
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3386
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3387
+		// So we need to setup a subquery and use that for the main join.
3388
+		// Note for now this only works on the primary table for the model.
3389
+		// So for instance, you could set the limit array like this:
3390
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3391
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3392
+			$query_object->set_main_model_join_sql(
3393
+				$this->_construct_limit_join_select(
3394
+					$query_params['on_join_limit'][0],
3395
+					$query_params['on_join_limit'][1]
3396
+				)
3397
+			);
3398
+		}
3399
+		// set limit
3400
+		if (array_key_exists('limit', $query_params)) {
3401
+			if (is_array($query_params['limit'])) {
3402
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3403
+					$e = sprintf(
3404
+						__(
3405
+							"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)",
3406
+							"event_espresso"
3407
+						),
3408
+						http_build_query($query_params['limit'])
3409
+					);
3410
+					throw new EE_Error($e . "|" . $e);
3411
+				}
3412
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3413
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3414
+			} elseif (! empty($query_params['limit'])) {
3415
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3416
+			}
3417
+		}
3418
+		// set order by
3419
+		if (array_key_exists('order_by', $query_params)) {
3420
+			if (is_array($query_params['order_by'])) {
3421
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3422
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3423
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3424
+				if (array_key_exists('order', $query_params)) {
3425
+					throw new EE_Error(
3426
+						sprintf(
3427
+							__(
3428
+								"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 ",
3429
+								"event_espresso"
3430
+							),
3431
+							get_class($this),
3432
+							implode(", ", array_keys($query_params['order_by'])),
3433
+							implode(", ", $query_params['order_by']),
3434
+							$query_params['order']
3435
+						)
3436
+					);
3437
+				}
3438
+				$this->_extract_related_models_from_sub_params_array_keys(
3439
+					$query_params['order_by'],
3440
+					$query_object,
3441
+					'order_by'
3442
+				);
3443
+				// assume it's an array of fields to order by
3444
+				$order_array = array();
3445
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3446
+					$order = $this->_extract_order($order);
3447
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3448
+				}
3449
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3450
+			} elseif (! empty($query_params['order_by'])) {
3451
+				$this->_extract_related_model_info_from_query_param(
3452
+					$query_params['order_by'],
3453
+					$query_object,
3454
+					'order',
3455
+					$query_params['order_by']
3456
+				);
3457
+				$order = isset($query_params['order'])
3458
+					? $this->_extract_order($query_params['order'])
3459
+					: 'DESC';
3460
+				$query_object->set_order_by_sql(
3461
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3462
+				);
3463
+			}
3464
+		}
3465
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3466
+		if (! array_key_exists('order_by', $query_params)
3467
+			&& array_key_exists('order', $query_params)
3468
+			&& ! empty($query_params['order'])
3469
+		) {
3470
+			$pk_field = $this->get_primary_key_field();
3471
+			$order = $this->_extract_order($query_params['order']);
3472
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3473
+		}
3474
+		// set group by
3475
+		if (array_key_exists('group_by', $query_params)) {
3476
+			if (is_array($query_params['group_by'])) {
3477
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3478
+				$group_by_array = array();
3479
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3480
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3481
+				}
3482
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3483
+			} elseif (! empty($query_params['group_by'])) {
3484
+				$query_object->set_group_by_sql(
3485
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3486
+				);
3487
+			}
3488
+		}
3489
+		// set having
3490
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3491
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3492
+		}
3493
+		// now, just verify they didn't pass anything wack
3494
+		foreach ($query_params as $query_key => $query_value) {
3495
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3496
+				throw new EE_Error(
3497
+					sprintf(
3498
+						__(
3499
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3500
+							'event_espresso'
3501
+						),
3502
+						$query_key,
3503
+						get_class($this),
3504
+						//                      print_r( $this->_allowed_query_params, TRUE )
3505
+						implode(',', $this->_allowed_query_params)
3506
+					)
3507
+				);
3508
+			}
3509
+		}
3510
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3511
+		if (empty($main_model_join_sql)) {
3512
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3513
+		}
3514
+		return $query_object;
3515
+	}
3516
+
3517
+
3518
+
3519
+	/**
3520
+	 * Gets the where conditions that should be imposed on the query based on the
3521
+	 * context (eg reading frontend, backend, edit or delete).
3522
+	 *
3523
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3524
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3525
+	 * @throws EE_Error
3526
+	 */
3527
+	public function caps_where_conditions($context = self::caps_read)
3528
+	{
3529
+		EEM_Base::verify_is_valid_cap_context($context);
3530
+		$cap_where_conditions = array();
3531
+		$cap_restrictions = $this->caps_missing($context);
3532
+		/**
3533
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3534
+		 */
3535
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3536
+			$cap_where_conditions = array_replace_recursive(
3537
+				$cap_where_conditions,
3538
+				$restriction_if_no_cap->get_default_where_conditions()
3539
+			);
3540
+		}
3541
+		return apply_filters(
3542
+			'FHEE__EEM_Base__caps_where_conditions__return',
3543
+			$cap_where_conditions,
3544
+			$this,
3545
+			$context,
3546
+			$cap_restrictions
3547
+		);
3548
+	}
3549
+
3550
+
3551
+
3552
+	/**
3553
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3554
+	 * otherwise throws an exception
3555
+	 *
3556
+	 * @param string $should_be_order_string
3557
+	 * @return string either ASC, asc, DESC or desc
3558
+	 * @throws EE_Error
3559
+	 */
3560
+	private function _extract_order($should_be_order_string)
3561
+	{
3562
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3563
+			return $should_be_order_string;
3564
+		}
3565
+		throw new EE_Error(
3566
+			sprintf(
3567
+				__(
3568
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3569
+					"event_espresso"
3570
+				),
3571
+				get_class($this),
3572
+				$should_be_order_string
3573
+			)
3574
+		);
3575
+	}
3576
+
3577
+
3578
+
3579
+	/**
3580
+	 * Looks at all the models which are included in this query, and asks each
3581
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3582
+	 * so they can be merged
3583
+	 *
3584
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3585
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3586
+	 *                                                                  'none' means NO default where conditions will
3587
+	 *                                                                  be used AT ALL during this query.
3588
+	 *                                                                  'other_models_only' means default where
3589
+	 *                                                                  conditions from other models will be used, but
3590
+	 *                                                                  not for this primary model. 'all', the default,
3591
+	 *                                                                  means default where conditions will apply as
3592
+	 *                                                                  normal
3593
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3594
+	 * @throws EE_Error
3595
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3596
+	 */
3597
+	private function _get_default_where_conditions_for_models_in_query(
3598
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3599
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3600
+		$where_query_params = array()
3601
+	) {
3602
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3603
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3604
+			throw new EE_Error(sprintf(
3605
+				__(
3606
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3607
+					"event_espresso"
3608
+				),
3609
+				$use_default_where_conditions,
3610
+				implode(", ", $allowed_used_default_where_conditions_values)
3611
+			));
3612
+		}
3613
+		$universal_query_params = array();
3614
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3615
+			$universal_query_params = $this->_get_default_where_conditions();
3616
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3617
+			$universal_query_params = $this->_get_minimum_where_conditions();
3618
+		}
3619
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3620
+			$related_model = $this->get_related_model_obj($model_name);
3621
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3622
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3623
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3624
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3625
+			} else {
3626
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3627
+				continue;
3628
+			}
3629
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3630
+				$related_model_universal_where_params,
3631
+				$where_query_params,
3632
+				$related_model,
3633
+				$model_relation_path
3634
+			);
3635
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3636
+				$universal_query_params,
3637
+				$overrides
3638
+			);
3639
+		}
3640
+		return $universal_query_params;
3641
+	}
3642
+
3643
+
3644
+
3645
+	/**
3646
+	 * Determines whether or not we should use default where conditions for the model in question
3647
+	 * (this model, or other related models).
3648
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3649
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3650
+	 * We should use default where conditions on related models when they requested to use default where conditions
3651
+	 * on all models, or specifically just on other related models
3652
+	 * @param      $default_where_conditions_value
3653
+	 * @param bool $for_this_model false means this is for OTHER related models
3654
+	 * @return bool
3655
+	 */
3656
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3657
+	{
3658
+		return (
3659
+				   $for_this_model
3660
+				   && in_array(
3661
+					   $default_where_conditions_value,
3662
+					   array(
3663
+						   EEM_Base::default_where_conditions_all,
3664
+						   EEM_Base::default_where_conditions_this_only,
3665
+						   EEM_Base::default_where_conditions_minimum_others,
3666
+					   ),
3667
+					   true
3668
+				   )
3669
+			   )
3670
+			   || (
3671
+				   ! $for_this_model
3672
+				   && in_array(
3673
+					   $default_where_conditions_value,
3674
+					   array(
3675
+						   EEM_Base::default_where_conditions_all,
3676
+						   EEM_Base::default_where_conditions_others_only,
3677
+					   ),
3678
+					   true
3679
+				   )
3680
+			   );
3681
+	}
3682
+
3683
+	/**
3684
+	 * Determines whether or not we should use default minimum conditions for the model in question
3685
+	 * (this model, or other related models).
3686
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3687
+	 * where conditions.
3688
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3689
+	 * on this model or others
3690
+	 * @param      $default_where_conditions_value
3691
+	 * @param bool $for_this_model false means this is for OTHER related models
3692
+	 * @return bool
3693
+	 */
3694
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3695
+	{
3696
+		return (
3697
+				   $for_this_model
3698
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3699
+			   )
3700
+			   || (
3701
+				   ! $for_this_model
3702
+				   && in_array(
3703
+					   $default_where_conditions_value,
3704
+					   array(
3705
+						   EEM_Base::default_where_conditions_minimum_others,
3706
+						   EEM_Base::default_where_conditions_minimum_all,
3707
+					   ),
3708
+					   true
3709
+				   )
3710
+			   );
3711
+	}
3712
+
3713
+
3714
+	/**
3715
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3716
+	 * then we also add a special where condition which allows for that model's primary key
3717
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3718
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3719
+	 *
3720
+	 * @param array    $default_where_conditions
3721
+	 * @param array    $provided_where_conditions
3722
+	 * @param EEM_Base $model
3723
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3724
+	 * @return array like EEM_Base::get_all's $query_params[0]
3725
+	 * @throws EE_Error
3726
+	 */
3727
+	private function _override_defaults_or_make_null_friendly(
3728
+		$default_where_conditions,
3729
+		$provided_where_conditions,
3730
+		$model,
3731
+		$model_relation_path
3732
+	) {
3733
+		$null_friendly_where_conditions = array();
3734
+		$none_overridden = true;
3735
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3736
+		foreach ($default_where_conditions as $key => $val) {
3737
+			if (isset($provided_where_conditions[ $key ])) {
3738
+				$none_overridden = false;
3739
+			} else {
3740
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3741
+			}
3742
+		}
3743
+		if ($none_overridden && $default_where_conditions) {
3744
+			if ($model->has_primary_key_field()) {
3745
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3746
+																				. "."
3747
+																				. $model->primary_key_name() ] = array('IS NULL');
3748
+			}/*else{
3749 3749
                 //@todo NO PK, use other defaults
3750 3750
             }*/
3751
-        }
3752
-        return $null_friendly_where_conditions;
3753
-    }
3754
-
3755
-
3756
-
3757
-    /**
3758
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3759
-     * default where conditions on all get_all, update, and delete queries done by this model.
3760
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3761
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3762
-     *
3763
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3764
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3765
-     */
3766
-    private function _get_default_where_conditions($model_relation_path = null)
3767
-    {
3768
-        if ($this->_ignore_where_strategy) {
3769
-            return array();
3770
-        }
3771
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3772
-    }
3773
-
3774
-
3775
-
3776
-    /**
3777
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3778
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3779
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3780
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3781
-     * Similar to _get_default_where_conditions
3782
-     *
3783
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3784
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3785
-     */
3786
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3787
-    {
3788
-        if ($this->_ignore_where_strategy) {
3789
-            return array();
3790
-        }
3791
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3792
-    }
3793
-
3794
-
3795
-
3796
-    /**
3797
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3798
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3799
-     *
3800
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3801
-     * @return string
3802
-     * @throws EE_Error
3803
-     */
3804
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3805
-    {
3806
-        $selects = $this->_get_columns_to_select_for_this_model();
3807
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3808
-            $name_of_other_model_included) {
3809
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3810
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3811
-            foreach ($other_model_selects as $key => $value) {
3812
-                $selects[] = $value;
3813
-            }
3814
-        }
3815
-        return implode(", ", $selects);
3816
-    }
3817
-
3818
-
3819
-
3820
-    /**
3821
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3822
-     * So that's going to be the columns for all the fields on the model
3823
-     *
3824
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3825
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3826
-     */
3827
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3828
-    {
3829
-        $fields = $this->field_settings();
3830
-        $selects = array();
3831
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3832
-            $model_relation_chain,
3833
-            $this->get_this_model_name()
3834
-        );
3835
-        foreach ($fields as $field_obj) {
3836
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3837
-                         . $field_obj->get_table_alias()
3838
-                         . "."
3839
-                         . $field_obj->get_table_column()
3840
-                         . " AS '"
3841
-                         . $table_alias_with_model_relation_chain_prefix
3842
-                         . $field_obj->get_table_alias()
3843
-                         . "."
3844
-                         . $field_obj->get_table_column()
3845
-                         . "'";
3846
-        }
3847
-        // make sure we are also getting the PKs of each table
3848
-        $tables = $this->get_tables();
3849
-        if (count($tables) > 1) {
3850
-            foreach ($tables as $table_obj) {
3851
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3852
-                                       . $table_obj->get_fully_qualified_pk_column();
3853
-                if (! in_array($qualified_pk_column, $selects)) {
3854
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3855
-                }
3856
-            }
3857
-        }
3858
-        return $selects;
3859
-    }
3860
-
3861
-
3862
-
3863
-    /**
3864
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3865
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3866
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3867
-     * SQL for joining, and the data types
3868
-     *
3869
-     * @param null|string                 $original_query_param
3870
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3871
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3872
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3873
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3874
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3875
-     *                                                          or 'Registration's
3876
-     * @param string                      $original_query_param what it originally was (eg
3877
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3878
-     *                                                          matches $query_param
3879
-     * @throws EE_Error
3880
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3881
-     */
3882
-    private function _extract_related_model_info_from_query_param(
3883
-        $query_param,
3884
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3885
-        $query_param_type,
3886
-        $original_query_param = null
3887
-    ) {
3888
-        if ($original_query_param === null) {
3889
-            $original_query_param = $query_param;
3890
-        }
3891
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3892
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3893
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3894
-        $allow_fields = in_array(
3895
-            $query_param_type,
3896
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3897
-            true
3898
-        );
3899
-        // check to see if we have a field on this model
3900
-        $this_model_fields = $this->field_settings(true);
3901
-        if (array_key_exists($query_param, $this_model_fields)) {
3902
-            if ($allow_fields) {
3903
-                return;
3904
-            }
3905
-            throw new EE_Error(
3906
-                sprintf(
3907
-                    __(
3908
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3909
-                        "event_espresso"
3910
-                    ),
3911
-                    $query_param,
3912
-                    get_class($this),
3913
-                    $query_param_type,
3914
-                    $original_query_param
3915
-                )
3916
-            );
3917
-        }
3918
-        // check if this is a special logic query param
3919
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3920
-            if ($allow_logic_query_params) {
3921
-                return;
3922
-            }
3923
-            throw new EE_Error(
3924
-                sprintf(
3925
-                    __(
3926
-                        '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',
3927
-                        'event_espresso'
3928
-                    ),
3929
-                    implode('", "', $this->_logic_query_param_keys),
3930
-                    $query_param,
3931
-                    get_class($this),
3932
-                    '<br />',
3933
-                    "\t"
3934
-                    . ' $passed_in_query_info = <pre>'
3935
-                    . print_r($passed_in_query_info, true)
3936
-                    . '</pre>'
3937
-                    . "\n\t"
3938
-                    . ' $query_param_type = '
3939
-                    . $query_param_type
3940
-                    . "\n\t"
3941
-                    . ' $original_query_param = '
3942
-                    . $original_query_param
3943
-                )
3944
-            );
3945
-        }
3946
-        // check if it's a custom selection
3947
-        if ($this->_custom_selections instanceof CustomSelects
3948
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3949
-        ) {
3950
-            return;
3951
-        }
3952
-        // check if has a model name at the beginning
3953
-        // and
3954
-        // check if it's a field on a related model
3955
-        if ($this->extractJoinModelFromQueryParams(
3956
-            $passed_in_query_info,
3957
-            $query_param,
3958
-            $original_query_param,
3959
-            $query_param_type
3960
-        )) {
3961
-            return;
3962
-        }
3963
-
3964
-        // ok so $query_param didn't start with a model name
3965
-        // and we previously confirmed it wasn't a logic query param or field on the current model
3966
-        // it's wack, that's what it is
3967
-        throw new EE_Error(
3968
-            sprintf(
3969
-                esc_html__(
3970
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3971
-                    "event_espresso"
3972
-                ),
3973
-                $query_param,
3974
-                get_class($this),
3975
-                $query_param_type,
3976
-                $original_query_param
3977
-            )
3978
-        );
3979
-    }
3980
-
3981
-
3982
-    /**
3983
-     * Extracts any possible join model information from the provided possible_join_string.
3984
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
3985
-     * parts that should be added to the query.
3986
-     *
3987
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3988
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
3989
-     * @param null|string                 $original_query_param
3990
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
3991
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
3992
-     * @return bool  returns true if a join was added and false if not.
3993
-     * @throws EE_Error
3994
-     */
3995
-    private function extractJoinModelFromQueryParams(
3996
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3997
-        $possible_join_string,
3998
-        $original_query_param,
3999
-        $query_parameter_type
4000
-    ) {
4001
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4002
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4003
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4004
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4005
-                if ($possible_join_string === '') {
4006
-                    // nothing left to $query_param
4007
-                    // we should actually end in a field name, not a model like this!
4008
-                    throw new EE_Error(
4009
-                        sprintf(
4010
-                            esc_html__(
4011
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4012
-                                "event_espresso"
4013
-                            ),
4014
-                            $possible_join_string,
4015
-                            $query_parameter_type,
4016
-                            get_class($this),
4017
-                            $valid_related_model_name
4018
-                        )
4019
-                    );
4020
-                }
4021
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4022
-                $related_model_obj->_extract_related_model_info_from_query_param(
4023
-                    $possible_join_string,
4024
-                    $query_info_carrier,
4025
-                    $query_parameter_type,
4026
-                    $original_query_param
4027
-                );
4028
-                return true;
4029
-            }
4030
-            if ($possible_join_string === $valid_related_model_name) {
4031
-                $this->_add_join_to_model(
4032
-                    $valid_related_model_name,
4033
-                    $query_info_carrier,
4034
-                    $original_query_param
4035
-                );
4036
-                return true;
4037
-            }
4038
-        }
4039
-        return false;
4040
-    }
4041
-
4042
-
4043
-    /**
4044
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4045
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4046
-     * @throws EE_Error
4047
-     */
4048
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4049
-    {
4050
-        if ($this->_custom_selections instanceof CustomSelects
4051
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4052
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4053
-            )
4054
-        ) {
4055
-            $original_selects = $this->_custom_selections->originalSelects();
4056
-            foreach ($original_selects as $alias => $select_configuration) {
4057
-                $this->extractJoinModelFromQueryParams(
4058
-                    $query_info_carrier,
4059
-                    $select_configuration[0],
4060
-                    $select_configuration[0],
4061
-                    'custom_selects'
4062
-                );
4063
-            }
4064
-        }
4065
-    }
4066
-
4067
-
4068
-
4069
-    /**
4070
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4071
-     * and store it on $passed_in_query_info
4072
-     *
4073
-     * @param string                      $model_name
4074
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4075
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4076
-     *                                                          model and $model_name. Eg, if we are querying Event,
4077
-     *                                                          and are adding a join to 'Payment' with the original
4078
-     *                                                          query param key
4079
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4080
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4081
-     *                                                          Payment wants to add default query params so that it
4082
-     *                                                          will know what models to prepend onto its default query
4083
-     *                                                          params or in case it wants to rename tables (in case
4084
-     *                                                          there are multiple joins to the same table)
4085
-     * @return void
4086
-     * @throws EE_Error
4087
-     */
4088
-    private function _add_join_to_model(
4089
-        $model_name,
4090
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4091
-        $original_query_param
4092
-    ) {
4093
-        $relation_obj = $this->related_settings_for($model_name);
4094
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4095
-        // check if the relation is HABTM, because then we're essentially doing two joins
4096
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4097
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4098
-            $join_model_obj = $relation_obj->get_join_model();
4099
-            // replace the model specified with the join model for this relation chain, whi
4100
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4101
-                $model_name,
4102
-                $join_model_obj->get_this_model_name(),
4103
-                $model_relation_chain
4104
-            );
4105
-            $passed_in_query_info->merge(
4106
-                new EE_Model_Query_Info_Carrier(
4107
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4108
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4109
-                )
4110
-            );
4111
-        }
4112
-        // now just join to the other table pointed to by the relation object, and add its data types
4113
-        $passed_in_query_info->merge(
4114
-            new EE_Model_Query_Info_Carrier(
4115
-                array($model_relation_chain => $model_name),
4116
-                $relation_obj->get_join_statement($model_relation_chain)
4117
-            )
4118
-        );
4119
-    }
4120
-
4121
-
4122
-
4123
-    /**
4124
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4125
-     *
4126
-     * @param array $where_params like EEM_Base::get_all
4127
-     * @return string of SQL
4128
-     * @throws EE_Error
4129
-     */
4130
-    private function _construct_where_clause($where_params)
4131
-    {
4132
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4133
-        if ($SQL) {
4134
-            return " WHERE " . $SQL;
4135
-        }
4136
-        return '';
4137
-    }
4138
-
4139
-
4140
-
4141
-    /**
4142
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4143
-     * and should be passed HAVING parameters, not WHERE parameters
4144
-     *
4145
-     * @param array $having_params
4146
-     * @return string
4147
-     * @throws EE_Error
4148
-     */
4149
-    private function _construct_having_clause($having_params)
4150
-    {
4151
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4152
-        if ($SQL) {
4153
-            return " HAVING " . $SQL;
4154
-        }
4155
-        return '';
4156
-    }
4157
-
4158
-
4159
-    /**
4160
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4161
-     * Event_Meta.meta_value = 'foo'))"
4162
-     *
4163
-     * @param array  $where_params see EEM_Base::get_all for documentation
4164
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4165
-     * @throws EE_Error
4166
-     * @return string of SQL
4167
-     */
4168
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4169
-    {
4170
-        $where_clauses = array();
4171
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4172
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4173
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4174
-                switch ($query_param) {
4175
-                    case 'not':
4176
-                    case 'NOT':
4177
-                        $where_clauses[] = "! ("
4178
-                                           . $this->_construct_condition_clause_recursive(
4179
-                                               $op_and_value_or_sub_condition,
4180
-                                               $glue
4181
-                                           )
4182
-                                           . ")";
4183
-                        break;
4184
-                    case 'and':
4185
-                    case 'AND':
4186
-                        $where_clauses[] = " ("
4187
-                                           . $this->_construct_condition_clause_recursive(
4188
-                                               $op_and_value_or_sub_condition,
4189
-                                               ' AND '
4190
-                                           )
4191
-                                           . ")";
4192
-                        break;
4193
-                    case 'or':
4194
-                    case 'OR':
4195
-                        $where_clauses[] = " ("
4196
-                                           . $this->_construct_condition_clause_recursive(
4197
-                                               $op_and_value_or_sub_condition,
4198
-                                               ' OR '
4199
-                                           )
4200
-                                           . ")";
4201
-                        break;
4202
-                }
4203
-            } else {
4204
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4205
-                // if it's not a normal field, maybe it's a custom selection?
4206
-                if (! $field_obj) {
4207
-                    if ($this->_custom_selections instanceof CustomSelects) {
4208
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4209
-                    } else {
4210
-                        throw new EE_Error(sprintf(__(
4211
-                            "%s is neither a valid model field name, nor a custom selection",
4212
-                            "event_espresso"
4213
-                        ), $query_param));
4214
-                    }
4215
-                }
4216
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4217
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4218
-            }
4219
-        }
4220
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4221
-    }
4222
-
4223
-
4224
-
4225
-    /**
4226
-     * Takes the input parameter and extract the table name (alias) and column name
4227
-     *
4228
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4229
-     * @throws EE_Error
4230
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4231
-     */
4232
-    private function _deduce_column_name_from_query_param($query_param)
4233
-    {
4234
-        $field = $this->_deduce_field_from_query_param($query_param);
4235
-        if ($field) {
4236
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4237
-                $field->get_model_name(),
4238
-                $query_param
4239
-            );
4240
-            return $table_alias_prefix . $field->get_qualified_column();
4241
-        }
4242
-        if ($this->_custom_selections instanceof CustomSelects
4243
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4244
-        ) {
4245
-            // maybe it's custom selection item?
4246
-            // if so, just use it as the "column name"
4247
-            return $query_param;
4248
-        }
4249
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4250
-            ? implode(',', $this->_custom_selections->columnAliases())
4251
-            : '';
4252
-        throw new EE_Error(
4253
-            sprintf(
4254
-                __(
4255
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4256
-                    "event_espresso"
4257
-                ),
4258
-                $query_param,
4259
-                $custom_select_aliases
4260
-            )
4261
-        );
4262
-    }
4263
-
4264
-
4265
-
4266
-    /**
4267
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4268
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4269
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4270
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4271
-     *
4272
-     * @param string $condition_query_param_key
4273
-     * @return string
4274
-     */
4275
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4276
-    {
4277
-        $pos_of_star = strpos($condition_query_param_key, '*');
4278
-        if ($pos_of_star === false) {
4279
-            return $condition_query_param_key;
4280
-        }
4281
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4282
-        return $condition_query_param_sans_star;
4283
-    }
4284
-
4285
-
4286
-
4287
-    /**
4288
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4289
-     *
4290
-     * @param                            mixed      array | string    $op_and_value
4291
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4292
-     * @throws EE_Error
4293
-     * @return string
4294
-     */
4295
-    private function _construct_op_and_value($op_and_value, $field_obj)
4296
-    {
4297
-        if (is_array($op_and_value)) {
4298
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4299
-            if (! $operator) {
4300
-                $php_array_like_string = array();
4301
-                foreach ($op_and_value as $key => $value) {
4302
-                    $php_array_like_string[] = "$key=>$value";
4303
-                }
4304
-                throw new EE_Error(
4305
-                    sprintf(
4306
-                        __(
4307
-                            "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))",
4308
-                            "event_espresso"
4309
-                        ),
4310
-                        implode(",", $php_array_like_string)
4311
-                    )
4312
-                );
4313
-            }
4314
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4315
-        } else {
4316
-            $operator = '=';
4317
-            $value = $op_and_value;
4318
-        }
4319
-        // check to see if the value is actually another field
4320
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4321
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4322
-        }
4323
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4324
-            // in this case, the value should be an array, or at least a comma-separated list
4325
-            // it will need to handle a little differently
4326
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4327
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4328
-            return $operator . SP . $cleaned_value;
4329
-        }
4330
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4331
-            // the value should be an array with count of two.
4332
-            if (count($value) !== 2) {
4333
-                throw new EE_Error(
4334
-                    sprintf(
4335
-                        __(
4336
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4337
-                            'event_espresso'
4338
-                        ),
4339
-                        "BETWEEN"
4340
-                    )
4341
-                );
4342
-            }
4343
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4344
-            return $operator . SP . $cleaned_value;
4345
-        }
4346
-        if (in_array($operator, $this->valid_null_style_operators())) {
4347
-            if ($value !== null) {
4348
-                throw new EE_Error(
4349
-                    sprintf(
4350
-                        __(
4351
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4352
-                            "event_espresso"
4353
-                        ),
4354
-                        $value,
4355
-                        $operator
4356
-                    )
4357
-                );
4358
-            }
4359
-            return $operator;
4360
-        }
4361
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4362
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4363
-            // remove other junk. So just treat it as a string.
4364
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4365
-        }
4366
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4367
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4368
-        }
4369
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4370
-            throw new EE_Error(
4371
-                sprintf(
4372
-                    __(
4373
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4374
-                        'event_espresso'
4375
-                    ),
4376
-                    $operator,
4377
-                    $operator
4378
-                )
4379
-            );
4380
-        }
4381
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4382
-            throw new EE_Error(
4383
-                sprintf(
4384
-                    __(
4385
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4386
-                        'event_espresso'
4387
-                    ),
4388
-                    $operator,
4389
-                    $operator
4390
-                )
4391
-            );
4392
-        }
4393
-        throw new EE_Error(
4394
-            sprintf(
4395
-                __(
4396
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4397
-                    "event_espresso"
4398
-                ),
4399
-                http_build_query($op_and_value)
4400
-            )
4401
-        );
4402
-    }
4403
-
4404
-
4405
-
4406
-    /**
4407
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4408
-     *
4409
-     * @param array                      $values
4410
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4411
-     *                                              '%s'
4412
-     * @return string
4413
-     * @throws EE_Error
4414
-     */
4415
-    public function _construct_between_value($values, $field_obj)
4416
-    {
4417
-        $cleaned_values = array();
4418
-        foreach ($values as $value) {
4419
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4420
-        }
4421
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4422
-    }
4423
-
4424
-
4425
-
4426
-    /**
4427
-     * Takes an array or a comma-separated list of $values and cleans them
4428
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4429
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4430
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4431
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4432
-     *
4433
-     * @param mixed                      $values    array or comma-separated string
4434
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4435
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4436
-     * @throws EE_Error
4437
-     */
4438
-    public function _construct_in_value($values, $field_obj)
4439
-    {
4440
-        // check if the value is a CSV list
4441
-        if (is_string($values)) {
4442
-            // in which case, turn it into an array
4443
-            $values = explode(",", $values);
4444
-        }
4445
-        $cleaned_values = array();
4446
-        foreach ($values as $value) {
4447
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4448
-        }
4449
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4450
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4451
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4452
-        if (empty($cleaned_values)) {
4453
-            $all_fields = $this->field_settings();
4454
-            $a_field = array_shift($all_fields);
4455
-            $main_table = $this->_get_main_table();
4456
-            $cleaned_values[] = "SELECT "
4457
-                                . $a_field->get_table_column()
4458
-                                . " FROM "
4459
-                                . $main_table->get_table_name()
4460
-                                . " WHERE FALSE";
4461
-        }
4462
-        return "(" . implode(",", $cleaned_values) . ")";
4463
-    }
4464
-
4465
-
4466
-
4467
-    /**
4468
-     * @param mixed                      $value
4469
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4470
-     * @throws EE_Error
4471
-     * @return false|null|string
4472
-     */
4473
-    private function _wpdb_prepare_using_field($value, $field_obj)
4474
-    {
4475
-        /** @type WPDB $wpdb */
4476
-        global $wpdb;
4477
-        if ($field_obj instanceof EE_Model_Field_Base) {
4478
-            return $wpdb->prepare(
4479
-                $field_obj->get_wpdb_data_type(),
4480
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4481
-            );
4482
-        } //$field_obj should really just be a data type
4483
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4484
-            throw new EE_Error(
4485
-                sprintf(
4486
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4487
-                    $field_obj,
4488
-                    implode(",", $this->_valid_wpdb_data_types)
4489
-                )
4490
-            );
4491
-        }
4492
-        return $wpdb->prepare($field_obj, $value);
4493
-    }
4494
-
4495
-
4496
-
4497
-    /**
4498
-     * Takes the input parameter and finds the model field that it indicates.
4499
-     *
4500
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4501
-     * @throws EE_Error
4502
-     * @return EE_Model_Field_Base
4503
-     */
4504
-    protected function _deduce_field_from_query_param($query_param_name)
4505
-    {
4506
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4507
-        // which will help us find the database table and column
4508
-        $query_param_parts = explode(".", $query_param_name);
4509
-        if (empty($query_param_parts)) {
4510
-            throw new EE_Error(sprintf(__(
4511
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4512
-                'event_espresso'
4513
-            ), $query_param_name));
4514
-        }
4515
-        $number_of_parts = count($query_param_parts);
4516
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4517
-        if ($number_of_parts === 1) {
4518
-            $field_name = $last_query_param_part;
4519
-            $model_obj = $this;
4520
-        } else {// $number_of_parts >= 2
4521
-            // the last part is the column name, and there are only 2parts. therefore...
4522
-            $field_name = $last_query_param_part;
4523
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4524
-        }
4525
-        try {
4526
-            return $model_obj->field_settings_for($field_name);
4527
-        } catch (EE_Error $e) {
4528
-            return null;
4529
-        }
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4536
-     * alias and column which corresponds to it
4537
-     *
4538
-     * @param string $field_name
4539
-     * @throws EE_Error
4540
-     * @return string
4541
-     */
4542
-    public function _get_qualified_column_for_field($field_name)
4543
-    {
4544
-        $all_fields = $this->field_settings();
4545
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4546
-        if ($field) {
4547
-            return $field->get_qualified_column();
4548
-        }
4549
-        throw new EE_Error(
4550
-            sprintf(
4551
-                __(
4552
-                    "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.",
4553
-                    'event_espresso'
4554
-                ),
4555
-                $field_name,
4556
-                get_class($this)
4557
-            )
4558
-        );
4559
-    }
4560
-
4561
-
4562
-
4563
-    /**
4564
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4565
-     * Example usage:
4566
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4567
-     *      array(),
4568
-     *      ARRAY_A,
4569
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4570
-     *  );
4571
-     * is equivalent to
4572
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4573
-     * and
4574
-     *  EEM_Event::instance()->get_all_wpdb_results(
4575
-     *      array(
4576
-     *          array(
4577
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4578
-     *          ),
4579
-     *          ARRAY_A,
4580
-     *          implode(
4581
-     *              ', ',
4582
-     *              array_merge(
4583
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4584
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4585
-     *              )
4586
-     *          )
4587
-     *      )
4588
-     *  );
4589
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4590
-     *
4591
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4592
-     *                                            and the one whose fields you are selecting for example: when querying
4593
-     *                                            tickets model and selecting fields from the tickets model you would
4594
-     *                                            leave this parameter empty, because no models are needed to join
4595
-     *                                            between the queried model and the selected one. Likewise when
4596
-     *                                            querying the datetime model and selecting fields from the tickets
4597
-     *                                            model, it would also be left empty, because there is a direct
4598
-     *                                            relation from datetimes to tickets, so no model is needed to join
4599
-     *                                            them together. However, when querying from the event model and
4600
-     *                                            selecting fields from the ticket model, you should provide the string
4601
-     *                                            'Datetime', indicating that the event model must first join to the
4602
-     *                                            datetime model in order to find its relation to ticket model.
4603
-     *                                            Also, when querying from the venue model and selecting fields from
4604
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4605
-     *                                            indicating you need to join the venue model to the event model,
4606
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4607
-     *                                            This string is used to deduce the prefix that gets added onto the
4608
-     *                                            models' tables qualified columns
4609
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4610
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4611
-     *                                            qualified column names
4612
-     * @return array|string
4613
-     */
4614
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4615
-    {
4616
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4617
-        $qualified_columns = array();
4618
-        foreach ($this->field_settings() as $field_name => $field) {
4619
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4620
-        }
4621
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4622
-    }
4623
-
4624
-
4625
-
4626
-    /**
4627
-     * constructs the select use on special limit joins
4628
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4629
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4630
-     * (as that is typically where the limits would be set).
4631
-     *
4632
-     * @param  string       $table_alias The table the select is being built for
4633
-     * @param  mixed|string $limit       The limit for this select
4634
-     * @return string                The final select join element for the query.
4635
-     */
4636
-    public function _construct_limit_join_select($table_alias, $limit)
4637
-    {
4638
-        $SQL = '';
4639
-        foreach ($this->_tables as $table_obj) {
4640
-            if ($table_obj instanceof EE_Primary_Table) {
4641
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4642
-                    ? $table_obj->get_select_join_limit($limit)
4643
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4644
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4645
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4646
-                    ? $table_obj->get_select_join_limit_join($limit)
4647
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4648
-            }
4649
-        }
4650
-        return $SQL;
4651
-    }
4652
-
4653
-
4654
-
4655
-    /**
4656
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4657
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4658
-     *
4659
-     * @return string SQL
4660
-     * @throws EE_Error
4661
-     */
4662
-    public function _construct_internal_join()
4663
-    {
4664
-        $SQL = $this->_get_main_table()->get_table_sql();
4665
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4666
-        return $SQL;
4667
-    }
4668
-
4669
-
4670
-
4671
-    /**
4672
-     * Constructs the SQL for joining all the tables on this model.
4673
-     * Normally $alias should be the primary table's alias, but in cases where
4674
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4675
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4676
-     * alias, this will construct SQL like:
4677
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4678
-     * With $alias being a secondary table's alias, this will construct SQL like:
4679
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4680
-     *
4681
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4682
-     * @return string
4683
-     */
4684
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4685
-    {
4686
-        $SQL = '';
4687
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4688
-        foreach ($this->_tables as $table_obj) {
4689
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4690
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4691
-                    // so we're joining to this table, meaning the table is already in
4692
-                    // the FROM statement, BUT the primary table isn't. So we want
4693
-                    // to add the inverse join sql
4694
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4695
-                } else {
4696
-                    // just add a regular JOIN to this table from the primary table
4697
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4698
-                }
4699
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4700
-        }
4701
-        return $SQL;
4702
-    }
4703
-
4704
-
4705
-
4706
-    /**
4707
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4708
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4709
-     * their data type (eg, '%s', '%d', etc)
4710
-     *
4711
-     * @return array
4712
-     */
4713
-    public function _get_data_types()
4714
-    {
4715
-        $data_types = array();
4716
-        foreach ($this->field_settings() as $field_obj) {
4717
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4718
-            /** @var $field_obj EE_Model_Field_Base */
4719
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4720
-        }
4721
-        return $data_types;
4722
-    }
4723
-
4724
-
4725
-
4726
-    /**
4727
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4728
-     *
4729
-     * @param string $model_name
4730
-     * @throws EE_Error
4731
-     * @return EEM_Base
4732
-     */
4733
-    public function get_related_model_obj($model_name)
4734
-    {
4735
-        $model_classname = "EEM_" . $model_name;
4736
-        if (! class_exists($model_classname)) {
4737
-            throw new EE_Error(sprintf(__(
4738
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4739
-                'event_espresso'
4740
-            ), $model_name, $model_classname));
4741
-        }
4742
-        return call_user_func($model_classname . "::instance");
4743
-    }
4744
-
4745
-
4746
-
4747
-    /**
4748
-     * Returns the array of EE_ModelRelations for this model.
4749
-     *
4750
-     * @return EE_Model_Relation_Base[]
4751
-     */
4752
-    public function relation_settings()
4753
-    {
4754
-        return $this->_model_relations;
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4761
-     * because without THOSE models, this model probably doesn't have much purpose.
4762
-     * (Eg, without an event, datetimes have little purpose.)
4763
-     *
4764
-     * @return EE_Belongs_To_Relation[]
4765
-     */
4766
-    public function belongs_to_relations()
4767
-    {
4768
-        $belongs_to_relations = array();
4769
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4770
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4771
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4772
-            }
4773
-        }
4774
-        return $belongs_to_relations;
4775
-    }
4776
-
4777
-
4778
-
4779
-    /**
4780
-     * Returns the specified EE_Model_Relation, or throws an exception
4781
-     *
4782
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4783
-     * @throws EE_Error
4784
-     * @return EE_Model_Relation_Base
4785
-     */
4786
-    public function related_settings_for($relation_name)
4787
-    {
4788
-        $relatedModels = $this->relation_settings();
4789
-        if (! array_key_exists($relation_name, $relatedModels)) {
4790
-            throw new EE_Error(
4791
-                sprintf(
4792
-                    __(
4793
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4794
-                        'event_espresso'
4795
-                    ),
4796
-                    $relation_name,
4797
-                    $this->_get_class_name(),
4798
-                    implode(', ', array_keys($relatedModels))
4799
-                )
4800
-            );
4801
-        }
4802
-        return $relatedModels[ $relation_name ];
4803
-    }
4804
-
4805
-
4806
-
4807
-    /**
4808
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4809
-     * fields
4810
-     *
4811
-     * @param string $fieldName
4812
-     * @param boolean $include_db_only_fields
4813
-     * @throws EE_Error
4814
-     * @return EE_Model_Field_Base
4815
-     */
4816
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4817
-    {
4818
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4819
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4820
-            throw new EE_Error(sprintf(
4821
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4822
-                $fieldName,
4823
-                get_class($this)
4824
-            ));
4825
-        }
4826
-        return $fieldSettings[ $fieldName ];
4827
-    }
4828
-
4829
-
4830
-
4831
-    /**
4832
-     * Checks if this field exists on this model
4833
-     *
4834
-     * @param string $fieldName a key in the model's _field_settings array
4835
-     * @return boolean
4836
-     */
4837
-    public function has_field($fieldName)
4838
-    {
4839
-        $fieldSettings = $this->field_settings(true);
4840
-        if (isset($fieldSettings[ $fieldName ])) {
4841
-            return true;
4842
-        }
4843
-        return false;
4844
-    }
4845
-
4846
-
4847
-
4848
-    /**
4849
-     * Returns whether or not this model has a relation to the specified model
4850
-     *
4851
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4852
-     * @return boolean
4853
-     */
4854
-    public function has_relation($relation_name)
4855
-    {
4856
-        $relations = $this->relation_settings();
4857
-        if (isset($relations[ $relation_name ])) {
4858
-            return true;
4859
-        }
4860
-        return false;
4861
-    }
4862
-
4863
-
4864
-
4865
-    /**
4866
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4867
-     * Eg, on EE_Answer that would be ANS_ID field object
4868
-     *
4869
-     * @param $field_obj
4870
-     * @return boolean
4871
-     */
4872
-    public function is_primary_key_field($field_obj)
4873
-    {
4874
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4875
-    }
4876
-
4877
-
4878
-
4879
-    /**
4880
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4881
-     * Eg, on EE_Answer that would be ANS_ID field object
4882
-     *
4883
-     * @return EE_Model_Field_Base
4884
-     * @throws EE_Error
4885
-     */
4886
-    public function get_primary_key_field()
4887
-    {
4888
-        if ($this->_primary_key_field === null) {
4889
-            foreach ($this->field_settings(true) as $field_obj) {
4890
-                if ($this->is_primary_key_field($field_obj)) {
4891
-                    $this->_primary_key_field = $field_obj;
4892
-                    break;
4893
-                }
4894
-            }
4895
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4896
-                throw new EE_Error(sprintf(
4897
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4898
-                    get_class($this)
4899
-                ));
4900
-            }
4901
-        }
4902
-        return $this->_primary_key_field;
4903
-    }
4904
-
4905
-
4906
-
4907
-    /**
4908
-     * Returns whether or not not there is a primary key on this model.
4909
-     * Internally does some caching.
4910
-     *
4911
-     * @return boolean
4912
-     */
4913
-    public function has_primary_key_field()
4914
-    {
4915
-        if ($this->_has_primary_key_field === null) {
4916
-            try {
4917
-                $this->get_primary_key_field();
4918
-                $this->_has_primary_key_field = true;
4919
-            } catch (EE_Error $e) {
4920
-                $this->_has_primary_key_field = false;
4921
-            }
4922
-        }
4923
-        return $this->_has_primary_key_field;
4924
-    }
4925
-
4926
-
4927
-
4928
-    /**
4929
-     * Finds the first field of type $field_class_name.
4930
-     *
4931
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4932
-     *                                 EE_Foreign_Key_Field, etc
4933
-     * @return EE_Model_Field_Base or null if none is found
4934
-     */
4935
-    public function get_a_field_of_type($field_class_name)
4936
-    {
4937
-        foreach ($this->field_settings() as $field) {
4938
-            if ($field instanceof $field_class_name) {
4939
-                return $field;
4940
-            }
4941
-        }
4942
-        return null;
4943
-    }
4944
-
4945
-
4946
-
4947
-    /**
4948
-     * Gets a foreign key field pointing to model.
4949
-     *
4950
-     * @param string $model_name eg Event, Registration, not EEM_Event
4951
-     * @return EE_Foreign_Key_Field_Base
4952
-     * @throws EE_Error
4953
-     */
4954
-    public function get_foreign_key_to($model_name)
4955
-    {
4956
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4957
-            foreach ($this->field_settings() as $field) {
4958
-                if ($field instanceof EE_Foreign_Key_Field_Base
4959
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4960
-                ) {
4961
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
4962
-                    break;
4963
-                }
4964
-            }
4965
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4966
-                throw new EE_Error(sprintf(__(
4967
-                    "There is no foreign key field pointing to model %s on model %s",
4968
-                    'event_espresso'
4969
-                ), $model_name, get_class($this)));
4970
-            }
4971
-        }
4972
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
4973
-    }
4974
-
4975
-
4976
-
4977
-    /**
4978
-     * Gets the table name (including $wpdb->prefix) for the table alias
4979
-     *
4980
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4981
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4982
-     *                            Either one works
4983
-     * @return string
4984
-     */
4985
-    public function get_table_for_alias($table_alias)
4986
-    {
4987
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4988
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
4989
-    }
4990
-
4991
-
4992
-
4993
-    /**
4994
-     * Returns a flat array of all field son this model, instead of organizing them
4995
-     * by table_alias as they are in the constructor.
4996
-     *
4997
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4998
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4999
-     */
5000
-    public function field_settings($include_db_only_fields = false)
5001
-    {
5002
-        if ($include_db_only_fields) {
5003
-            if ($this->_cached_fields === null) {
5004
-                $this->_cached_fields = array();
5005
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5006
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5007
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5008
-                    }
5009
-                }
5010
-            }
5011
-            return $this->_cached_fields;
5012
-        }
5013
-        if ($this->_cached_fields_non_db_only === null) {
5014
-            $this->_cached_fields_non_db_only = array();
5015
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5016
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5017
-                    /** @var $field_obj EE_Model_Field_Base */
5018
-                    if (! $field_obj->is_db_only_field()) {
5019
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5020
-                    }
5021
-                }
5022
-            }
5023
-        }
5024
-        return $this->_cached_fields_non_db_only;
5025
-    }
5026
-
5027
-
5028
-
5029
-    /**
5030
-     *        cycle though array of attendees and create objects out of each item
5031
-     *
5032
-     * @access        private
5033
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5034
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5035
-     *                           numerically indexed)
5036
-     * @throws EE_Error
5037
-     */
5038
-    protected function _create_objects($rows = array())
5039
-    {
5040
-        $array_of_objects = array();
5041
-        if (empty($rows)) {
5042
-            return array();
5043
-        }
5044
-        $count_if_model_has_no_primary_key = 0;
5045
-        $has_primary_key = $this->has_primary_key_field();
5046
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5047
-        foreach ((array) $rows as $row) {
5048
-            if (empty($row)) {
5049
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5050
-                return array();
5051
-            }
5052
-            // check if we've already set this object in the results array,
5053
-            // in which case there's no need to process it further (again)
5054
-            if ($has_primary_key) {
5055
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5056
-                    $row,
5057
-                    $primary_key_field->get_qualified_column(),
5058
-                    $primary_key_field->get_table_column()
5059
-                );
5060
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5061
-                    continue;
5062
-                }
5063
-            }
5064
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5065
-            if (! $classInstance) {
5066
-                throw new EE_Error(
5067
-                    sprintf(
5068
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5069
-                        $this->get_this_model_name(),
5070
-                        http_build_query($row)
5071
-                    )
5072
-                );
5073
-            }
5074
-            // set the timezone on the instantiated objects
5075
-            $classInstance->set_timezone($this->_timezone);
5076
-            // make sure if there is any timezone setting present that we set the timezone for the object
5077
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5078
-            $array_of_objects[ $key ] = $classInstance;
5079
-            // also, for all the relations of type BelongsTo, see if we can cache
5080
-            // those related models
5081
-            // (we could do this for other relations too, but if there are conditions
5082
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5083
-            // so it requires a little more thought than just caching them immediately...)
5084
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5085
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5086
-                    // check if this model's INFO is present. If so, cache it on the model
5087
-                    $other_model = $relation_obj->get_other_model();
5088
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5089
-                    // if we managed to make a model object from the results, cache it on the main model object
5090
-                    if ($other_model_obj_maybe) {
5091
-                        // set timezone on these other model objects if they are present
5092
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5093
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5094
-                    }
5095
-                }
5096
-            }
5097
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5098
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5099
-            // the field in the CustomSelects object
5100
-            if ($this->_custom_selections instanceof CustomSelects) {
5101
-                $classInstance->setCustomSelectsValues(
5102
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5103
-                );
5104
-            }
5105
-        }
5106
-        return $array_of_objects;
5107
-    }
5108
-
5109
-
5110
-    /**
5111
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5112
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5113
-     *
5114
-     * @param array $db_results_row
5115
-     * @return array
5116
-     */
5117
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5118
-    {
5119
-        $results = array();
5120
-        if ($this->_custom_selections instanceof CustomSelects) {
5121
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5122
-                if (isset($db_results_row[ $alias ])) {
5123
-                    $results[ $alias ] = $this->convertValueToDataType(
5124
-                        $db_results_row[ $alias ],
5125
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5126
-                    );
5127
-                }
5128
-            }
5129
-        }
5130
-        return $results;
5131
-    }
5132
-
5133
-
5134
-    /**
5135
-     * This will set the value for the given alias
5136
-     * @param string $value
5137
-     * @param string $datatype (one of %d, %s, %f)
5138
-     * @return int|string|float (int for %d, string for %s, float for %f)
5139
-     */
5140
-    protected function convertValueToDataType($value, $datatype)
5141
-    {
5142
-        switch ($datatype) {
5143
-            case '%f':
5144
-                return (float) $value;
5145
-            case '%d':
5146
-                return (int) $value;
5147
-            default:
5148
-                return (string) $value;
5149
-        }
5150
-    }
5151
-
5152
-
5153
-    /**
5154
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5155
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5156
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5157
-     * object (as set in the model_field!).
5158
-     *
5159
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5160
-     */
5161
-    public function create_default_object()
5162
-    {
5163
-        $this_model_fields_and_values = array();
5164
-        // setup the row using default values;
5165
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5166
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5167
-        }
5168
-        $className = $this->_get_class_name();
5169
-        $classInstance = EE_Registry::instance()
5170
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5171
-        return $classInstance;
5172
-    }
5173
-
5174
-
5175
-
5176
-    /**
5177
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5178
-     *                             or an stdClass where each property is the name of a column,
5179
-     * @return EE_Base_Class
5180
-     * @throws EE_Error
5181
-     */
5182
-    public function instantiate_class_from_array_or_object($cols_n_values)
5183
-    {
5184
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5185
-            $cols_n_values = get_object_vars($cols_n_values);
5186
-        }
5187
-        $primary_key = null;
5188
-        // make sure the array only has keys that are fields/columns on this model
5189
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5190
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5191
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5192
-        }
5193
-        $className = $this->_get_class_name();
5194
-        // check we actually found results that we can use to build our model object
5195
-        // if not, return null
5196
-        if ($this->has_primary_key_field()) {
5197
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5198
-                return null;
5199
-            }
5200
-        } elseif ($this->unique_indexes()) {
5201
-            $first_column = reset($this_model_fields_n_values);
5202
-            if (empty($first_column)) {
5203
-                return null;
5204
-            }
5205
-        }
5206
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5207
-        if ($primary_key) {
5208
-            $classInstance = $this->get_from_entity_map($primary_key);
5209
-            if (! $classInstance) {
5210
-                $classInstance = EE_Registry::instance()
5211
-                                            ->load_class(
5212
-                                                $className,
5213
-                                                array($this_model_fields_n_values, $this->_timezone),
5214
-                                                true,
5215
-                                                false
5216
-                                            );
5217
-                // add this new object to the entity map
5218
-                $classInstance = $this->add_to_entity_map($classInstance);
5219
-            }
5220
-        } else {
5221
-            $classInstance = EE_Registry::instance()
5222
-                                        ->load_class(
5223
-                                            $className,
5224
-                                            array($this_model_fields_n_values, $this->_timezone),
5225
-                                            true,
5226
-                                            false
5227
-                                        );
5228
-        }
5229
-        return $classInstance;
5230
-    }
5231
-
5232
-
5233
-
5234
-    /**
5235
-     * Gets the model object from the  entity map if it exists
5236
-     *
5237
-     * @param int|string $id the ID of the model object
5238
-     * @return EE_Base_Class
5239
-     */
5240
-    public function get_from_entity_map($id)
5241
-    {
5242
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5243
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5244
-    }
5245
-
5246
-
5247
-
5248
-    /**
5249
-     * add_to_entity_map
5250
-     * Adds the object to the model's entity mappings
5251
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5252
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5253
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5254
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5255
-     *        then this method should be called immediately after the update query
5256
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5257
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5258
-     *
5259
-     * @param    EE_Base_Class $object
5260
-     * @throws EE_Error
5261
-     * @return \EE_Base_Class
5262
-     */
5263
-    public function add_to_entity_map(EE_Base_Class $object)
5264
-    {
5265
-        $className = $this->_get_class_name();
5266
-        if (! $object instanceof $className) {
5267
-            throw new EE_Error(sprintf(
5268
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5269
-                is_object($object) ? get_class($object) : $object,
5270
-                $className
5271
-            ));
5272
-        }
5273
-        /** @var $object EE_Base_Class */
5274
-        if (! $object->ID()) {
5275
-            throw new EE_Error(sprintf(__(
5276
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5277
-                "event_espresso"
5278
-            ), get_class($this)));
5279
-        }
5280
-        // double check it's not already there
5281
-        $classInstance = $this->get_from_entity_map($object->ID());
5282
-        if ($classInstance) {
5283
-            return $classInstance;
5284
-        }
5285
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5286
-        return $object;
5287
-    }
5288
-
5289
-
5290
-
5291
-    /**
5292
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5293
-     * if no identifier is provided, then the entire entity map is emptied
5294
-     *
5295
-     * @param int|string $id the ID of the model object
5296
-     * @return boolean
5297
-     */
5298
-    public function clear_entity_map($id = null)
5299
-    {
5300
-        if (empty($id)) {
5301
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5302
-            return true;
5303
-        }
5304
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5305
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5306
-            return true;
5307
-        }
5308
-        return false;
5309
-    }
5310
-
5311
-
5312
-
5313
-    /**
5314
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5315
-     * Given an array where keys are column (or column alias) names and values,
5316
-     * returns an array of their corresponding field names and database values
5317
-     *
5318
-     * @param array $cols_n_values
5319
-     * @return array
5320
-     */
5321
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5322
-    {
5323
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
-    }
5325
-
5326
-
5327
-
5328
-    /**
5329
-     * _deduce_fields_n_values_from_cols_n_values
5330
-     * Given an array where keys are column (or column alias) names and values,
5331
-     * returns an array of their corresponding field names and database values
5332
-     *
5333
-     * @param string $cols_n_values
5334
-     * @return array
5335
-     */
5336
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5337
-    {
5338
-        $this_model_fields_n_values = array();
5339
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5340
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5341
-                $cols_n_values,
5342
-                $table_obj->get_fully_qualified_pk_column(),
5343
-                $table_obj->get_pk_column()
5344
-            );
5345
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5346
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5347
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5348
-                    if (! $field_obj->is_db_only_field()) {
5349
-                        // prepare field as if its coming from db
5350
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5351
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5352
-                    }
5353
-                }
5354
-            } else {
5355
-                // the table's rows existed. Use their values
5356
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5357
-                    if (! $field_obj->is_db_only_field()) {
5358
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5359
-                            $cols_n_values,
5360
-                            $field_obj->get_qualified_column(),
5361
-                            $field_obj->get_table_column()
5362
-                        );
5363
-                    }
5364
-                }
5365
-            }
5366
-        }
5367
-        return $this_model_fields_n_values;
5368
-    }
5369
-
5370
-
5371
-
5372
-    /**
5373
-     * @param $cols_n_values
5374
-     * @param $qualified_column
5375
-     * @param $regular_column
5376
-     * @return null
5377
-     */
5378
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5379
-    {
5380
-        $value = null;
5381
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5382
-        // does the field on the model relate to this column retrieved from the db?
5383
-        // or is it a db-only field? (not relating to the model)
5384
-        if (isset($cols_n_values[ $qualified_column ])) {
5385
-            $value = $cols_n_values[ $qualified_column ];
5386
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5387
-            $value = $cols_n_values[ $regular_column ];
5388
-        }
5389
-        return $value;
5390
-    }
5391
-
5392
-
5393
-
5394
-    /**
5395
-     * refresh_entity_map_from_db
5396
-     * Makes sure the model object in the entity map at $id assumes the values
5397
-     * of the database (opposite of EE_base_Class::save())
5398
-     *
5399
-     * @param int|string $id
5400
-     * @return EE_Base_Class
5401
-     * @throws EE_Error
5402
-     */
5403
-    public function refresh_entity_map_from_db($id)
5404
-    {
5405
-        $obj_in_map = $this->get_from_entity_map($id);
5406
-        if ($obj_in_map) {
5407
-            $wpdb_results = $this->_get_all_wpdb_results(
5408
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5409
-            );
5410
-            if ($wpdb_results && is_array($wpdb_results)) {
5411
-                $one_row = reset($wpdb_results);
5412
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5413
-                    $obj_in_map->set_from_db($field_name, $db_value);
5414
-                }
5415
-                // clear the cache of related model objects
5416
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5417
-                    $obj_in_map->clear_cache($relation_name, null, true);
5418
-                }
5419
-            }
5420
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5421
-            return $obj_in_map;
5422
-        }
5423
-        return $this->get_one_by_ID($id);
5424
-    }
5425
-
5426
-
5427
-
5428
-    /**
5429
-     * refresh_entity_map_with
5430
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5431
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5432
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5433
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5434
-     *
5435
-     * @param int|string    $id
5436
-     * @param EE_Base_Class $replacing_model_obj
5437
-     * @return \EE_Base_Class
5438
-     * @throws EE_Error
5439
-     */
5440
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5441
-    {
5442
-        $obj_in_map = $this->get_from_entity_map($id);
5443
-        if ($obj_in_map) {
5444
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5445
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5446
-                    $obj_in_map->set($field_name, $value);
5447
-                }
5448
-                // make the model object in the entity map's cache match the $replacing_model_obj
5449
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5450
-                    $obj_in_map->clear_cache($relation_name, null, true);
5451
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5452
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5453
-                    }
5454
-                }
5455
-            }
5456
-            return $obj_in_map;
5457
-        }
5458
-        $this->add_to_entity_map($replacing_model_obj);
5459
-        return $replacing_model_obj;
5460
-    }
5461
-
5462
-
5463
-
5464
-    /**
5465
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5466
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5467
-     * require_once($this->_getClassName().".class.php");
5468
-     *
5469
-     * @return string
5470
-     */
5471
-    private function _get_class_name()
5472
-    {
5473
-        return "EE_" . $this->get_this_model_name();
5474
-    }
5475
-
5476
-
5477
-
5478
-    /**
5479
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5480
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5481
-     * it would be 'Events'.
5482
-     *
5483
-     * @param int $quantity
5484
-     * @return string
5485
-     */
5486
-    public function item_name($quantity = 1)
5487
-    {
5488
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5489
-    }
5490
-
5491
-
5492
-
5493
-    /**
5494
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5495
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5496
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5497
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5498
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5499
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5500
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5501
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5502
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5503
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5504
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5505
-     *        return $previousReturnValue.$returnString;
5506
-     * }
5507
-     * require('EEM_Answer.model.php');
5508
-     * $answer=EEM_Answer::instance();
5509
-     * echo $answer->my_callback('monkeys',100);
5510
-     * //will output "you called my_callback! and passed args:monkeys,100"
5511
-     *
5512
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5513
-     * @param array  $args       array of original arguments passed to the function
5514
-     * @throws EE_Error
5515
-     * @return mixed whatever the plugin which calls add_filter decides
5516
-     */
5517
-    public function __call($methodName, $args)
5518
-    {
5519
-        $className = get_class($this);
5520
-        $tagName = "FHEE__{$className}__{$methodName}";
5521
-        if (! has_filter($tagName)) {
5522
-            throw new EE_Error(
5523
-                sprintf(
5524
-                    __(
5525
-                        '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 );',
5526
-                        'event_espresso'
5527
-                    ),
5528
-                    $methodName,
5529
-                    $className,
5530
-                    $tagName,
5531
-                    '<br />'
5532
-                )
5533
-            );
5534
-        }
5535
-        return apply_filters($tagName, null, $this, $args);
5536
-    }
5537
-
5538
-
5539
-
5540
-    /**
5541
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5542
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5543
-     *
5544
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5545
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5546
-     *                                                       the object's class name
5547
-     *                                                       or object's ID
5548
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5549
-     *                                                       exists in the database. If it does not, we add it
5550
-     * @throws EE_Error
5551
-     * @return EE_Base_Class
5552
-     */
5553
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5554
-    {
5555
-        $className = $this->_get_class_name();
5556
-        if ($base_class_obj_or_id instanceof $className) {
5557
-            $model_object = $base_class_obj_or_id;
5558
-        } else {
5559
-            $primary_key_field = $this->get_primary_key_field();
5560
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5561
-                && (
5562
-                    is_int($base_class_obj_or_id)
5563
-                    || is_string($base_class_obj_or_id)
5564
-                )
5565
-            ) {
5566
-                // assume it's an ID.
5567
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5568
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5569
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5570
-                && is_string($base_class_obj_or_id)
5571
-            ) {
5572
-                // assume its a string representation of the object
5573
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5574
-            } else {
5575
-                throw new EE_Error(
5576
-                    sprintf(
5577
-                        __(
5578
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5579
-                            'event_espresso'
5580
-                        ),
5581
-                        $base_class_obj_or_id,
5582
-                        $this->_get_class_name(),
5583
-                        print_r($base_class_obj_or_id, true)
5584
-                    )
5585
-                );
5586
-            }
5587
-        }
5588
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5589
-            $model_object->save();
5590
-        }
5591
-        return $model_object;
5592
-    }
5593
-
5594
-
5595
-
5596
-    /**
5597
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5598
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5599
-     * returns it ID.
5600
-     *
5601
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5602
-     * @return int|string depending on the type of this model object's ID
5603
-     * @throws EE_Error
5604
-     */
5605
-    public function ensure_is_ID($base_class_obj_or_id)
5606
-    {
5607
-        $className = $this->_get_class_name();
5608
-        if ($base_class_obj_or_id instanceof $className) {
5609
-            /** @var $base_class_obj_or_id EE_Base_Class */
5610
-            $id = $base_class_obj_or_id->ID();
5611
-        } elseif (is_int($base_class_obj_or_id)) {
5612
-            // assume it's an ID
5613
-            $id = $base_class_obj_or_id;
5614
-        } elseif (is_string($base_class_obj_or_id)) {
5615
-            // assume its a string representation of the object
5616
-            $id = $base_class_obj_or_id;
5617
-        } else {
5618
-            throw new EE_Error(sprintf(
5619
-                __(
5620
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5621
-                    'event_espresso'
5622
-                ),
5623
-                $base_class_obj_or_id,
5624
-                $this->_get_class_name(),
5625
-                print_r($base_class_obj_or_id, true)
5626
-            ));
5627
-        }
5628
-        return $id;
5629
-    }
5630
-
5631
-
5632
-
5633
-    /**
5634
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5635
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5636
-     * been sanitized and converted into the appropriate domain.
5637
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5638
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5639
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5640
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5641
-     * $EVT = EEM_Event::instance(); $old_setting =
5642
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5643
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5644
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5645
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5646
-     *
5647
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5648
-     * @return void
5649
-     */
5650
-    public function assume_values_already_prepared_by_model_object(
5651
-        $values_already_prepared = self::not_prepared_by_model_object
5652
-    ) {
5653
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5654
-    }
5655
-
5656
-
5657
-
5658
-    /**
5659
-     * Read comments for assume_values_already_prepared_by_model_object()
5660
-     *
5661
-     * @return int
5662
-     */
5663
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5664
-    {
5665
-        return $this->_values_already_prepared_by_model_object;
5666
-    }
5667
-
5668
-
5669
-
5670
-    /**
5671
-     * Gets all the indexes on this model
5672
-     *
5673
-     * @return EE_Index[]
5674
-     */
5675
-    public function indexes()
5676
-    {
5677
-        return $this->_indexes;
5678
-    }
5679
-
5680
-
5681
-
5682
-    /**
5683
-     * Gets all the Unique Indexes on this model
5684
-     *
5685
-     * @return EE_Unique_Index[]
5686
-     */
5687
-    public function unique_indexes()
5688
-    {
5689
-        $unique_indexes = array();
5690
-        foreach ($this->_indexes as $name => $index) {
5691
-            if ($index instanceof EE_Unique_Index) {
5692
-                $unique_indexes [ $name ] = $index;
5693
-            }
5694
-        }
5695
-        return $unique_indexes;
5696
-    }
5697
-
5698
-
5699
-
5700
-    /**
5701
-     * Gets all the fields which, when combined, make the primary key.
5702
-     * This is usually just an array with 1 element (the primary key), but in cases
5703
-     * where there is no primary key, it's a combination of fields as defined
5704
-     * on a primary index
5705
-     *
5706
-     * @return EE_Model_Field_Base[] indexed by the field's name
5707
-     * @throws EE_Error
5708
-     */
5709
-    public function get_combined_primary_key_fields()
5710
-    {
5711
-        foreach ($this->indexes() as $index) {
5712
-            if ($index instanceof EE_Primary_Key_Index) {
5713
-                return $index->fields();
5714
-            }
5715
-        }
5716
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5717
-    }
5718
-
5719
-
5720
-
5721
-    /**
5722
-     * Used to build a primary key string (when the model has no primary key),
5723
-     * which can be used a unique string to identify this model object.
5724
-     *
5725
-     * @param array $cols_n_values keys are field names, values are their values
5726
-     * @return string
5727
-     * @throws EE_Error
5728
-     */
5729
-    public function get_index_primary_key_string($cols_n_values)
5730
-    {
5731
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5732
-            $cols_n_values,
5733
-            $this->get_combined_primary_key_fields()
5734
-        );
5735
-        return http_build_query($cols_n_values_for_primary_key_index);
5736
-    }
5737
-
5738
-
5739
-
5740
-    /**
5741
-     * Gets the field values from the primary key string
5742
-     *
5743
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5744
-     * @param string $index_primary_key_string
5745
-     * @return null|array
5746
-     * @throws EE_Error
5747
-     */
5748
-    public function parse_index_primary_key_string($index_primary_key_string)
5749
-    {
5750
-        $key_fields = $this->get_combined_primary_key_fields();
5751
-        // check all of them are in the $id
5752
-        $key_vals_in_combined_pk = array();
5753
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5754
-        foreach ($key_fields as $key_field_name => $field_obj) {
5755
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5756
-                return null;
5757
-            }
5758
-        }
5759
-        return $key_vals_in_combined_pk;
5760
-    }
5761
-
5762
-
5763
-
5764
-    /**
5765
-     * verifies that an array of key-value pairs for model fields has a key
5766
-     * for each field comprising the primary key index
5767
-     *
5768
-     * @param array $key_vals
5769
-     * @return boolean
5770
-     * @throws EE_Error
5771
-     */
5772
-    public function has_all_combined_primary_key_fields($key_vals)
5773
-    {
5774
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5775
-        foreach ($keys_it_should_have as $key) {
5776
-            if (! isset($key_vals[ $key ])) {
5777
-                return false;
5778
-            }
5779
-        }
5780
-        return true;
5781
-    }
5782
-
5783
-
5784
-
5785
-    /**
5786
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5787
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5788
-     *
5789
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5790
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5791
-     * @throws EE_Error
5792
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5793
-     *                                                              indexed)
5794
-     */
5795
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5796
-    {
5797
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5798
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5799
-        } elseif (is_array($model_object_or_attributes_array)) {
5800
-            $attributes_array = $model_object_or_attributes_array;
5801
-        } else {
5802
-            throw new EE_Error(sprintf(__(
5803
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5804
-                "event_espresso"
5805
-            ), $model_object_or_attributes_array));
5806
-        }
5807
-        // even copies obviously won't have the same ID, so remove the primary key
5808
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5809
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5810
-            unset($attributes_array[ $this->primary_key_name() ]);
5811
-        }
5812
-        if (isset($query_params[0])) {
5813
-            $query_params[0] = array_merge($attributes_array, $query_params);
5814
-        } else {
5815
-            $query_params[0] = $attributes_array;
5816
-        }
5817
-        return $this->get_all($query_params);
5818
-    }
5819
-
5820
-
5821
-
5822
-    /**
5823
-     * Gets the first copy we find. See get_all_copies for more details
5824
-     *
5825
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5826
-     * @param array $query_params
5827
-     * @return EE_Base_Class
5828
-     * @throws EE_Error
5829
-     */
5830
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5831
-    {
5832
-        if (! is_array($query_params)) {
5833
-            EE_Error::doing_it_wrong(
5834
-                'EEM_Base::get_one_copy',
5835
-                sprintf(
5836
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5837
-                    gettype($query_params)
5838
-                ),
5839
-                '4.6.0'
5840
-            );
5841
-            $query_params = array();
5842
-        }
5843
-        $query_params['limit'] = 1;
5844
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5845
-        if (is_array($copies)) {
5846
-            return array_shift($copies);
5847
-        }
5848
-        return null;
5849
-    }
5850
-
5851
-
5852
-
5853
-    /**
5854
-     * Updates the item with the specified id. Ignores default query parameters because
5855
-     * we have specified the ID, and its assumed we KNOW what we're doing
5856
-     *
5857
-     * @param array      $fields_n_values keys are field names, values are their new values
5858
-     * @param int|string $id              the value of the primary key to update
5859
-     * @return int number of rows updated
5860
-     * @throws EE_Error
5861
-     */
5862
-    public function update_by_ID($fields_n_values, $id)
5863
-    {
5864
-        $query_params = array(
5865
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5866
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5867
-        );
5868
-        return $this->update($fields_n_values, $query_params);
5869
-    }
5870
-
5871
-
5872
-
5873
-    /**
5874
-     * Changes an operator which was supplied to the models into one usable in SQL
5875
-     *
5876
-     * @param string $operator_supplied
5877
-     * @return string an operator which can be used in SQL
5878
-     * @throws EE_Error
5879
-     */
5880
-    private function _prepare_operator_for_sql($operator_supplied)
5881
-    {
5882
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5883
-            : null;
5884
-        if ($sql_operator) {
5885
-            return $sql_operator;
5886
-        }
5887
-        throw new EE_Error(
5888
-            sprintf(
5889
-                __(
5890
-                    "The operator '%s' is not in the list of valid operators: %s",
5891
-                    "event_espresso"
5892
-                ),
5893
-                $operator_supplied,
5894
-                implode(",", array_keys($this->_valid_operators))
5895
-            )
5896
-        );
5897
-    }
5898
-
5899
-
5900
-
5901
-    /**
5902
-     * Gets the valid operators
5903
-     * @return array keys are accepted strings, values are the SQL they are converted to
5904
-     */
5905
-    public function valid_operators()
5906
-    {
5907
-        return $this->_valid_operators;
5908
-    }
5909
-
5910
-
5911
-
5912
-    /**
5913
-     * Gets the between-style operators (take 2 arguments).
5914
-     * @return array keys are accepted strings, values are the SQL they are converted to
5915
-     */
5916
-    public function valid_between_style_operators()
5917
-    {
5918
-        return array_intersect(
5919
-            $this->valid_operators(),
5920
-            $this->_between_style_operators
5921
-        );
5922
-    }
5923
-
5924
-    /**
5925
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5926
-     * @return array keys are accepted strings, values are the SQL they are converted to
5927
-     */
5928
-    public function valid_like_style_operators()
5929
-    {
5930
-        return array_intersect(
5931
-            $this->valid_operators(),
5932
-            $this->_like_style_operators
5933
-        );
5934
-    }
5935
-
5936
-    /**
5937
-     * Gets the "in"-style operators
5938
-     * @return array keys are accepted strings, values are the SQL they are converted to
5939
-     */
5940
-    public function valid_in_style_operators()
5941
-    {
5942
-        return array_intersect(
5943
-            $this->valid_operators(),
5944
-            $this->_in_style_operators
5945
-        );
5946
-    }
5947
-
5948
-    /**
5949
-     * Gets the "null"-style operators (accept no arguments)
5950
-     * @return array keys are accepted strings, values are the SQL they are converted to
5951
-     */
5952
-    public function valid_null_style_operators()
5953
-    {
5954
-        return array_intersect(
5955
-            $this->valid_operators(),
5956
-            $this->_null_style_operators
5957
-        );
5958
-    }
5959
-
5960
-    /**
5961
-     * Gets an array where keys are the primary keys and values are their 'names'
5962
-     * (as determined by the model object's name() function, which is often overridden)
5963
-     *
5964
-     * @param array $query_params like get_all's
5965
-     * @return string[]
5966
-     * @throws EE_Error
5967
-     */
5968
-    public function get_all_names($query_params = array())
5969
-    {
5970
-        $objs = $this->get_all($query_params);
5971
-        $names = array();
5972
-        foreach ($objs as $obj) {
5973
-            $names[ $obj->ID() ] = $obj->name();
5974
-        }
5975
-        return $names;
5976
-    }
5977
-
5978
-
5979
-
5980
-    /**
5981
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5982
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5983
-     * this is duplicated effort and reduces efficiency) you would be better to use
5984
-     * array_keys() on $model_objects.
5985
-     *
5986
-     * @param \EE_Base_Class[] $model_objects
5987
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5988
-     *                                               in the returned array
5989
-     * @return array
5990
-     * @throws EE_Error
5991
-     */
5992
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5993
-    {
5994
-        if (! $this->has_primary_key_field()) {
5995
-            if (WP_DEBUG) {
5996
-                EE_Error::add_error(
5997
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5998
-                    __FILE__,
5999
-                    __FUNCTION__,
6000
-                    __LINE__
6001
-                );
6002
-            }
6003
-        }
6004
-        $IDs = array();
6005
-        foreach ($model_objects as $model_object) {
6006
-            $id = $model_object->ID();
6007
-            if (! $id) {
6008
-                if ($filter_out_empty_ids) {
6009
-                    continue;
6010
-                }
6011
-                if (WP_DEBUG) {
6012
-                    EE_Error::add_error(
6013
-                        __(
6014
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6015
-                            'event_espresso'
6016
-                        ),
6017
-                        __FILE__,
6018
-                        __FUNCTION__,
6019
-                        __LINE__
6020
-                    );
6021
-                }
6022
-            }
6023
-            $IDs[] = $id;
6024
-        }
6025
-        return $IDs;
6026
-    }
6027
-
6028
-
6029
-
6030
-    /**
6031
-     * Returns the string used in capabilities relating to this model. If there
6032
-     * are no capabilities that relate to this model returns false
6033
-     *
6034
-     * @return string|false
6035
-     */
6036
-    public function cap_slug()
6037
-    {
6038
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6039
-    }
6040
-
6041
-
6042
-
6043
-    /**
6044
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6045
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6046
-     * only returns the cap restrictions array in that context (ie, the array
6047
-     * at that key)
6048
-     *
6049
-     * @param string $context
6050
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6051
-     * @throws EE_Error
6052
-     */
6053
-    public function cap_restrictions($context = EEM_Base::caps_read)
6054
-    {
6055
-        EEM_Base::verify_is_valid_cap_context($context);
6056
-        // check if we ought to run the restriction generator first
6057
-        if (isset($this->_cap_restriction_generators[ $context ])
6058
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6059
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6060
-        ) {
6061
-            $this->_cap_restrictions[ $context ] = array_merge(
6062
-                $this->_cap_restrictions[ $context ],
6063
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6064
-            );
6065
-        }
6066
-        // and make sure we've finalized the construction of each restriction
6067
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6068
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6069
-                $where_conditions_obj->_finalize_construct($this);
6070
-            }
6071
-        }
6072
-        return $this->_cap_restrictions[ $context ];
6073
-    }
6074
-
6075
-
6076
-
6077
-    /**
6078
-     * Indicating whether or not this model thinks its a wp core model
6079
-     *
6080
-     * @return boolean
6081
-     */
6082
-    public function is_wp_core_model()
6083
-    {
6084
-        return $this->_wp_core_model;
6085
-    }
6086
-
6087
-
6088
-
6089
-    /**
6090
-     * Gets all the caps that are missing which impose a restriction on
6091
-     * queries made in this context
6092
-     *
6093
-     * @param string $context one of EEM_Base::caps_ constants
6094
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6095
-     * @throws EE_Error
6096
-     */
6097
-    public function caps_missing($context = EEM_Base::caps_read)
6098
-    {
6099
-        $missing_caps = array();
6100
-        $cap_restrictions = $this->cap_restrictions($context);
6101
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6102
-            if (! EE_Capabilities::instance()
6103
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6104
-            ) {
6105
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6106
-            }
6107
-        }
6108
-        return $missing_caps;
6109
-    }
6110
-
6111
-
6112
-
6113
-    /**
6114
-     * Gets the mapping from capability contexts to action strings used in capability names
6115
-     *
6116
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6117
-     * one of 'read', 'edit', or 'delete'
6118
-     */
6119
-    public function cap_contexts_to_cap_action_map()
6120
-    {
6121
-        return apply_filters(
6122
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6123
-            $this->_cap_contexts_to_cap_action_map,
6124
-            $this
6125
-        );
6126
-    }
6127
-
6128
-
6129
-
6130
-    /**
6131
-     * Gets the action string for the specified capability context
6132
-     *
6133
-     * @param string $context
6134
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6135
-     * @throws EE_Error
6136
-     */
6137
-    public function cap_action_for_context($context)
6138
-    {
6139
-        $mapping = $this->cap_contexts_to_cap_action_map();
6140
-        if (isset($mapping[ $context ])) {
6141
-            return $mapping[ $context ];
6142
-        }
6143
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6144
-            return $action;
6145
-        }
6146
-        throw new EE_Error(
6147
-            sprintf(
6148
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6149
-                $context,
6150
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6151
-            )
6152
-        );
6153
-    }
6154
-
6155
-
6156
-
6157
-    /**
6158
-     * Returns all the capability contexts which are valid when querying models
6159
-     *
6160
-     * @return array
6161
-     */
6162
-    public static function valid_cap_contexts()
6163
-    {
6164
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6165
-            self::caps_read,
6166
-            self::caps_read_admin,
6167
-            self::caps_edit,
6168
-            self::caps_delete,
6169
-        ));
6170
-    }
6171
-
6172
-
6173
-
6174
-    /**
6175
-     * Returns all valid options for 'default_where_conditions'
6176
-     *
6177
-     * @return array
6178
-     */
6179
-    public static function valid_default_where_conditions()
6180
-    {
6181
-        return array(
6182
-            EEM_Base::default_where_conditions_all,
6183
-            EEM_Base::default_where_conditions_this_only,
6184
-            EEM_Base::default_where_conditions_others_only,
6185
-            EEM_Base::default_where_conditions_minimum_all,
6186
-            EEM_Base::default_where_conditions_minimum_others,
6187
-            EEM_Base::default_where_conditions_none
6188
-        );
6189
-    }
6190
-
6191
-    // public static function default_where_conditions_full
6192
-    /**
6193
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6194
-     *
6195
-     * @param string $context
6196
-     * @return bool
6197
-     * @throws EE_Error
6198
-     */
6199
-    public static function verify_is_valid_cap_context($context)
6200
-    {
6201
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6202
-        if (in_array($context, $valid_cap_contexts)) {
6203
-            return true;
6204
-        }
6205
-        throw new EE_Error(
6206
-            sprintf(
6207
-                __(
6208
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6209
-                    'event_espresso'
6210
-                ),
6211
-                $context,
6212
-                'EEM_Base',
6213
-                implode(',', $valid_cap_contexts)
6214
-            )
6215
-        );
6216
-    }
6217
-
6218
-
6219
-
6220
-    /**
6221
-     * Clears all the models field caches. This is only useful when a sub-class
6222
-     * might have added a field or something and these caches might be invalidated
6223
-     */
6224
-    protected function _invalidate_field_caches()
6225
-    {
6226
-        $this->_cache_foreign_key_to_fields = array();
6227
-        $this->_cached_fields = null;
6228
-        $this->_cached_fields_non_db_only = null;
6229
-    }
6230
-
6231
-
6232
-
6233
-    /**
6234
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6235
-     * (eg "and", "or", "not").
6236
-     *
6237
-     * @return array
6238
-     */
6239
-    public function logic_query_param_keys()
6240
-    {
6241
-        return $this->_logic_query_param_keys;
6242
-    }
6243
-
6244
-
6245
-
6246
-    /**
6247
-     * Determines whether or not the where query param array key is for a logic query param.
6248
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6249
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6250
-     *
6251
-     * @param $query_param_key
6252
-     * @return bool
6253
-     */
6254
-    public function is_logic_query_param_key($query_param_key)
6255
-    {
6256
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6257
-            if ($query_param_key === $logic_query_param_key
6258
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6259
-            ) {
6260
-                return true;
6261
-            }
6262
-        }
6263
-        return false;
6264
-    }
3751
+		}
3752
+		return $null_friendly_where_conditions;
3753
+	}
3754
+
3755
+
3756
+
3757
+	/**
3758
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3759
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3760
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3761
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3762
+	 *
3763
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3764
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3765
+	 */
3766
+	private function _get_default_where_conditions($model_relation_path = null)
3767
+	{
3768
+		if ($this->_ignore_where_strategy) {
3769
+			return array();
3770
+		}
3771
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3772
+	}
3773
+
3774
+
3775
+
3776
+	/**
3777
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3778
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3779
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3780
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3781
+	 * Similar to _get_default_where_conditions
3782
+	 *
3783
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3784
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3785
+	 */
3786
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3787
+	{
3788
+		if ($this->_ignore_where_strategy) {
3789
+			return array();
3790
+		}
3791
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3792
+	}
3793
+
3794
+
3795
+
3796
+	/**
3797
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3798
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3799
+	 *
3800
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3801
+	 * @return string
3802
+	 * @throws EE_Error
3803
+	 */
3804
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3805
+	{
3806
+		$selects = $this->_get_columns_to_select_for_this_model();
3807
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3808
+			$name_of_other_model_included) {
3809
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3810
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3811
+			foreach ($other_model_selects as $key => $value) {
3812
+				$selects[] = $value;
3813
+			}
3814
+		}
3815
+		return implode(", ", $selects);
3816
+	}
3817
+
3818
+
3819
+
3820
+	/**
3821
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3822
+	 * So that's going to be the columns for all the fields on the model
3823
+	 *
3824
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3825
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3826
+	 */
3827
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3828
+	{
3829
+		$fields = $this->field_settings();
3830
+		$selects = array();
3831
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3832
+			$model_relation_chain,
3833
+			$this->get_this_model_name()
3834
+		);
3835
+		foreach ($fields as $field_obj) {
3836
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3837
+						 . $field_obj->get_table_alias()
3838
+						 . "."
3839
+						 . $field_obj->get_table_column()
3840
+						 . " AS '"
3841
+						 . $table_alias_with_model_relation_chain_prefix
3842
+						 . $field_obj->get_table_alias()
3843
+						 . "."
3844
+						 . $field_obj->get_table_column()
3845
+						 . "'";
3846
+		}
3847
+		// make sure we are also getting the PKs of each table
3848
+		$tables = $this->get_tables();
3849
+		if (count($tables) > 1) {
3850
+			foreach ($tables as $table_obj) {
3851
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3852
+									   . $table_obj->get_fully_qualified_pk_column();
3853
+				if (! in_array($qualified_pk_column, $selects)) {
3854
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3855
+				}
3856
+			}
3857
+		}
3858
+		return $selects;
3859
+	}
3860
+
3861
+
3862
+
3863
+	/**
3864
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3865
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3866
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3867
+	 * SQL for joining, and the data types
3868
+	 *
3869
+	 * @param null|string                 $original_query_param
3870
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3871
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3872
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3873
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3874
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3875
+	 *                                                          or 'Registration's
3876
+	 * @param string                      $original_query_param what it originally was (eg
3877
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3878
+	 *                                                          matches $query_param
3879
+	 * @throws EE_Error
3880
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3881
+	 */
3882
+	private function _extract_related_model_info_from_query_param(
3883
+		$query_param,
3884
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3885
+		$query_param_type,
3886
+		$original_query_param = null
3887
+	) {
3888
+		if ($original_query_param === null) {
3889
+			$original_query_param = $query_param;
3890
+		}
3891
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3892
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3893
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3894
+		$allow_fields = in_array(
3895
+			$query_param_type,
3896
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3897
+			true
3898
+		);
3899
+		// check to see if we have a field on this model
3900
+		$this_model_fields = $this->field_settings(true);
3901
+		if (array_key_exists($query_param, $this_model_fields)) {
3902
+			if ($allow_fields) {
3903
+				return;
3904
+			}
3905
+			throw new EE_Error(
3906
+				sprintf(
3907
+					__(
3908
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3909
+						"event_espresso"
3910
+					),
3911
+					$query_param,
3912
+					get_class($this),
3913
+					$query_param_type,
3914
+					$original_query_param
3915
+				)
3916
+			);
3917
+		}
3918
+		// check if this is a special logic query param
3919
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3920
+			if ($allow_logic_query_params) {
3921
+				return;
3922
+			}
3923
+			throw new EE_Error(
3924
+				sprintf(
3925
+					__(
3926
+						'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',
3927
+						'event_espresso'
3928
+					),
3929
+					implode('", "', $this->_logic_query_param_keys),
3930
+					$query_param,
3931
+					get_class($this),
3932
+					'<br />',
3933
+					"\t"
3934
+					. ' $passed_in_query_info = <pre>'
3935
+					. print_r($passed_in_query_info, true)
3936
+					. '</pre>'
3937
+					. "\n\t"
3938
+					. ' $query_param_type = '
3939
+					. $query_param_type
3940
+					. "\n\t"
3941
+					. ' $original_query_param = '
3942
+					. $original_query_param
3943
+				)
3944
+			);
3945
+		}
3946
+		// check if it's a custom selection
3947
+		if ($this->_custom_selections instanceof CustomSelects
3948
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3949
+		) {
3950
+			return;
3951
+		}
3952
+		// check if has a model name at the beginning
3953
+		// and
3954
+		// check if it's a field on a related model
3955
+		if ($this->extractJoinModelFromQueryParams(
3956
+			$passed_in_query_info,
3957
+			$query_param,
3958
+			$original_query_param,
3959
+			$query_param_type
3960
+		)) {
3961
+			return;
3962
+		}
3963
+
3964
+		// ok so $query_param didn't start with a model name
3965
+		// and we previously confirmed it wasn't a logic query param or field on the current model
3966
+		// it's wack, that's what it is
3967
+		throw new EE_Error(
3968
+			sprintf(
3969
+				esc_html__(
3970
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3971
+					"event_espresso"
3972
+				),
3973
+				$query_param,
3974
+				get_class($this),
3975
+				$query_param_type,
3976
+				$original_query_param
3977
+			)
3978
+		);
3979
+	}
3980
+
3981
+
3982
+	/**
3983
+	 * Extracts any possible join model information from the provided possible_join_string.
3984
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
3985
+	 * parts that should be added to the query.
3986
+	 *
3987
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3988
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
3989
+	 * @param null|string                 $original_query_param
3990
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
3991
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
3992
+	 * @return bool  returns true if a join was added and false if not.
3993
+	 * @throws EE_Error
3994
+	 */
3995
+	private function extractJoinModelFromQueryParams(
3996
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3997
+		$possible_join_string,
3998
+		$original_query_param,
3999
+		$query_parameter_type
4000
+	) {
4001
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4002
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4003
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4004
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4005
+				if ($possible_join_string === '') {
4006
+					// nothing left to $query_param
4007
+					// we should actually end in a field name, not a model like this!
4008
+					throw new EE_Error(
4009
+						sprintf(
4010
+							esc_html__(
4011
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4012
+								"event_espresso"
4013
+							),
4014
+							$possible_join_string,
4015
+							$query_parameter_type,
4016
+							get_class($this),
4017
+							$valid_related_model_name
4018
+						)
4019
+					);
4020
+				}
4021
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4022
+				$related_model_obj->_extract_related_model_info_from_query_param(
4023
+					$possible_join_string,
4024
+					$query_info_carrier,
4025
+					$query_parameter_type,
4026
+					$original_query_param
4027
+				);
4028
+				return true;
4029
+			}
4030
+			if ($possible_join_string === $valid_related_model_name) {
4031
+				$this->_add_join_to_model(
4032
+					$valid_related_model_name,
4033
+					$query_info_carrier,
4034
+					$original_query_param
4035
+				);
4036
+				return true;
4037
+			}
4038
+		}
4039
+		return false;
4040
+	}
4041
+
4042
+
4043
+	/**
4044
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4045
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4046
+	 * @throws EE_Error
4047
+	 */
4048
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4049
+	{
4050
+		if ($this->_custom_selections instanceof CustomSelects
4051
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4052
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4053
+			)
4054
+		) {
4055
+			$original_selects = $this->_custom_selections->originalSelects();
4056
+			foreach ($original_selects as $alias => $select_configuration) {
4057
+				$this->extractJoinModelFromQueryParams(
4058
+					$query_info_carrier,
4059
+					$select_configuration[0],
4060
+					$select_configuration[0],
4061
+					'custom_selects'
4062
+				);
4063
+			}
4064
+		}
4065
+	}
4066
+
4067
+
4068
+
4069
+	/**
4070
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4071
+	 * and store it on $passed_in_query_info
4072
+	 *
4073
+	 * @param string                      $model_name
4074
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4075
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4076
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4077
+	 *                                                          and are adding a join to 'Payment' with the original
4078
+	 *                                                          query param key
4079
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4080
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4081
+	 *                                                          Payment wants to add default query params so that it
4082
+	 *                                                          will know what models to prepend onto its default query
4083
+	 *                                                          params or in case it wants to rename tables (in case
4084
+	 *                                                          there are multiple joins to the same table)
4085
+	 * @return void
4086
+	 * @throws EE_Error
4087
+	 */
4088
+	private function _add_join_to_model(
4089
+		$model_name,
4090
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4091
+		$original_query_param
4092
+	) {
4093
+		$relation_obj = $this->related_settings_for($model_name);
4094
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4095
+		// check if the relation is HABTM, because then we're essentially doing two joins
4096
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4097
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4098
+			$join_model_obj = $relation_obj->get_join_model();
4099
+			// replace the model specified with the join model for this relation chain, whi
4100
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4101
+				$model_name,
4102
+				$join_model_obj->get_this_model_name(),
4103
+				$model_relation_chain
4104
+			);
4105
+			$passed_in_query_info->merge(
4106
+				new EE_Model_Query_Info_Carrier(
4107
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4108
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4109
+				)
4110
+			);
4111
+		}
4112
+		// now just join to the other table pointed to by the relation object, and add its data types
4113
+		$passed_in_query_info->merge(
4114
+			new EE_Model_Query_Info_Carrier(
4115
+				array($model_relation_chain => $model_name),
4116
+				$relation_obj->get_join_statement($model_relation_chain)
4117
+			)
4118
+		);
4119
+	}
4120
+
4121
+
4122
+
4123
+	/**
4124
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4125
+	 *
4126
+	 * @param array $where_params like EEM_Base::get_all
4127
+	 * @return string of SQL
4128
+	 * @throws EE_Error
4129
+	 */
4130
+	private function _construct_where_clause($where_params)
4131
+	{
4132
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4133
+		if ($SQL) {
4134
+			return " WHERE " . $SQL;
4135
+		}
4136
+		return '';
4137
+	}
4138
+
4139
+
4140
+
4141
+	/**
4142
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4143
+	 * and should be passed HAVING parameters, not WHERE parameters
4144
+	 *
4145
+	 * @param array $having_params
4146
+	 * @return string
4147
+	 * @throws EE_Error
4148
+	 */
4149
+	private function _construct_having_clause($having_params)
4150
+	{
4151
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4152
+		if ($SQL) {
4153
+			return " HAVING " . $SQL;
4154
+		}
4155
+		return '';
4156
+	}
4157
+
4158
+
4159
+	/**
4160
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4161
+	 * Event_Meta.meta_value = 'foo'))"
4162
+	 *
4163
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4164
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4165
+	 * @throws EE_Error
4166
+	 * @return string of SQL
4167
+	 */
4168
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4169
+	{
4170
+		$where_clauses = array();
4171
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4172
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4173
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4174
+				switch ($query_param) {
4175
+					case 'not':
4176
+					case 'NOT':
4177
+						$where_clauses[] = "! ("
4178
+										   . $this->_construct_condition_clause_recursive(
4179
+											   $op_and_value_or_sub_condition,
4180
+											   $glue
4181
+										   )
4182
+										   . ")";
4183
+						break;
4184
+					case 'and':
4185
+					case 'AND':
4186
+						$where_clauses[] = " ("
4187
+										   . $this->_construct_condition_clause_recursive(
4188
+											   $op_and_value_or_sub_condition,
4189
+											   ' AND '
4190
+										   )
4191
+										   . ")";
4192
+						break;
4193
+					case 'or':
4194
+					case 'OR':
4195
+						$where_clauses[] = " ("
4196
+										   . $this->_construct_condition_clause_recursive(
4197
+											   $op_and_value_or_sub_condition,
4198
+											   ' OR '
4199
+										   )
4200
+										   . ")";
4201
+						break;
4202
+				}
4203
+			} else {
4204
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4205
+				// if it's not a normal field, maybe it's a custom selection?
4206
+				if (! $field_obj) {
4207
+					if ($this->_custom_selections instanceof CustomSelects) {
4208
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4209
+					} else {
4210
+						throw new EE_Error(sprintf(__(
4211
+							"%s is neither a valid model field name, nor a custom selection",
4212
+							"event_espresso"
4213
+						), $query_param));
4214
+					}
4215
+				}
4216
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4217
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4218
+			}
4219
+		}
4220
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4221
+	}
4222
+
4223
+
4224
+
4225
+	/**
4226
+	 * Takes the input parameter and extract the table name (alias) and column name
4227
+	 *
4228
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4229
+	 * @throws EE_Error
4230
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4231
+	 */
4232
+	private function _deduce_column_name_from_query_param($query_param)
4233
+	{
4234
+		$field = $this->_deduce_field_from_query_param($query_param);
4235
+		if ($field) {
4236
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4237
+				$field->get_model_name(),
4238
+				$query_param
4239
+			);
4240
+			return $table_alias_prefix . $field->get_qualified_column();
4241
+		}
4242
+		if ($this->_custom_selections instanceof CustomSelects
4243
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4244
+		) {
4245
+			// maybe it's custom selection item?
4246
+			// if so, just use it as the "column name"
4247
+			return $query_param;
4248
+		}
4249
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4250
+			? implode(',', $this->_custom_selections->columnAliases())
4251
+			: '';
4252
+		throw new EE_Error(
4253
+			sprintf(
4254
+				__(
4255
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4256
+					"event_espresso"
4257
+				),
4258
+				$query_param,
4259
+				$custom_select_aliases
4260
+			)
4261
+		);
4262
+	}
4263
+
4264
+
4265
+
4266
+	/**
4267
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4268
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4269
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4270
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4271
+	 *
4272
+	 * @param string $condition_query_param_key
4273
+	 * @return string
4274
+	 */
4275
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4276
+	{
4277
+		$pos_of_star = strpos($condition_query_param_key, '*');
4278
+		if ($pos_of_star === false) {
4279
+			return $condition_query_param_key;
4280
+		}
4281
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4282
+		return $condition_query_param_sans_star;
4283
+	}
4284
+
4285
+
4286
+
4287
+	/**
4288
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4289
+	 *
4290
+	 * @param                            mixed      array | string    $op_and_value
4291
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4292
+	 * @throws EE_Error
4293
+	 * @return string
4294
+	 */
4295
+	private function _construct_op_and_value($op_and_value, $field_obj)
4296
+	{
4297
+		if (is_array($op_and_value)) {
4298
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4299
+			if (! $operator) {
4300
+				$php_array_like_string = array();
4301
+				foreach ($op_and_value as $key => $value) {
4302
+					$php_array_like_string[] = "$key=>$value";
4303
+				}
4304
+				throw new EE_Error(
4305
+					sprintf(
4306
+						__(
4307
+							"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))",
4308
+							"event_espresso"
4309
+						),
4310
+						implode(",", $php_array_like_string)
4311
+					)
4312
+				);
4313
+			}
4314
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4315
+		} else {
4316
+			$operator = '=';
4317
+			$value = $op_and_value;
4318
+		}
4319
+		// check to see if the value is actually another field
4320
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4321
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4322
+		}
4323
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4324
+			// in this case, the value should be an array, or at least a comma-separated list
4325
+			// it will need to handle a little differently
4326
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4327
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4328
+			return $operator . SP . $cleaned_value;
4329
+		}
4330
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4331
+			// the value should be an array with count of two.
4332
+			if (count($value) !== 2) {
4333
+				throw new EE_Error(
4334
+					sprintf(
4335
+						__(
4336
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4337
+							'event_espresso'
4338
+						),
4339
+						"BETWEEN"
4340
+					)
4341
+				);
4342
+			}
4343
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4344
+			return $operator . SP . $cleaned_value;
4345
+		}
4346
+		if (in_array($operator, $this->valid_null_style_operators())) {
4347
+			if ($value !== null) {
4348
+				throw new EE_Error(
4349
+					sprintf(
4350
+						__(
4351
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4352
+							"event_espresso"
4353
+						),
4354
+						$value,
4355
+						$operator
4356
+					)
4357
+				);
4358
+			}
4359
+			return $operator;
4360
+		}
4361
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4362
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4363
+			// remove other junk. So just treat it as a string.
4364
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4365
+		}
4366
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4367
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4368
+		}
4369
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4370
+			throw new EE_Error(
4371
+				sprintf(
4372
+					__(
4373
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4374
+						'event_espresso'
4375
+					),
4376
+					$operator,
4377
+					$operator
4378
+				)
4379
+			);
4380
+		}
4381
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4382
+			throw new EE_Error(
4383
+				sprintf(
4384
+					__(
4385
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4386
+						'event_espresso'
4387
+					),
4388
+					$operator,
4389
+					$operator
4390
+				)
4391
+			);
4392
+		}
4393
+		throw new EE_Error(
4394
+			sprintf(
4395
+				__(
4396
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4397
+					"event_espresso"
4398
+				),
4399
+				http_build_query($op_and_value)
4400
+			)
4401
+		);
4402
+	}
4403
+
4404
+
4405
+
4406
+	/**
4407
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4408
+	 *
4409
+	 * @param array                      $values
4410
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4411
+	 *                                              '%s'
4412
+	 * @return string
4413
+	 * @throws EE_Error
4414
+	 */
4415
+	public function _construct_between_value($values, $field_obj)
4416
+	{
4417
+		$cleaned_values = array();
4418
+		foreach ($values as $value) {
4419
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4420
+		}
4421
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4422
+	}
4423
+
4424
+
4425
+
4426
+	/**
4427
+	 * Takes an array or a comma-separated list of $values and cleans them
4428
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4429
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4430
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4431
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4432
+	 *
4433
+	 * @param mixed                      $values    array or comma-separated string
4434
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4435
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4436
+	 * @throws EE_Error
4437
+	 */
4438
+	public function _construct_in_value($values, $field_obj)
4439
+	{
4440
+		// check if the value is a CSV list
4441
+		if (is_string($values)) {
4442
+			// in which case, turn it into an array
4443
+			$values = explode(",", $values);
4444
+		}
4445
+		$cleaned_values = array();
4446
+		foreach ($values as $value) {
4447
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4448
+		}
4449
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4450
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4451
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4452
+		if (empty($cleaned_values)) {
4453
+			$all_fields = $this->field_settings();
4454
+			$a_field = array_shift($all_fields);
4455
+			$main_table = $this->_get_main_table();
4456
+			$cleaned_values[] = "SELECT "
4457
+								. $a_field->get_table_column()
4458
+								. " FROM "
4459
+								. $main_table->get_table_name()
4460
+								. " WHERE FALSE";
4461
+		}
4462
+		return "(" . implode(",", $cleaned_values) . ")";
4463
+	}
4464
+
4465
+
4466
+
4467
+	/**
4468
+	 * @param mixed                      $value
4469
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4470
+	 * @throws EE_Error
4471
+	 * @return false|null|string
4472
+	 */
4473
+	private function _wpdb_prepare_using_field($value, $field_obj)
4474
+	{
4475
+		/** @type WPDB $wpdb */
4476
+		global $wpdb;
4477
+		if ($field_obj instanceof EE_Model_Field_Base) {
4478
+			return $wpdb->prepare(
4479
+				$field_obj->get_wpdb_data_type(),
4480
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4481
+			);
4482
+		} //$field_obj should really just be a data type
4483
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4484
+			throw new EE_Error(
4485
+				sprintf(
4486
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4487
+					$field_obj,
4488
+					implode(",", $this->_valid_wpdb_data_types)
4489
+				)
4490
+			);
4491
+		}
4492
+		return $wpdb->prepare($field_obj, $value);
4493
+	}
4494
+
4495
+
4496
+
4497
+	/**
4498
+	 * Takes the input parameter and finds the model field that it indicates.
4499
+	 *
4500
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4501
+	 * @throws EE_Error
4502
+	 * @return EE_Model_Field_Base
4503
+	 */
4504
+	protected function _deduce_field_from_query_param($query_param_name)
4505
+	{
4506
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4507
+		// which will help us find the database table and column
4508
+		$query_param_parts = explode(".", $query_param_name);
4509
+		if (empty($query_param_parts)) {
4510
+			throw new EE_Error(sprintf(__(
4511
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4512
+				'event_espresso'
4513
+			), $query_param_name));
4514
+		}
4515
+		$number_of_parts = count($query_param_parts);
4516
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4517
+		if ($number_of_parts === 1) {
4518
+			$field_name = $last_query_param_part;
4519
+			$model_obj = $this;
4520
+		} else {// $number_of_parts >= 2
4521
+			// the last part is the column name, and there are only 2parts. therefore...
4522
+			$field_name = $last_query_param_part;
4523
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4524
+		}
4525
+		try {
4526
+			return $model_obj->field_settings_for($field_name);
4527
+		} catch (EE_Error $e) {
4528
+			return null;
4529
+		}
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4536
+	 * alias and column which corresponds to it
4537
+	 *
4538
+	 * @param string $field_name
4539
+	 * @throws EE_Error
4540
+	 * @return string
4541
+	 */
4542
+	public function _get_qualified_column_for_field($field_name)
4543
+	{
4544
+		$all_fields = $this->field_settings();
4545
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4546
+		if ($field) {
4547
+			return $field->get_qualified_column();
4548
+		}
4549
+		throw new EE_Error(
4550
+			sprintf(
4551
+				__(
4552
+					"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.",
4553
+					'event_espresso'
4554
+				),
4555
+				$field_name,
4556
+				get_class($this)
4557
+			)
4558
+		);
4559
+	}
4560
+
4561
+
4562
+
4563
+	/**
4564
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4565
+	 * Example usage:
4566
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4567
+	 *      array(),
4568
+	 *      ARRAY_A,
4569
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4570
+	 *  );
4571
+	 * is equivalent to
4572
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4573
+	 * and
4574
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4575
+	 *      array(
4576
+	 *          array(
4577
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4578
+	 *          ),
4579
+	 *          ARRAY_A,
4580
+	 *          implode(
4581
+	 *              ', ',
4582
+	 *              array_merge(
4583
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4584
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4585
+	 *              )
4586
+	 *          )
4587
+	 *      )
4588
+	 *  );
4589
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4590
+	 *
4591
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4592
+	 *                                            and the one whose fields you are selecting for example: when querying
4593
+	 *                                            tickets model and selecting fields from the tickets model you would
4594
+	 *                                            leave this parameter empty, because no models are needed to join
4595
+	 *                                            between the queried model and the selected one. Likewise when
4596
+	 *                                            querying the datetime model and selecting fields from the tickets
4597
+	 *                                            model, it would also be left empty, because there is a direct
4598
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4599
+	 *                                            them together. However, when querying from the event model and
4600
+	 *                                            selecting fields from the ticket model, you should provide the string
4601
+	 *                                            'Datetime', indicating that the event model must first join to the
4602
+	 *                                            datetime model in order to find its relation to ticket model.
4603
+	 *                                            Also, when querying from the venue model and selecting fields from
4604
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4605
+	 *                                            indicating you need to join the venue model to the event model,
4606
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4607
+	 *                                            This string is used to deduce the prefix that gets added onto the
4608
+	 *                                            models' tables qualified columns
4609
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4610
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4611
+	 *                                            qualified column names
4612
+	 * @return array|string
4613
+	 */
4614
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4615
+	{
4616
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4617
+		$qualified_columns = array();
4618
+		foreach ($this->field_settings() as $field_name => $field) {
4619
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4620
+		}
4621
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4622
+	}
4623
+
4624
+
4625
+
4626
+	/**
4627
+	 * constructs the select use on special limit joins
4628
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4629
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4630
+	 * (as that is typically where the limits would be set).
4631
+	 *
4632
+	 * @param  string       $table_alias The table the select is being built for
4633
+	 * @param  mixed|string $limit       The limit for this select
4634
+	 * @return string                The final select join element for the query.
4635
+	 */
4636
+	public function _construct_limit_join_select($table_alias, $limit)
4637
+	{
4638
+		$SQL = '';
4639
+		foreach ($this->_tables as $table_obj) {
4640
+			if ($table_obj instanceof EE_Primary_Table) {
4641
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4642
+					? $table_obj->get_select_join_limit($limit)
4643
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4644
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4645
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4646
+					? $table_obj->get_select_join_limit_join($limit)
4647
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4648
+			}
4649
+		}
4650
+		return $SQL;
4651
+	}
4652
+
4653
+
4654
+
4655
+	/**
4656
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4657
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4658
+	 *
4659
+	 * @return string SQL
4660
+	 * @throws EE_Error
4661
+	 */
4662
+	public function _construct_internal_join()
4663
+	{
4664
+		$SQL = $this->_get_main_table()->get_table_sql();
4665
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4666
+		return $SQL;
4667
+	}
4668
+
4669
+
4670
+
4671
+	/**
4672
+	 * Constructs the SQL for joining all the tables on this model.
4673
+	 * Normally $alias should be the primary table's alias, but in cases where
4674
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4675
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4676
+	 * alias, this will construct SQL like:
4677
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4678
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4679
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4680
+	 *
4681
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4682
+	 * @return string
4683
+	 */
4684
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4685
+	{
4686
+		$SQL = '';
4687
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4688
+		foreach ($this->_tables as $table_obj) {
4689
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4690
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4691
+					// so we're joining to this table, meaning the table is already in
4692
+					// the FROM statement, BUT the primary table isn't. So we want
4693
+					// to add the inverse join sql
4694
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4695
+				} else {
4696
+					// just add a regular JOIN to this table from the primary table
4697
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4698
+				}
4699
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4700
+		}
4701
+		return $SQL;
4702
+	}
4703
+
4704
+
4705
+
4706
+	/**
4707
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4708
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4709
+	 * their data type (eg, '%s', '%d', etc)
4710
+	 *
4711
+	 * @return array
4712
+	 */
4713
+	public function _get_data_types()
4714
+	{
4715
+		$data_types = array();
4716
+		foreach ($this->field_settings() as $field_obj) {
4717
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4718
+			/** @var $field_obj EE_Model_Field_Base */
4719
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4720
+		}
4721
+		return $data_types;
4722
+	}
4723
+
4724
+
4725
+
4726
+	/**
4727
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4728
+	 *
4729
+	 * @param string $model_name
4730
+	 * @throws EE_Error
4731
+	 * @return EEM_Base
4732
+	 */
4733
+	public function get_related_model_obj($model_name)
4734
+	{
4735
+		$model_classname = "EEM_" . $model_name;
4736
+		if (! class_exists($model_classname)) {
4737
+			throw new EE_Error(sprintf(__(
4738
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4739
+				'event_espresso'
4740
+			), $model_name, $model_classname));
4741
+		}
4742
+		return call_user_func($model_classname . "::instance");
4743
+	}
4744
+
4745
+
4746
+
4747
+	/**
4748
+	 * Returns the array of EE_ModelRelations for this model.
4749
+	 *
4750
+	 * @return EE_Model_Relation_Base[]
4751
+	 */
4752
+	public function relation_settings()
4753
+	{
4754
+		return $this->_model_relations;
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4761
+	 * because without THOSE models, this model probably doesn't have much purpose.
4762
+	 * (Eg, without an event, datetimes have little purpose.)
4763
+	 *
4764
+	 * @return EE_Belongs_To_Relation[]
4765
+	 */
4766
+	public function belongs_to_relations()
4767
+	{
4768
+		$belongs_to_relations = array();
4769
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4770
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4771
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4772
+			}
4773
+		}
4774
+		return $belongs_to_relations;
4775
+	}
4776
+
4777
+
4778
+
4779
+	/**
4780
+	 * Returns the specified EE_Model_Relation, or throws an exception
4781
+	 *
4782
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4783
+	 * @throws EE_Error
4784
+	 * @return EE_Model_Relation_Base
4785
+	 */
4786
+	public function related_settings_for($relation_name)
4787
+	{
4788
+		$relatedModels = $this->relation_settings();
4789
+		if (! array_key_exists($relation_name, $relatedModels)) {
4790
+			throw new EE_Error(
4791
+				sprintf(
4792
+					__(
4793
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4794
+						'event_espresso'
4795
+					),
4796
+					$relation_name,
4797
+					$this->_get_class_name(),
4798
+					implode(', ', array_keys($relatedModels))
4799
+				)
4800
+			);
4801
+		}
4802
+		return $relatedModels[ $relation_name ];
4803
+	}
4804
+
4805
+
4806
+
4807
+	/**
4808
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4809
+	 * fields
4810
+	 *
4811
+	 * @param string $fieldName
4812
+	 * @param boolean $include_db_only_fields
4813
+	 * @throws EE_Error
4814
+	 * @return EE_Model_Field_Base
4815
+	 */
4816
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4817
+	{
4818
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4819
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4820
+			throw new EE_Error(sprintf(
4821
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4822
+				$fieldName,
4823
+				get_class($this)
4824
+			));
4825
+		}
4826
+		return $fieldSettings[ $fieldName ];
4827
+	}
4828
+
4829
+
4830
+
4831
+	/**
4832
+	 * Checks if this field exists on this model
4833
+	 *
4834
+	 * @param string $fieldName a key in the model's _field_settings array
4835
+	 * @return boolean
4836
+	 */
4837
+	public function has_field($fieldName)
4838
+	{
4839
+		$fieldSettings = $this->field_settings(true);
4840
+		if (isset($fieldSettings[ $fieldName ])) {
4841
+			return true;
4842
+		}
4843
+		return false;
4844
+	}
4845
+
4846
+
4847
+
4848
+	/**
4849
+	 * Returns whether or not this model has a relation to the specified model
4850
+	 *
4851
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4852
+	 * @return boolean
4853
+	 */
4854
+	public function has_relation($relation_name)
4855
+	{
4856
+		$relations = $this->relation_settings();
4857
+		if (isset($relations[ $relation_name ])) {
4858
+			return true;
4859
+		}
4860
+		return false;
4861
+	}
4862
+
4863
+
4864
+
4865
+	/**
4866
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4867
+	 * Eg, on EE_Answer that would be ANS_ID field object
4868
+	 *
4869
+	 * @param $field_obj
4870
+	 * @return boolean
4871
+	 */
4872
+	public function is_primary_key_field($field_obj)
4873
+	{
4874
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4875
+	}
4876
+
4877
+
4878
+
4879
+	/**
4880
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4881
+	 * Eg, on EE_Answer that would be ANS_ID field object
4882
+	 *
4883
+	 * @return EE_Model_Field_Base
4884
+	 * @throws EE_Error
4885
+	 */
4886
+	public function get_primary_key_field()
4887
+	{
4888
+		if ($this->_primary_key_field === null) {
4889
+			foreach ($this->field_settings(true) as $field_obj) {
4890
+				if ($this->is_primary_key_field($field_obj)) {
4891
+					$this->_primary_key_field = $field_obj;
4892
+					break;
4893
+				}
4894
+			}
4895
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4896
+				throw new EE_Error(sprintf(
4897
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4898
+					get_class($this)
4899
+				));
4900
+			}
4901
+		}
4902
+		return $this->_primary_key_field;
4903
+	}
4904
+
4905
+
4906
+
4907
+	/**
4908
+	 * Returns whether or not not there is a primary key on this model.
4909
+	 * Internally does some caching.
4910
+	 *
4911
+	 * @return boolean
4912
+	 */
4913
+	public function has_primary_key_field()
4914
+	{
4915
+		if ($this->_has_primary_key_field === null) {
4916
+			try {
4917
+				$this->get_primary_key_field();
4918
+				$this->_has_primary_key_field = true;
4919
+			} catch (EE_Error $e) {
4920
+				$this->_has_primary_key_field = false;
4921
+			}
4922
+		}
4923
+		return $this->_has_primary_key_field;
4924
+	}
4925
+
4926
+
4927
+
4928
+	/**
4929
+	 * Finds the first field of type $field_class_name.
4930
+	 *
4931
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4932
+	 *                                 EE_Foreign_Key_Field, etc
4933
+	 * @return EE_Model_Field_Base or null if none is found
4934
+	 */
4935
+	public function get_a_field_of_type($field_class_name)
4936
+	{
4937
+		foreach ($this->field_settings() as $field) {
4938
+			if ($field instanceof $field_class_name) {
4939
+				return $field;
4940
+			}
4941
+		}
4942
+		return null;
4943
+	}
4944
+
4945
+
4946
+
4947
+	/**
4948
+	 * Gets a foreign key field pointing to model.
4949
+	 *
4950
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4951
+	 * @return EE_Foreign_Key_Field_Base
4952
+	 * @throws EE_Error
4953
+	 */
4954
+	public function get_foreign_key_to($model_name)
4955
+	{
4956
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4957
+			foreach ($this->field_settings() as $field) {
4958
+				if ($field instanceof EE_Foreign_Key_Field_Base
4959
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4960
+				) {
4961
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
4962
+					break;
4963
+				}
4964
+			}
4965
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4966
+				throw new EE_Error(sprintf(__(
4967
+					"There is no foreign key field pointing to model %s on model %s",
4968
+					'event_espresso'
4969
+				), $model_name, get_class($this)));
4970
+			}
4971
+		}
4972
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
4973
+	}
4974
+
4975
+
4976
+
4977
+	/**
4978
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4979
+	 *
4980
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4981
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4982
+	 *                            Either one works
4983
+	 * @return string
4984
+	 */
4985
+	public function get_table_for_alias($table_alias)
4986
+	{
4987
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4988
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
4989
+	}
4990
+
4991
+
4992
+
4993
+	/**
4994
+	 * Returns a flat array of all field son this model, instead of organizing them
4995
+	 * by table_alias as they are in the constructor.
4996
+	 *
4997
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4998
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4999
+	 */
5000
+	public function field_settings($include_db_only_fields = false)
5001
+	{
5002
+		if ($include_db_only_fields) {
5003
+			if ($this->_cached_fields === null) {
5004
+				$this->_cached_fields = array();
5005
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5006
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5007
+						$this->_cached_fields[ $field_name ] = $field_obj;
5008
+					}
5009
+				}
5010
+			}
5011
+			return $this->_cached_fields;
5012
+		}
5013
+		if ($this->_cached_fields_non_db_only === null) {
5014
+			$this->_cached_fields_non_db_only = array();
5015
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5016
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5017
+					/** @var $field_obj EE_Model_Field_Base */
5018
+					if (! $field_obj->is_db_only_field()) {
5019
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5020
+					}
5021
+				}
5022
+			}
5023
+		}
5024
+		return $this->_cached_fields_non_db_only;
5025
+	}
5026
+
5027
+
5028
+
5029
+	/**
5030
+	 *        cycle though array of attendees and create objects out of each item
5031
+	 *
5032
+	 * @access        private
5033
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5034
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5035
+	 *                           numerically indexed)
5036
+	 * @throws EE_Error
5037
+	 */
5038
+	protected function _create_objects($rows = array())
5039
+	{
5040
+		$array_of_objects = array();
5041
+		if (empty($rows)) {
5042
+			return array();
5043
+		}
5044
+		$count_if_model_has_no_primary_key = 0;
5045
+		$has_primary_key = $this->has_primary_key_field();
5046
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5047
+		foreach ((array) $rows as $row) {
5048
+			if (empty($row)) {
5049
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5050
+				return array();
5051
+			}
5052
+			// check if we've already set this object in the results array,
5053
+			// in which case there's no need to process it further (again)
5054
+			if ($has_primary_key) {
5055
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5056
+					$row,
5057
+					$primary_key_field->get_qualified_column(),
5058
+					$primary_key_field->get_table_column()
5059
+				);
5060
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5061
+					continue;
5062
+				}
5063
+			}
5064
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5065
+			if (! $classInstance) {
5066
+				throw new EE_Error(
5067
+					sprintf(
5068
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5069
+						$this->get_this_model_name(),
5070
+						http_build_query($row)
5071
+					)
5072
+				);
5073
+			}
5074
+			// set the timezone on the instantiated objects
5075
+			$classInstance->set_timezone($this->_timezone);
5076
+			// make sure if there is any timezone setting present that we set the timezone for the object
5077
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5078
+			$array_of_objects[ $key ] = $classInstance;
5079
+			// also, for all the relations of type BelongsTo, see if we can cache
5080
+			// those related models
5081
+			// (we could do this for other relations too, but if there are conditions
5082
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5083
+			// so it requires a little more thought than just caching them immediately...)
5084
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5085
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5086
+					// check if this model's INFO is present. If so, cache it on the model
5087
+					$other_model = $relation_obj->get_other_model();
5088
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5089
+					// if we managed to make a model object from the results, cache it on the main model object
5090
+					if ($other_model_obj_maybe) {
5091
+						// set timezone on these other model objects if they are present
5092
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5093
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5094
+					}
5095
+				}
5096
+			}
5097
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5098
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5099
+			// the field in the CustomSelects object
5100
+			if ($this->_custom_selections instanceof CustomSelects) {
5101
+				$classInstance->setCustomSelectsValues(
5102
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5103
+				);
5104
+			}
5105
+		}
5106
+		return $array_of_objects;
5107
+	}
5108
+
5109
+
5110
+	/**
5111
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5112
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5113
+	 *
5114
+	 * @param array $db_results_row
5115
+	 * @return array
5116
+	 */
5117
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5118
+	{
5119
+		$results = array();
5120
+		if ($this->_custom_selections instanceof CustomSelects) {
5121
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5122
+				if (isset($db_results_row[ $alias ])) {
5123
+					$results[ $alias ] = $this->convertValueToDataType(
5124
+						$db_results_row[ $alias ],
5125
+						$this->_custom_selections->getDataTypeForAlias($alias)
5126
+					);
5127
+				}
5128
+			}
5129
+		}
5130
+		return $results;
5131
+	}
5132
+
5133
+
5134
+	/**
5135
+	 * This will set the value for the given alias
5136
+	 * @param string $value
5137
+	 * @param string $datatype (one of %d, %s, %f)
5138
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5139
+	 */
5140
+	protected function convertValueToDataType($value, $datatype)
5141
+	{
5142
+		switch ($datatype) {
5143
+			case '%f':
5144
+				return (float) $value;
5145
+			case '%d':
5146
+				return (int) $value;
5147
+			default:
5148
+				return (string) $value;
5149
+		}
5150
+	}
5151
+
5152
+
5153
+	/**
5154
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5155
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5156
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5157
+	 * object (as set in the model_field!).
5158
+	 *
5159
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5160
+	 */
5161
+	public function create_default_object()
5162
+	{
5163
+		$this_model_fields_and_values = array();
5164
+		// setup the row using default values;
5165
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5166
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5167
+		}
5168
+		$className = $this->_get_class_name();
5169
+		$classInstance = EE_Registry::instance()
5170
+									->load_class($className, array($this_model_fields_and_values), false, false);
5171
+		return $classInstance;
5172
+	}
5173
+
5174
+
5175
+
5176
+	/**
5177
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5178
+	 *                             or an stdClass where each property is the name of a column,
5179
+	 * @return EE_Base_Class
5180
+	 * @throws EE_Error
5181
+	 */
5182
+	public function instantiate_class_from_array_or_object($cols_n_values)
5183
+	{
5184
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5185
+			$cols_n_values = get_object_vars($cols_n_values);
5186
+		}
5187
+		$primary_key = null;
5188
+		// make sure the array only has keys that are fields/columns on this model
5189
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5190
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5191
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5192
+		}
5193
+		$className = $this->_get_class_name();
5194
+		// check we actually found results that we can use to build our model object
5195
+		// if not, return null
5196
+		if ($this->has_primary_key_field()) {
5197
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5198
+				return null;
5199
+			}
5200
+		} elseif ($this->unique_indexes()) {
5201
+			$first_column = reset($this_model_fields_n_values);
5202
+			if (empty($first_column)) {
5203
+				return null;
5204
+			}
5205
+		}
5206
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5207
+		if ($primary_key) {
5208
+			$classInstance = $this->get_from_entity_map($primary_key);
5209
+			if (! $classInstance) {
5210
+				$classInstance = EE_Registry::instance()
5211
+											->load_class(
5212
+												$className,
5213
+												array($this_model_fields_n_values, $this->_timezone),
5214
+												true,
5215
+												false
5216
+											);
5217
+				// add this new object to the entity map
5218
+				$classInstance = $this->add_to_entity_map($classInstance);
5219
+			}
5220
+		} else {
5221
+			$classInstance = EE_Registry::instance()
5222
+										->load_class(
5223
+											$className,
5224
+											array($this_model_fields_n_values, $this->_timezone),
5225
+											true,
5226
+											false
5227
+										);
5228
+		}
5229
+		return $classInstance;
5230
+	}
5231
+
5232
+
5233
+
5234
+	/**
5235
+	 * Gets the model object from the  entity map if it exists
5236
+	 *
5237
+	 * @param int|string $id the ID of the model object
5238
+	 * @return EE_Base_Class
5239
+	 */
5240
+	public function get_from_entity_map($id)
5241
+	{
5242
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5243
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5244
+	}
5245
+
5246
+
5247
+
5248
+	/**
5249
+	 * add_to_entity_map
5250
+	 * Adds the object to the model's entity mappings
5251
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5252
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5253
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5254
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5255
+	 *        then this method should be called immediately after the update query
5256
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5257
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5258
+	 *
5259
+	 * @param    EE_Base_Class $object
5260
+	 * @throws EE_Error
5261
+	 * @return \EE_Base_Class
5262
+	 */
5263
+	public function add_to_entity_map(EE_Base_Class $object)
5264
+	{
5265
+		$className = $this->_get_class_name();
5266
+		if (! $object instanceof $className) {
5267
+			throw new EE_Error(sprintf(
5268
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5269
+				is_object($object) ? get_class($object) : $object,
5270
+				$className
5271
+			));
5272
+		}
5273
+		/** @var $object EE_Base_Class */
5274
+		if (! $object->ID()) {
5275
+			throw new EE_Error(sprintf(__(
5276
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5277
+				"event_espresso"
5278
+			), get_class($this)));
5279
+		}
5280
+		// double check it's not already there
5281
+		$classInstance = $this->get_from_entity_map($object->ID());
5282
+		if ($classInstance) {
5283
+			return $classInstance;
5284
+		}
5285
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5286
+		return $object;
5287
+	}
5288
+
5289
+
5290
+
5291
+	/**
5292
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5293
+	 * if no identifier is provided, then the entire entity map is emptied
5294
+	 *
5295
+	 * @param int|string $id the ID of the model object
5296
+	 * @return boolean
5297
+	 */
5298
+	public function clear_entity_map($id = null)
5299
+	{
5300
+		if (empty($id)) {
5301
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5302
+			return true;
5303
+		}
5304
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5305
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5306
+			return true;
5307
+		}
5308
+		return false;
5309
+	}
5310
+
5311
+
5312
+
5313
+	/**
5314
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5315
+	 * Given an array where keys are column (or column alias) names and values,
5316
+	 * returns an array of their corresponding field names and database values
5317
+	 *
5318
+	 * @param array $cols_n_values
5319
+	 * @return array
5320
+	 */
5321
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5322
+	{
5323
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
+	}
5325
+
5326
+
5327
+
5328
+	/**
5329
+	 * _deduce_fields_n_values_from_cols_n_values
5330
+	 * Given an array where keys are column (or column alias) names and values,
5331
+	 * returns an array of their corresponding field names and database values
5332
+	 *
5333
+	 * @param string $cols_n_values
5334
+	 * @return array
5335
+	 */
5336
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5337
+	{
5338
+		$this_model_fields_n_values = array();
5339
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5340
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5341
+				$cols_n_values,
5342
+				$table_obj->get_fully_qualified_pk_column(),
5343
+				$table_obj->get_pk_column()
5344
+			);
5345
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5346
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5347
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5348
+					if (! $field_obj->is_db_only_field()) {
5349
+						// prepare field as if its coming from db
5350
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5351
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5352
+					}
5353
+				}
5354
+			} else {
5355
+				// the table's rows existed. Use their values
5356
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5357
+					if (! $field_obj->is_db_only_field()) {
5358
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5359
+							$cols_n_values,
5360
+							$field_obj->get_qualified_column(),
5361
+							$field_obj->get_table_column()
5362
+						);
5363
+					}
5364
+				}
5365
+			}
5366
+		}
5367
+		return $this_model_fields_n_values;
5368
+	}
5369
+
5370
+
5371
+
5372
+	/**
5373
+	 * @param $cols_n_values
5374
+	 * @param $qualified_column
5375
+	 * @param $regular_column
5376
+	 * @return null
5377
+	 */
5378
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5379
+	{
5380
+		$value = null;
5381
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5382
+		// does the field on the model relate to this column retrieved from the db?
5383
+		// or is it a db-only field? (not relating to the model)
5384
+		if (isset($cols_n_values[ $qualified_column ])) {
5385
+			$value = $cols_n_values[ $qualified_column ];
5386
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5387
+			$value = $cols_n_values[ $regular_column ];
5388
+		}
5389
+		return $value;
5390
+	}
5391
+
5392
+
5393
+
5394
+	/**
5395
+	 * refresh_entity_map_from_db
5396
+	 * Makes sure the model object in the entity map at $id assumes the values
5397
+	 * of the database (opposite of EE_base_Class::save())
5398
+	 *
5399
+	 * @param int|string $id
5400
+	 * @return EE_Base_Class
5401
+	 * @throws EE_Error
5402
+	 */
5403
+	public function refresh_entity_map_from_db($id)
5404
+	{
5405
+		$obj_in_map = $this->get_from_entity_map($id);
5406
+		if ($obj_in_map) {
5407
+			$wpdb_results = $this->_get_all_wpdb_results(
5408
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5409
+			);
5410
+			if ($wpdb_results && is_array($wpdb_results)) {
5411
+				$one_row = reset($wpdb_results);
5412
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5413
+					$obj_in_map->set_from_db($field_name, $db_value);
5414
+				}
5415
+				// clear the cache of related model objects
5416
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5417
+					$obj_in_map->clear_cache($relation_name, null, true);
5418
+				}
5419
+			}
5420
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5421
+			return $obj_in_map;
5422
+		}
5423
+		return $this->get_one_by_ID($id);
5424
+	}
5425
+
5426
+
5427
+
5428
+	/**
5429
+	 * refresh_entity_map_with
5430
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5431
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5432
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5433
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5434
+	 *
5435
+	 * @param int|string    $id
5436
+	 * @param EE_Base_Class $replacing_model_obj
5437
+	 * @return \EE_Base_Class
5438
+	 * @throws EE_Error
5439
+	 */
5440
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5441
+	{
5442
+		$obj_in_map = $this->get_from_entity_map($id);
5443
+		if ($obj_in_map) {
5444
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5445
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5446
+					$obj_in_map->set($field_name, $value);
5447
+				}
5448
+				// make the model object in the entity map's cache match the $replacing_model_obj
5449
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5450
+					$obj_in_map->clear_cache($relation_name, null, true);
5451
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5452
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5453
+					}
5454
+				}
5455
+			}
5456
+			return $obj_in_map;
5457
+		}
5458
+		$this->add_to_entity_map($replacing_model_obj);
5459
+		return $replacing_model_obj;
5460
+	}
5461
+
5462
+
5463
+
5464
+	/**
5465
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5466
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5467
+	 * require_once($this->_getClassName().".class.php");
5468
+	 *
5469
+	 * @return string
5470
+	 */
5471
+	private function _get_class_name()
5472
+	{
5473
+		return "EE_" . $this->get_this_model_name();
5474
+	}
5475
+
5476
+
5477
+
5478
+	/**
5479
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5480
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5481
+	 * it would be 'Events'.
5482
+	 *
5483
+	 * @param int $quantity
5484
+	 * @return string
5485
+	 */
5486
+	public function item_name($quantity = 1)
5487
+	{
5488
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5489
+	}
5490
+
5491
+
5492
+
5493
+	/**
5494
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5495
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5496
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5497
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5498
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5499
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5500
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5501
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5502
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5503
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5504
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5505
+	 *        return $previousReturnValue.$returnString;
5506
+	 * }
5507
+	 * require('EEM_Answer.model.php');
5508
+	 * $answer=EEM_Answer::instance();
5509
+	 * echo $answer->my_callback('monkeys',100);
5510
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5511
+	 *
5512
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5513
+	 * @param array  $args       array of original arguments passed to the function
5514
+	 * @throws EE_Error
5515
+	 * @return mixed whatever the plugin which calls add_filter decides
5516
+	 */
5517
+	public function __call($methodName, $args)
5518
+	{
5519
+		$className = get_class($this);
5520
+		$tagName = "FHEE__{$className}__{$methodName}";
5521
+		if (! has_filter($tagName)) {
5522
+			throw new EE_Error(
5523
+				sprintf(
5524
+					__(
5525
+						'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 );',
5526
+						'event_espresso'
5527
+					),
5528
+					$methodName,
5529
+					$className,
5530
+					$tagName,
5531
+					'<br />'
5532
+				)
5533
+			);
5534
+		}
5535
+		return apply_filters($tagName, null, $this, $args);
5536
+	}
5537
+
5538
+
5539
+
5540
+	/**
5541
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5542
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5543
+	 *
5544
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5545
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5546
+	 *                                                       the object's class name
5547
+	 *                                                       or object's ID
5548
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5549
+	 *                                                       exists in the database. If it does not, we add it
5550
+	 * @throws EE_Error
5551
+	 * @return EE_Base_Class
5552
+	 */
5553
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5554
+	{
5555
+		$className = $this->_get_class_name();
5556
+		if ($base_class_obj_or_id instanceof $className) {
5557
+			$model_object = $base_class_obj_or_id;
5558
+		} else {
5559
+			$primary_key_field = $this->get_primary_key_field();
5560
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5561
+				&& (
5562
+					is_int($base_class_obj_or_id)
5563
+					|| is_string($base_class_obj_or_id)
5564
+				)
5565
+			) {
5566
+				// assume it's an ID.
5567
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5568
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5569
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5570
+				&& is_string($base_class_obj_or_id)
5571
+			) {
5572
+				// assume its a string representation of the object
5573
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5574
+			} else {
5575
+				throw new EE_Error(
5576
+					sprintf(
5577
+						__(
5578
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5579
+							'event_espresso'
5580
+						),
5581
+						$base_class_obj_or_id,
5582
+						$this->_get_class_name(),
5583
+						print_r($base_class_obj_or_id, true)
5584
+					)
5585
+				);
5586
+			}
5587
+		}
5588
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5589
+			$model_object->save();
5590
+		}
5591
+		return $model_object;
5592
+	}
5593
+
5594
+
5595
+
5596
+	/**
5597
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5598
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5599
+	 * returns it ID.
5600
+	 *
5601
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5602
+	 * @return int|string depending on the type of this model object's ID
5603
+	 * @throws EE_Error
5604
+	 */
5605
+	public function ensure_is_ID($base_class_obj_or_id)
5606
+	{
5607
+		$className = $this->_get_class_name();
5608
+		if ($base_class_obj_or_id instanceof $className) {
5609
+			/** @var $base_class_obj_or_id EE_Base_Class */
5610
+			$id = $base_class_obj_or_id->ID();
5611
+		} elseif (is_int($base_class_obj_or_id)) {
5612
+			// assume it's an ID
5613
+			$id = $base_class_obj_or_id;
5614
+		} elseif (is_string($base_class_obj_or_id)) {
5615
+			// assume its a string representation of the object
5616
+			$id = $base_class_obj_or_id;
5617
+		} else {
5618
+			throw new EE_Error(sprintf(
5619
+				__(
5620
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5621
+					'event_espresso'
5622
+				),
5623
+				$base_class_obj_or_id,
5624
+				$this->_get_class_name(),
5625
+				print_r($base_class_obj_or_id, true)
5626
+			));
5627
+		}
5628
+		return $id;
5629
+	}
5630
+
5631
+
5632
+
5633
+	/**
5634
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5635
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5636
+	 * been sanitized and converted into the appropriate domain.
5637
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5638
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5639
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5640
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5641
+	 * $EVT = EEM_Event::instance(); $old_setting =
5642
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5643
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5644
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5645
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5646
+	 *
5647
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5648
+	 * @return void
5649
+	 */
5650
+	public function assume_values_already_prepared_by_model_object(
5651
+		$values_already_prepared = self::not_prepared_by_model_object
5652
+	) {
5653
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5654
+	}
5655
+
5656
+
5657
+
5658
+	/**
5659
+	 * Read comments for assume_values_already_prepared_by_model_object()
5660
+	 *
5661
+	 * @return int
5662
+	 */
5663
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5664
+	{
5665
+		return $this->_values_already_prepared_by_model_object;
5666
+	}
5667
+
5668
+
5669
+
5670
+	/**
5671
+	 * Gets all the indexes on this model
5672
+	 *
5673
+	 * @return EE_Index[]
5674
+	 */
5675
+	public function indexes()
5676
+	{
5677
+		return $this->_indexes;
5678
+	}
5679
+
5680
+
5681
+
5682
+	/**
5683
+	 * Gets all the Unique Indexes on this model
5684
+	 *
5685
+	 * @return EE_Unique_Index[]
5686
+	 */
5687
+	public function unique_indexes()
5688
+	{
5689
+		$unique_indexes = array();
5690
+		foreach ($this->_indexes as $name => $index) {
5691
+			if ($index instanceof EE_Unique_Index) {
5692
+				$unique_indexes [ $name ] = $index;
5693
+			}
5694
+		}
5695
+		return $unique_indexes;
5696
+	}
5697
+
5698
+
5699
+
5700
+	/**
5701
+	 * Gets all the fields which, when combined, make the primary key.
5702
+	 * This is usually just an array with 1 element (the primary key), but in cases
5703
+	 * where there is no primary key, it's a combination of fields as defined
5704
+	 * on a primary index
5705
+	 *
5706
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5707
+	 * @throws EE_Error
5708
+	 */
5709
+	public function get_combined_primary_key_fields()
5710
+	{
5711
+		foreach ($this->indexes() as $index) {
5712
+			if ($index instanceof EE_Primary_Key_Index) {
5713
+				return $index->fields();
5714
+			}
5715
+		}
5716
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5717
+	}
5718
+
5719
+
5720
+
5721
+	/**
5722
+	 * Used to build a primary key string (when the model has no primary key),
5723
+	 * which can be used a unique string to identify this model object.
5724
+	 *
5725
+	 * @param array $cols_n_values keys are field names, values are their values
5726
+	 * @return string
5727
+	 * @throws EE_Error
5728
+	 */
5729
+	public function get_index_primary_key_string($cols_n_values)
5730
+	{
5731
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5732
+			$cols_n_values,
5733
+			$this->get_combined_primary_key_fields()
5734
+		);
5735
+		return http_build_query($cols_n_values_for_primary_key_index);
5736
+	}
5737
+
5738
+
5739
+
5740
+	/**
5741
+	 * Gets the field values from the primary key string
5742
+	 *
5743
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5744
+	 * @param string $index_primary_key_string
5745
+	 * @return null|array
5746
+	 * @throws EE_Error
5747
+	 */
5748
+	public function parse_index_primary_key_string($index_primary_key_string)
5749
+	{
5750
+		$key_fields = $this->get_combined_primary_key_fields();
5751
+		// check all of them are in the $id
5752
+		$key_vals_in_combined_pk = array();
5753
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5754
+		foreach ($key_fields as $key_field_name => $field_obj) {
5755
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5756
+				return null;
5757
+			}
5758
+		}
5759
+		return $key_vals_in_combined_pk;
5760
+	}
5761
+
5762
+
5763
+
5764
+	/**
5765
+	 * verifies that an array of key-value pairs for model fields has a key
5766
+	 * for each field comprising the primary key index
5767
+	 *
5768
+	 * @param array $key_vals
5769
+	 * @return boolean
5770
+	 * @throws EE_Error
5771
+	 */
5772
+	public function has_all_combined_primary_key_fields($key_vals)
5773
+	{
5774
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5775
+		foreach ($keys_it_should_have as $key) {
5776
+			if (! isset($key_vals[ $key ])) {
5777
+				return false;
5778
+			}
5779
+		}
5780
+		return true;
5781
+	}
5782
+
5783
+
5784
+
5785
+	/**
5786
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5787
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5788
+	 *
5789
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5790
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5791
+	 * @throws EE_Error
5792
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5793
+	 *                                                              indexed)
5794
+	 */
5795
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5796
+	{
5797
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5798
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5799
+		} elseif (is_array($model_object_or_attributes_array)) {
5800
+			$attributes_array = $model_object_or_attributes_array;
5801
+		} else {
5802
+			throw new EE_Error(sprintf(__(
5803
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5804
+				"event_espresso"
5805
+			), $model_object_or_attributes_array));
5806
+		}
5807
+		// even copies obviously won't have the same ID, so remove the primary key
5808
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5809
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5810
+			unset($attributes_array[ $this->primary_key_name() ]);
5811
+		}
5812
+		if (isset($query_params[0])) {
5813
+			$query_params[0] = array_merge($attributes_array, $query_params);
5814
+		} else {
5815
+			$query_params[0] = $attributes_array;
5816
+		}
5817
+		return $this->get_all($query_params);
5818
+	}
5819
+
5820
+
5821
+
5822
+	/**
5823
+	 * Gets the first copy we find. See get_all_copies for more details
5824
+	 *
5825
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5826
+	 * @param array $query_params
5827
+	 * @return EE_Base_Class
5828
+	 * @throws EE_Error
5829
+	 */
5830
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5831
+	{
5832
+		if (! is_array($query_params)) {
5833
+			EE_Error::doing_it_wrong(
5834
+				'EEM_Base::get_one_copy',
5835
+				sprintf(
5836
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5837
+					gettype($query_params)
5838
+				),
5839
+				'4.6.0'
5840
+			);
5841
+			$query_params = array();
5842
+		}
5843
+		$query_params['limit'] = 1;
5844
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5845
+		if (is_array($copies)) {
5846
+			return array_shift($copies);
5847
+		}
5848
+		return null;
5849
+	}
5850
+
5851
+
5852
+
5853
+	/**
5854
+	 * Updates the item with the specified id. Ignores default query parameters because
5855
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5856
+	 *
5857
+	 * @param array      $fields_n_values keys are field names, values are their new values
5858
+	 * @param int|string $id              the value of the primary key to update
5859
+	 * @return int number of rows updated
5860
+	 * @throws EE_Error
5861
+	 */
5862
+	public function update_by_ID($fields_n_values, $id)
5863
+	{
5864
+		$query_params = array(
5865
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5866
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5867
+		);
5868
+		return $this->update($fields_n_values, $query_params);
5869
+	}
5870
+
5871
+
5872
+
5873
+	/**
5874
+	 * Changes an operator which was supplied to the models into one usable in SQL
5875
+	 *
5876
+	 * @param string $operator_supplied
5877
+	 * @return string an operator which can be used in SQL
5878
+	 * @throws EE_Error
5879
+	 */
5880
+	private function _prepare_operator_for_sql($operator_supplied)
5881
+	{
5882
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5883
+			: null;
5884
+		if ($sql_operator) {
5885
+			return $sql_operator;
5886
+		}
5887
+		throw new EE_Error(
5888
+			sprintf(
5889
+				__(
5890
+					"The operator '%s' is not in the list of valid operators: %s",
5891
+					"event_espresso"
5892
+				),
5893
+				$operator_supplied,
5894
+				implode(",", array_keys($this->_valid_operators))
5895
+			)
5896
+		);
5897
+	}
5898
+
5899
+
5900
+
5901
+	/**
5902
+	 * Gets the valid operators
5903
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5904
+	 */
5905
+	public function valid_operators()
5906
+	{
5907
+		return $this->_valid_operators;
5908
+	}
5909
+
5910
+
5911
+
5912
+	/**
5913
+	 * Gets the between-style operators (take 2 arguments).
5914
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5915
+	 */
5916
+	public function valid_between_style_operators()
5917
+	{
5918
+		return array_intersect(
5919
+			$this->valid_operators(),
5920
+			$this->_between_style_operators
5921
+		);
5922
+	}
5923
+
5924
+	/**
5925
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5926
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5927
+	 */
5928
+	public function valid_like_style_operators()
5929
+	{
5930
+		return array_intersect(
5931
+			$this->valid_operators(),
5932
+			$this->_like_style_operators
5933
+		);
5934
+	}
5935
+
5936
+	/**
5937
+	 * Gets the "in"-style operators
5938
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5939
+	 */
5940
+	public function valid_in_style_operators()
5941
+	{
5942
+		return array_intersect(
5943
+			$this->valid_operators(),
5944
+			$this->_in_style_operators
5945
+		);
5946
+	}
5947
+
5948
+	/**
5949
+	 * Gets the "null"-style operators (accept no arguments)
5950
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5951
+	 */
5952
+	public function valid_null_style_operators()
5953
+	{
5954
+		return array_intersect(
5955
+			$this->valid_operators(),
5956
+			$this->_null_style_operators
5957
+		);
5958
+	}
5959
+
5960
+	/**
5961
+	 * Gets an array where keys are the primary keys and values are their 'names'
5962
+	 * (as determined by the model object's name() function, which is often overridden)
5963
+	 *
5964
+	 * @param array $query_params like get_all's
5965
+	 * @return string[]
5966
+	 * @throws EE_Error
5967
+	 */
5968
+	public function get_all_names($query_params = array())
5969
+	{
5970
+		$objs = $this->get_all($query_params);
5971
+		$names = array();
5972
+		foreach ($objs as $obj) {
5973
+			$names[ $obj->ID() ] = $obj->name();
5974
+		}
5975
+		return $names;
5976
+	}
5977
+
5978
+
5979
+
5980
+	/**
5981
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5982
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5983
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5984
+	 * array_keys() on $model_objects.
5985
+	 *
5986
+	 * @param \EE_Base_Class[] $model_objects
5987
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5988
+	 *                                               in the returned array
5989
+	 * @return array
5990
+	 * @throws EE_Error
5991
+	 */
5992
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5993
+	{
5994
+		if (! $this->has_primary_key_field()) {
5995
+			if (WP_DEBUG) {
5996
+				EE_Error::add_error(
5997
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5998
+					__FILE__,
5999
+					__FUNCTION__,
6000
+					__LINE__
6001
+				);
6002
+			}
6003
+		}
6004
+		$IDs = array();
6005
+		foreach ($model_objects as $model_object) {
6006
+			$id = $model_object->ID();
6007
+			if (! $id) {
6008
+				if ($filter_out_empty_ids) {
6009
+					continue;
6010
+				}
6011
+				if (WP_DEBUG) {
6012
+					EE_Error::add_error(
6013
+						__(
6014
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6015
+							'event_espresso'
6016
+						),
6017
+						__FILE__,
6018
+						__FUNCTION__,
6019
+						__LINE__
6020
+					);
6021
+				}
6022
+			}
6023
+			$IDs[] = $id;
6024
+		}
6025
+		return $IDs;
6026
+	}
6027
+
6028
+
6029
+
6030
+	/**
6031
+	 * Returns the string used in capabilities relating to this model. If there
6032
+	 * are no capabilities that relate to this model returns false
6033
+	 *
6034
+	 * @return string|false
6035
+	 */
6036
+	public function cap_slug()
6037
+	{
6038
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6039
+	}
6040
+
6041
+
6042
+
6043
+	/**
6044
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6045
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6046
+	 * only returns the cap restrictions array in that context (ie, the array
6047
+	 * at that key)
6048
+	 *
6049
+	 * @param string $context
6050
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6051
+	 * @throws EE_Error
6052
+	 */
6053
+	public function cap_restrictions($context = EEM_Base::caps_read)
6054
+	{
6055
+		EEM_Base::verify_is_valid_cap_context($context);
6056
+		// check if we ought to run the restriction generator first
6057
+		if (isset($this->_cap_restriction_generators[ $context ])
6058
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6059
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6060
+		) {
6061
+			$this->_cap_restrictions[ $context ] = array_merge(
6062
+				$this->_cap_restrictions[ $context ],
6063
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6064
+			);
6065
+		}
6066
+		// and make sure we've finalized the construction of each restriction
6067
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6068
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6069
+				$where_conditions_obj->_finalize_construct($this);
6070
+			}
6071
+		}
6072
+		return $this->_cap_restrictions[ $context ];
6073
+	}
6074
+
6075
+
6076
+
6077
+	/**
6078
+	 * Indicating whether or not this model thinks its a wp core model
6079
+	 *
6080
+	 * @return boolean
6081
+	 */
6082
+	public function is_wp_core_model()
6083
+	{
6084
+		return $this->_wp_core_model;
6085
+	}
6086
+
6087
+
6088
+
6089
+	/**
6090
+	 * Gets all the caps that are missing which impose a restriction on
6091
+	 * queries made in this context
6092
+	 *
6093
+	 * @param string $context one of EEM_Base::caps_ constants
6094
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6095
+	 * @throws EE_Error
6096
+	 */
6097
+	public function caps_missing($context = EEM_Base::caps_read)
6098
+	{
6099
+		$missing_caps = array();
6100
+		$cap_restrictions = $this->cap_restrictions($context);
6101
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6102
+			if (! EE_Capabilities::instance()
6103
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6104
+			) {
6105
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6106
+			}
6107
+		}
6108
+		return $missing_caps;
6109
+	}
6110
+
6111
+
6112
+
6113
+	/**
6114
+	 * Gets the mapping from capability contexts to action strings used in capability names
6115
+	 *
6116
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6117
+	 * one of 'read', 'edit', or 'delete'
6118
+	 */
6119
+	public function cap_contexts_to_cap_action_map()
6120
+	{
6121
+		return apply_filters(
6122
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6123
+			$this->_cap_contexts_to_cap_action_map,
6124
+			$this
6125
+		);
6126
+	}
6127
+
6128
+
6129
+
6130
+	/**
6131
+	 * Gets the action string for the specified capability context
6132
+	 *
6133
+	 * @param string $context
6134
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6135
+	 * @throws EE_Error
6136
+	 */
6137
+	public function cap_action_for_context($context)
6138
+	{
6139
+		$mapping = $this->cap_contexts_to_cap_action_map();
6140
+		if (isset($mapping[ $context ])) {
6141
+			return $mapping[ $context ];
6142
+		}
6143
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6144
+			return $action;
6145
+		}
6146
+		throw new EE_Error(
6147
+			sprintf(
6148
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6149
+				$context,
6150
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6151
+			)
6152
+		);
6153
+	}
6154
+
6155
+
6156
+
6157
+	/**
6158
+	 * Returns all the capability contexts which are valid when querying models
6159
+	 *
6160
+	 * @return array
6161
+	 */
6162
+	public static function valid_cap_contexts()
6163
+	{
6164
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6165
+			self::caps_read,
6166
+			self::caps_read_admin,
6167
+			self::caps_edit,
6168
+			self::caps_delete,
6169
+		));
6170
+	}
6171
+
6172
+
6173
+
6174
+	/**
6175
+	 * Returns all valid options for 'default_where_conditions'
6176
+	 *
6177
+	 * @return array
6178
+	 */
6179
+	public static function valid_default_where_conditions()
6180
+	{
6181
+		return array(
6182
+			EEM_Base::default_where_conditions_all,
6183
+			EEM_Base::default_where_conditions_this_only,
6184
+			EEM_Base::default_where_conditions_others_only,
6185
+			EEM_Base::default_where_conditions_minimum_all,
6186
+			EEM_Base::default_where_conditions_minimum_others,
6187
+			EEM_Base::default_where_conditions_none
6188
+		);
6189
+	}
6190
+
6191
+	// public static function default_where_conditions_full
6192
+	/**
6193
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6194
+	 *
6195
+	 * @param string $context
6196
+	 * @return bool
6197
+	 * @throws EE_Error
6198
+	 */
6199
+	public static function verify_is_valid_cap_context($context)
6200
+	{
6201
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6202
+		if (in_array($context, $valid_cap_contexts)) {
6203
+			return true;
6204
+		}
6205
+		throw new EE_Error(
6206
+			sprintf(
6207
+				__(
6208
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6209
+					'event_espresso'
6210
+				),
6211
+				$context,
6212
+				'EEM_Base',
6213
+				implode(',', $valid_cap_contexts)
6214
+			)
6215
+		);
6216
+	}
6217
+
6218
+
6219
+
6220
+	/**
6221
+	 * Clears all the models field caches. This is only useful when a sub-class
6222
+	 * might have added a field or something and these caches might be invalidated
6223
+	 */
6224
+	protected function _invalidate_field_caches()
6225
+	{
6226
+		$this->_cache_foreign_key_to_fields = array();
6227
+		$this->_cached_fields = null;
6228
+		$this->_cached_fields_non_db_only = null;
6229
+	}
6230
+
6231
+
6232
+
6233
+	/**
6234
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6235
+	 * (eg "and", "or", "not").
6236
+	 *
6237
+	 * @return array
6238
+	 */
6239
+	public function logic_query_param_keys()
6240
+	{
6241
+		return $this->_logic_query_param_keys;
6242
+	}
6243
+
6244
+
6245
+
6246
+	/**
6247
+	 * Determines whether or not the where query param array key is for a logic query param.
6248
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6249
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6250
+	 *
6251
+	 * @param $query_param_key
6252
+	 * @return bool
6253
+	 */
6254
+	public function is_logic_query_param_key($query_param_key)
6255
+	{
6256
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6257
+			if ($query_param_key === $logic_query_param_key
6258
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6259
+			) {
6260
+				return true;
6261
+			}
6262
+		}
6263
+		return false;
6264
+	}
6265 6265
 }
Please login to merge, or discard this patch.