Completed
Branch foreign-key-alias-objects (c91d1e)
by
unknown
42:07 queued 33:58
created
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6460 added lines, -6460 removed lines patch added patch discarded remove patch
@@ -35,6466 +35,6466 @@
 block discarded – undo
35 35
 abstract class EEM_Base extends EE_Base implements ResettableInterface
36 36
 {
37 37
 
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    private static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    __(
561
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            __(
680
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
-     *                                        array( array(
852
-     *                                        'OR'=>array(
853
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
-     *                                        )
856
-     *                                        ),
857
-     *                                        'limit'=>10,
858
-     *                                        'group_by'=>'TXN_ID'
859
-     *                                        ));
860
-     *                                        get all the answers to the question titled "shirt size" for event with id
861
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
-     *                                        'Question.QST_display_text'=>'shirt size',
863
-     *                                        'Registration.Event.EVT_ID'=>12
864
-     *                                        ),
865
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
866
-     *                                        ));
867
-     * @throws EE_Error
868
-     */
869
-    public function get_all($query_params = array())
870
-    {
871
-        if (isset($query_params['limit'])
872
-            && ! isset($query_params['group_by'])
873
-        ) {
874
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
-        }
876
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
-    }
878
-
879
-
880
-
881
-    /**
882
-     * Modifies the query parameters so we only get back model objects
883
-     * that "belong" to the current user
884
-     *
885
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     */
888
-    public function alter_query_params_to_only_include_mine($query_params = array())
889
-    {
890
-        $wp_user_field_name = $this->wp_user_field_name();
891
-        if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
-        }
894
-        return $query_params;
895
-    }
896
-
897
-
898
-
899
-    /**
900
-     * Returns the name of the field's name that points to the WP_User table
901
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
-     * foreign key to the WP_User table)
903
-     *
904
-     * @return string|boolean string on success, boolean false when there is no
905
-     * foreign key to the WP_User table
906
-     */
907
-    public function wp_user_field_name()
908
-    {
909
-        try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
911
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
-                $last_model_name = end($models_to_follow_to_wp_users);
913
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
-            } else {
916
-                $model_with_fk_to_wp_users = $this;
917
-                $model_chain_to_wp_user = '';
918
-            }
919
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
921
-        } catch (EE_Error $e) {
922
-            return false;
923
-        }
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
930
-     * (or transiently-related model) has a foreign key to the wp_users table;
931
-     * useful for finding if model objects of this type are 'owned' by the current user.
932
-     * This is an empty string when the foreign key is on this model and when it isn't,
933
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
934
-     * (or transiently-related model)
935
-     *
936
-     * @return string
937
-     */
938
-    public function model_chain_to_wp_user()
939
-    {
940
-        return $this->_model_chain_to_wp_user;
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
-     * like how registrations don't have a foreign key to wp_users, but the
948
-     * events they are for are), or is unrelated to wp users.
949
-     * generally available
950
-     *
951
-     * @return boolean
952
-     */
953
-    public function is_owned()
954
-    {
955
-        if ($this->model_chain_to_wp_user()) {
956
-            return true;
957
-        }
958
-        try {
959
-            $this->get_foreign_key_to('WP_User');
960
-            return true;
961
-        } catch (EE_Error $e) {
962
-            return false;
963
-        }
964
-    }
965
-
966
-
967
-    /**
968
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
-     * the model)
971
-     *
972
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
-     *                                  fields on the model, and the models we joined to in the query. However, you can
976
-     *                                  override this and set the select to "*", or a specific column name, like
977
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
-     *                                  the aliases used to refer to this selection, and values are to be
980
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
-     * @throws EE_Error
984
-     * @throws InvalidArgumentException
985
-     */
986
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
-    {
988
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
-        ;
990
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
991
-        $select_expressions = $columns_to_select === null
992
-            ? $this->_construct_default_select_sql($model_query_info)
993
-            : '';
994
-        if ($this->_custom_selections instanceof CustomSelects) {
995
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
-            $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
998
-                : $custom_expressions;
999
-        }
1000
-
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
-     * method of including extra select information.
1010
-     *
1011
-     * @param array             $query_params
1012
-     * @param null|array|string $columns_to_select
1013
-     * @return null|CustomSelects
1014
-     * @throws InvalidArgumentException
1015
-     */
1016
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
-    {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
-            return null;
1020
-        }
1021
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
-        return new CustomSelects($selects);
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1030
-     * but you can use the model query params to more easily
1031
-     * take care of joins, field preparation etc.
1032
-     *
1033
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
-    }
1050
-
1051
-
1052
-
1053
-    /**
1054
-     * For creating a custom select statement
1055
-     *
1056
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
-     *                                 SQL, and 1=>is the datatype
1059
-     * @throws EE_Error
1060
-     * @return string
1061
-     */
1062
-    private function _construct_select_from_input($columns_to_select)
1063
-    {
1064
-        if (is_array($columns_to_select)) {
1065
-            $select_sql_array = array();
1066
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
-                    throw new EE_Error(
1069
-                        sprintf(
1070
-                            __(
1071
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
-                                'event_espresso'
1073
-                            ),
1074
-                            $selection_and_datatype,
1075
-                            $alias
1076
-                        )
1077
-                    );
1078
-                }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
-                    throw new EE_Error(
1081
-                        sprintf(
1082
-                            esc_html__(
1083
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
-                                'event_espresso'
1085
-                            ),
1086
-                            $selection_and_datatype[1],
1087
-                            $selection_and_datatype[0],
1088
-                            $alias,
1089
-                            implode(', ', $this->_valid_wpdb_data_types)
1090
-                        )
1091
-                    );
1092
-                }
1093
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
-            }
1095
-            $columns_to_select_string = implode(', ', $select_sql_array);
1096
-        } else {
1097
-            $columns_to_select_string = $columns_to_select;
1098
-        }
1099
-        return $columns_to_select_string;
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
-     *
1107
-     * @return string
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function primary_key_name()
1111
-    {
1112
-        return $this->get_primary_key_field()->get_name();
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1118
-     * If there is no primary key on this model, $id is treated as primary key string
1119
-     *
1120
-     * @param mixed $id int or string, depending on the type of the model's primary key
1121
-     * @return EE_Base_Class
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function get_one_by_ID($id)
1125
-    {
1126
-        if ($this->get_from_entity_map($id)) {
1127
-            return $this->get_from_entity_map($id);
1128
-        }
1129
-        $model_object = $this->get_one(
1130
-            $this->alter_query_params_to_restrict_by_ID(
1131
-                $id,
1132
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
-            )
1134
-        );
1135
-        $className = $this->_get_class_name();
1136
-        if ($model_object instanceof $className) {
1137
-            // make sure valid objects get added to the entity map
1138
-            // so that the next call to this method doesn't trigger another trip to the db
1139
-            $this->add_to_entity_map($model_object);
1140
-        }
1141
-        return $model_object;
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Alters query parameters to only get items with this ID are returned.
1148
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1149
-     * or could just be a simple primary key ID
1150
-     *
1151
-     * @param int   $id
1152
-     * @param array $query_params
1153
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157
-    {
1158
-        if (! isset($query_params[0])) {
1159
-            $query_params[0] = array();
1160
-        }
1161
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1162
-        if ($conditions_from_id === null) {
1163
-            $query_params[0][ $this->primary_key_name() ] = $id;
1164
-        } else {
1165
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1166
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1167
-        }
1168
-        return $query_params;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1175
-     * array. If no item is found, null is returned.
1176
-     *
1177
-     * @param array $query_params like EEM_Base's $query_params variable.
1178
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1179
-     * @throws EE_Error
1180
-     */
1181
-    public function get_one($query_params = array())
1182
-    {
1183
-        if (! is_array($query_params)) {
1184
-            EE_Error::doing_it_wrong(
1185
-                'EEM_Base::get_one',
1186
-                sprintf(
1187
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1188
-                    gettype($query_params)
1189
-                ),
1190
-                '4.6.0'
1191
-            );
1192
-            $query_params = array();
1193
-        }
1194
-        $query_params['limit'] = 1;
1195
-        $items = $this->get_all($query_params);
1196
-        if (empty($items)) {
1197
-            return null;
1198
-        }
1199
-        return array_shift($items);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Returns the next x number of items in sequence from the given value as
1206
-     * found in the database matching the given query conditions.
1207
-     *
1208
-     * @param mixed $current_field_value    Value used for the reference point.
1209
-     * @param null  $field_to_order_by      What field is used for the
1210
-     *                                      reference point.
1211
-     * @param int   $limit                  How many to return.
1212
-     * @param array $query_params           Extra conditions on the query.
1213
-     * @param null  $columns_to_select      If left null, then an array of
1214
-     *                                      EE_Base_Class objects is returned,
1215
-     *                                      otherwise you can indicate just the
1216
-     *                                      columns you want returned.
1217
-     * @return EE_Base_Class[]|array
1218
-     * @throws EE_Error
1219
-     */
1220
-    public function next_x(
1221
-        $current_field_value,
1222
-        $field_to_order_by = null,
1223
-        $limit = 1,
1224
-        $query_params = array(),
1225
-        $columns_to_select = null
1226
-    ) {
1227
-        return $this->_get_consecutive(
1228
-            $current_field_value,
1229
-            '>',
1230
-            $field_to_order_by,
1231
-            $limit,
1232
-            $query_params,
1233
-            $columns_to_select
1234
-        );
1235
-    }
1236
-
1237
-
1238
-
1239
-    /**
1240
-     * Returns the previous x number of items in sequence from the given value
1241
-     * as found in the database matching the given query conditions.
1242
-     *
1243
-     * @param mixed $current_field_value    Value used for the reference point.
1244
-     * @param null  $field_to_order_by      What field is used for the
1245
-     *                                      reference point.
1246
-     * @param int   $limit                  How many to return.
1247
-     * @param array $query_params           Extra conditions on the query.
1248
-     * @param null  $columns_to_select      If left null, then an array of
1249
-     *                                      EE_Base_Class objects is returned,
1250
-     *                                      otherwise you can indicate just the
1251
-     *                                      columns you want returned.
1252
-     * @return EE_Base_Class[]|array
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function previous_x(
1256
-        $current_field_value,
1257
-        $field_to_order_by = null,
1258
-        $limit = 1,
1259
-        $query_params = array(),
1260
-        $columns_to_select = null
1261
-    ) {
1262
-        return $this->_get_consecutive(
1263
-            $current_field_value,
1264
-            '<',
1265
-            $field_to_order_by,
1266
-            $limit,
1267
-            $query_params,
1268
-            $columns_to_select
1269
-        );
1270
-    }
1271
-
1272
-
1273
-
1274
-    /**
1275
-     * Returns the next item in sequence from the given value as found in the
1276
-     * database matching the given query conditions.
1277
-     *
1278
-     * @param mixed $current_field_value    Value used for the reference point.
1279
-     * @param null  $field_to_order_by      What field is used for the
1280
-     *                                      reference point.
1281
-     * @param array $query_params           Extra conditions on the query.
1282
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1283
-     *                                      object is returned, otherwise you
1284
-     *                                      can indicate just the columns you
1285
-     *                                      want and a single array indexed by
1286
-     *                                      the columns will be returned.
1287
-     * @return EE_Base_Class|null|array()
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function next(
1291
-        $current_field_value,
1292
-        $field_to_order_by = null,
1293
-        $query_params = array(),
1294
-        $columns_to_select = null
1295
-    ) {
1296
-        $results = $this->_get_consecutive(
1297
-            $current_field_value,
1298
-            '>',
1299
-            $field_to_order_by,
1300
-            1,
1301
-            $query_params,
1302
-            $columns_to_select
1303
-        );
1304
-        return empty($results) ? null : reset($results);
1305
-    }
1306
-
1307
-
1308
-
1309
-    /**
1310
-     * Returns the previous item in sequence from the given value as found in
1311
-     * the database matching the given query conditions.
1312
-     *
1313
-     * @param mixed $current_field_value    Value used for the reference point.
1314
-     * @param null  $field_to_order_by      What field is used for the
1315
-     *                                      reference point.
1316
-     * @param array $query_params           Extra conditions on the query.
1317
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1318
-     *                                      object is returned, otherwise you
1319
-     *                                      can indicate just the columns you
1320
-     *                                      want and a single array indexed by
1321
-     *                                      the columns will be returned.
1322
-     * @return EE_Base_Class|null|array()
1323
-     * @throws EE_Error
1324
-     */
1325
-    public function previous(
1326
-        $current_field_value,
1327
-        $field_to_order_by = null,
1328
-        $query_params = array(),
1329
-        $columns_to_select = null
1330
-    ) {
1331
-        $results = $this->_get_consecutive(
1332
-            $current_field_value,
1333
-            '<',
1334
-            $field_to_order_by,
1335
-            1,
1336
-            $query_params,
1337
-            $columns_to_select
1338
-        );
1339
-        return empty($results) ? null : reset($results);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Returns the a consecutive number of items in sequence from the given
1346
-     * value as found in the database matching the given query conditions.
1347
-     *
1348
-     * @param mixed  $current_field_value   Value used for the reference point.
1349
-     * @param string $operand               What operand is used for the sequence.
1350
-     * @param string $field_to_order_by     What field is used for the reference point.
1351
-     * @param int    $limit                 How many to return.
1352
-     * @param array  $query_params          Extra conditions on the query.
1353
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
-     *                                      otherwise you can indicate just the columns you want returned.
1355
-     * @return EE_Base_Class[]|array
1356
-     * @throws EE_Error
1357
-     */
1358
-    protected function _get_consecutive(
1359
-        $current_field_value,
1360
-        $operand = '>',
1361
-        $field_to_order_by = null,
1362
-        $limit = 1,
1363
-        $query_params = array(),
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
-        if (empty($field_to_order_by)) {
1368
-            if ($this->has_primary_key_field()) {
1369
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1370
-            } else {
1371
-                if (WP_DEBUG) {
1372
-                    throw new EE_Error(__(
1373
-                        '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).',
1374
-                        'event_espresso'
1375
-                    ));
1376
-                }
1377
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1378
-                return array();
1379
-            }
1380
-        }
1381
-        if (! is_array($query_params)) {
1382
-            EE_Error::doing_it_wrong(
1383
-                'EEM_Base::_get_consecutive',
1384
-                sprintf(
1385
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1386
-                    gettype($query_params)
1387
-                ),
1388
-                '4.6.0'
1389
-            );
1390
-            $query_params = array();
1391
-        }
1392
-        // let's add the where query param for consecutive look up.
1393
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
-        $query_params['limit'] = $limit;
1395
-        // set direction
1396
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1397
-        $query_params['order_by'] = $operand === '>'
1398
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1399
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1400
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1401
-        if (empty($columns_to_select)) {
1402
-            return $this->get_all($query_params);
1403
-        }
1404
-        // getting just the fields
1405
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1406
-    }
1407
-
1408
-
1409
-
1410
-    /**
1411
-     * This sets the _timezone property after model object has been instantiated.
1412
-     *
1413
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1414
-     */
1415
-    public function set_timezone($timezone)
1416
-    {
1417
-        if ($timezone !== null) {
1418
-            $this->_timezone = $timezone;
1419
-        }
1420
-        // note we need to loop through relations and set the timezone on those objects as well.
1421
-        foreach ($this->_model_relations as $relation) {
1422
-            $relation->set_timezone($timezone);
1423
-        }
1424
-        // and finally we do the same for any datetime fields
1425
-        foreach ($this->_fields as $field) {
1426
-            if ($field instanceof EE_Datetime_Field) {
1427
-                $field->set_timezone($timezone);
1428
-            }
1429
-        }
1430
-    }
1431
-
1432
-
1433
-
1434
-    /**
1435
-     * This just returns whatever is set for the current timezone.
1436
-     *
1437
-     * @access public
1438
-     * @return string
1439
-     */
1440
-    public function get_timezone()
1441
-    {
1442
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1443
-        if (empty($this->_timezone)) {
1444
-            foreach ($this->_fields as $field) {
1445
-                if ($field instanceof EE_Datetime_Field) {
1446
-                    $this->set_timezone($field->get_timezone());
1447
-                    break;
1448
-                }
1449
-            }
1450
-        }
1451
-        // if timezone STILL empty then return the default timezone for the site.
1452
-        if (empty($this->_timezone)) {
1453
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1454
-        }
1455
-        return $this->_timezone;
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This returns the date formats set for the given field name and also ensures that
1462
-     * $this->_timezone property is set correctly.
1463
-     *
1464
-     * @since 4.6.x
1465
-     * @param string $field_name The name of the field the formats are being retrieved for.
1466
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1467
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1468
-     * @return array formats in an array with the date format first, and the time format last.
1469
-     */
1470
-    public function get_formats_for($field_name, $pretty = false)
1471
-    {
1472
-        $field_settings = $this->field_settings_for($field_name);
1473
-        // if not a valid EE_Datetime_Field then throw error
1474
-        if (! $field_settings instanceof EE_Datetime_Field) {
1475
-            throw new EE_Error(sprintf(__(
1476
-                '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.',
1477
-                'event_espresso'
1478
-            ), $field_name));
1479
-        }
1480
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1481
-        // the field.
1482
-        $this->_timezone = $field_settings->get_timezone();
1483
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1484
-    }
1485
-
1486
-
1487
-
1488
-    /**
1489
-     * This returns the current time in a format setup for a query on this model.
1490
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1491
-     * it will return:
1492
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1493
-     *  NOW
1494
-     *  - or a unix timestamp (equivalent to time())
1495
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1496
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1497
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1498
-     * @since 4.6.x
1499
-     * @param string $field_name       The field the current time is needed for.
1500
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1501
-     *                                 formatted string matching the set format for the field in the set timezone will
1502
-     *                                 be returned.
1503
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1504
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1505
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1506
-     *                                 exception is triggered.
1507
-     */
1508
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1509
-    {
1510
-        $formats = $this->get_formats_for($field_name);
1511
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1512
-        if ($timestamp) {
1513
-            return $DateTime->format('U');
1514
-        }
1515
-        // not returning timestamp, so return formatted string in timezone.
1516
-        switch ($what) {
1517
-            case 'time':
1518
-                return $DateTime->format($formats[1]);
1519
-                break;
1520
-            case 'date':
1521
-                return $DateTime->format($formats[0]);
1522
-                break;
1523
-            default:
1524
-                return $DateTime->format(implode(' ', $formats));
1525
-                break;
1526
-        }
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1533
-     * for the model are.  Returns a DateTime object.
1534
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1535
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1536
-     * ignored.
1537
-     *
1538
-     * @param string $field_name      The field being setup.
1539
-     * @param string $timestring      The date time string being used.
1540
-     * @param string $incoming_format The format for the time string.
1541
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1542
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1543
-     *                                format is
1544
-     *                                'U', this is ignored.
1545
-     * @return DateTime
1546
-     * @throws EE_Error
1547
-     */
1548
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1549
-    {
1550
-        // just using this to ensure the timezone is set correctly internally
1551
-        $this->get_formats_for($field_name);
1552
-        // load EEH_DTT_Helper
1553
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1554
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1555
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1556
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1563
-     *
1564
-     * @return EE_Table_Base[]
1565
-     */
1566
-    public function get_tables()
1567
-    {
1568
-        return $this->_tables;
1569
-    }
1570
-
1571
-
1572
-
1573
-    /**
1574
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1575
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1576
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1577
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1578
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1579
-     * model object with EVT_ID = 1
1580
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1581
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1582
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1583
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1584
-     * are not specified)
1585
-     *
1586
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1587
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1588
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1589
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1590
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1591
-     *                                         ID=34, we'd use this method as follows:
1592
-     *                                         EEM_Transaction::instance()->update(
1593
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1594
-     *                                         array(array('TXN_ID'=>34)));
1595
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1596
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1597
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1598
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1599
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1600
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1601
-     *                                         TRUE, it is assumed that you've already called
1602
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1603
-     *                                         malicious javascript. However, if
1604
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1605
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1606
-     *                                         and every other field, before insertion. We provide this parameter
1607
-     *                                         because model objects perform their prepare_for_set function on all
1608
-     *                                         their values, and so don't need to be called again (and in many cases,
1609
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1610
-     *                                         prepare_for_set method...)
1611
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1612
-     *                                         in this model's entity map according to $fields_n_values that match
1613
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1614
-     *                                         by setting this to FALSE, but be aware that model objects being used
1615
-     *                                         could get out-of-sync with the database
1616
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1617
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1618
-     *                                         bad)
1619
-     * @throws EE_Error
1620
-     */
1621
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622
-    {
1623
-        if (! is_array($query_params)) {
1624
-            EE_Error::doing_it_wrong(
1625
-                'EEM_Base::update',
1626
-                sprintf(
1627
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1628
-                    gettype($query_params)
1629
-                ),
1630
-                '4.6.0'
1631
-            );
1632
-            $query_params = array();
1633
-        }
1634
-        /**
1635
-         * Action called before a model update call has been made.
1636
-         *
1637
-         * @param EEM_Base $model
1638
-         * @param array    $fields_n_values the updated fields and their new values
1639
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1640
-         */
1641
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1642
-        /**
1643
-         * Filters the fields about to be updated given the query parameters. You can provide the
1644
-         * $query_params to $this->get_all() to find exactly which records will be updated
1645
-         *
1646
-         * @param array    $fields_n_values fields and their new values
1647
-         * @param EEM_Base $model           the model being queried
1648
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1649
-         */
1650
-        $fields_n_values = (array) apply_filters(
1651
-            'FHEE__EEM_Base__update__fields_n_values',
1652
-            $fields_n_values,
1653
-            $this,
1654
-            $query_params
1655
-        );
1656
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1657
-        // to do that, for each table, verify that it's PK isn't null.
1658
-        $tables = $this->get_tables();
1659
-        // 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
1660
-        // NOTE: we should make this code more efficient by NOT querying twice
1661
-        // before the real update, but that needs to first go through ALPHA testing
1662
-        // as it's dangerous. says Mike August 8 2014
1663
-        // we want to make sure the default_where strategy is ignored
1664
-        $this->_ignore_where_strategy = true;
1665
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1666
-        foreach ($wpdb_select_results as $wpdb_result) {
1667
-            // type cast stdClass as array
1668
-            $wpdb_result = (array) $wpdb_result;
1669
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670
-            if ($this->has_primary_key_field()) {
1671
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
-            } else {
1673
-                // 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)
1674
-                $main_table_pk_value = null;
1675
-            }
1676
-            // 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
1677
-            // 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
1678
-            if (count($tables) > 1) {
1679
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1680
-                // in that table, and so we'll want to insert one
1681
-                foreach ($tables as $table_obj) {
1682
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683
-                    // if there is no private key for this table on the results, it means there's no entry
1684
-                    // in this table, right? so insert a row in the current table, using any fields available
1685
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
-                           && $wpdb_result[ $this_table_pk_column ])
1687
-                    ) {
1688
-                        $success = $this->_insert_into_specific_table(
1689
-                            $table_obj,
1690
-                            $fields_n_values,
1691
-                            $main_table_pk_value
1692
-                        );
1693
-                        // if we died here, report the error
1694
-                        if (! $success) {
1695
-                            return false;
1696
-                        }
1697
-                    }
1698
-                }
1699
-            }
1700
-            //              //and now check that if we have cached any models by that ID on the model, that
1701
-            //              //they also get updated properly
1702
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1703
-            //              if( $model_object ){
1704
-            //                  foreach( $fields_n_values as $field => $value ){
1705
-            //                      $model_object->set($field, $value);
1706
-            // let's make sure default_where strategy is followed now
1707
-            $this->_ignore_where_strategy = false;
1708
-        }
1709
-        // if we want to keep model objects in sync, AND
1710
-        // if this wasn't called from a model object (to update itself)
1711
-        // then we want to make sure we keep all the existing
1712
-        // model objects in sync with the db
1713
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1714
-            if ($this->has_primary_key_field()) {
1715
-                $model_objs_affected_ids = $this->get_col($query_params);
1716
-            } else {
1717
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1718
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1719
-                $model_objs_affected_ids = array();
1720
-                foreach ($models_affected_key_columns as $row) {
1721
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1722
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1723
-                }
1724
-            }
1725
-            if (! $model_objs_affected_ids) {
1726
-                // wait wait wait- if nothing was affected let's stop here
1727
-                return 0;
1728
-            }
1729
-            foreach ($model_objs_affected_ids as $id) {
1730
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1731
-                if ($model_obj_in_entity_map) {
1732
-                    foreach ($fields_n_values as $field => $new_value) {
1733
-                        $model_obj_in_entity_map->set($field, $new_value);
1734
-                    }
1735
-                }
1736
-            }
1737
-            // if there is a primary key on this model, we can now do a slight optimization
1738
-            if ($this->has_primary_key_field()) {
1739
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1740
-                $query_params = array(
1741
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1742
-                    'limit'                    => count($model_objs_affected_ids),
1743
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1744
-                );
1745
-            }
1746
-        }
1747
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
-        $SQL = "UPDATE "
1749
-               . $model_query_info->get_full_join_sql()
1750
-               . " SET "
1751
-               . $this->_construct_update_sql($fields_n_values)
1752
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754
-        /**
1755
-         * Action called after a model update call has been made.
1756
-         *
1757
-         * @param EEM_Base $model
1758
-         * @param array    $fields_n_values the updated fields and their new values
1759
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1760
-         * @param int      $rows_affected
1761
-         */
1762
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
-        return $rows_affected;// how many supposedly got updated
1764
-    }
1765
-
1766
-
1767
-
1768
-    /**
1769
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1770
-     * are teh values of the field specified (or by default the primary key field)
1771
-     * that matched the query params. Note that you should pass the name of the
1772
-     * model FIELD, not the database table's column name.
1773
-     *
1774
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1775
-     * @param string $field_to_select
1776
-     * @return array just like $wpdb->get_col()
1777
-     * @throws EE_Error
1778
-     */
1779
-    public function get_col($query_params = array(), $field_to_select = null)
1780
-    {
1781
-        if ($field_to_select) {
1782
-            $field = $this->field_settings_for($field_to_select);
1783
-        } elseif ($this->has_primary_key_field()) {
1784
-            $field = $this->get_primary_key_field();
1785
-        } else {
1786
-            // no primary key, just grab the first column
1787
-            $field = reset($this->field_settings());
1788
-        }
1789
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1790
-        $select_expressions = $field->get_qualified_column();
1791
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1792
-        return $this->_do_wpdb_query('get_col', array($SQL));
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Returns a single column value for a single row from the database
1799
-     *
1800
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1801
-     * @param string $field_to_select @see EEM_Base::get_col()
1802
-     * @return string
1803
-     * @throws EE_Error
1804
-     */
1805
-    public function get_var($query_params = array(), $field_to_select = null)
1806
-    {
1807
-        $query_params['limit'] = 1;
1808
-        $col = $this->get_col($query_params, $field_to_select);
1809
-        if (! empty($col)) {
1810
-            return reset($col);
1811
-        }
1812
-        return null;
1813
-    }
1814
-
1815
-
1816
-
1817
-    /**
1818
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1819
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1820
-     * injection, but currently no further filtering is done
1821
-     *
1822
-     * @global      $wpdb
1823
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1824
-     *                               be updated to in the DB
1825
-     * @return string of SQL
1826
-     * @throws EE_Error
1827
-     */
1828
-    public function _construct_update_sql($fields_n_values)
1829
-    {
1830
-        /** @type WPDB $wpdb */
1831
-        global $wpdb;
1832
-        $cols_n_values = array();
1833
-        foreach ($fields_n_values as $field_name => $value) {
1834
-            $field_obj = $this->field_settings_for($field_name);
1835
-            // if the value is NULL, we want to assign the value to that.
1836
-            // wpdb->prepare doesn't really handle that properly
1837
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838
-            $value_sql = $prepared_value === null ? 'NULL'
1839
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1841
-        }
1842
-        return implode(",", $cols_n_values);
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
-     * Performs a HARD delete, meaning the database row should always be removed,
1850
-     * not just have a flag field on it switched
1851
-     * Wrapper for EEM_Base::delete_permanently()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @param boolean $allow_blocking
1855
-     * @return int the number of rows deleted
1856
-     * @throws EE_Error
1857
-     */
1858
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1859
-    {
1860
-        return $this->delete_permanently(
1861
-            array(
1862
-                array($this->get_primary_key_field()->get_name() => $id),
1863
-                'limit' => 1,
1864
-            ),
1865
-            $allow_blocking
1866
-        );
1867
-    }
1868
-
1869
-
1870
-
1871
-    /**
1872
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1873
-     * Wrapper for EEM_Base::delete()
1874
-     *
1875
-     * @param mixed $id
1876
-     * @param boolean $allow_blocking
1877
-     * @return int the number of rows deleted
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function delete_by_ID($id, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete(
1883
-            array(
1884
-                array($this->get_primary_key_field()->get_name() => $id),
1885
-                'limit' => 1,
1886
-            ),
1887
-            $allow_blocking
1888
-        );
1889
-    }
1890
-
1891
-
1892
-
1893
-    /**
1894
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1895
-     * meaning if the model has a field that indicates its been "trashed" or
1896
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1897
-     *
1898
-     * @see EEM_Base::delete_permanently
1899
-     * @param array   $query_params
1900
-     * @param boolean $allow_blocking
1901
-     * @return int how many rows got deleted
1902
-     * @throws EE_Error
1903
-     */
1904
-    public function delete($query_params, $allow_blocking = true)
1905
-    {
1906
-        return $this->delete_permanently($query_params, $allow_blocking);
1907
-    }
1908
-
1909
-
1910
-
1911
-    /**
1912
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1913
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1914
-     * as archived, not actually deleted
1915
-     *
1916
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1917
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1918
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1919
-     *                                deletes regardless of other objects which may depend on it. Its generally
1920
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1921
-     *                                DB
1922
-     * @return int how many rows got deleted
1923
-     * @throws EE_Error
1924
-     */
1925
-    public function delete_permanently($query_params, $allow_blocking = true)
1926
-    {
1927
-        /**
1928
-         * Action called just before performing a real deletion query. You can use the
1929
-         * model and its $query_params to find exactly which items will be deleted
1930
-         *
1931
-         * @param EEM_Base $model
1932
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1933
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1934
-         *                                 to block (prevent) this deletion
1935
-         */
1936
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1937
-        // some MySQL databases may be running safe mode, which may restrict
1938
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1939
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1940
-        // to delete them
1941
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1942
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1943
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1944
-            $columns_and_ids_for_deleting
1945
-        );
1946
-        /**
1947
-         * Allows client code to act on the items being deleted before the query is actually executed.
1948
-         *
1949
-         * @param EEM_Base $this  The model instance being acted on.
1950
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1951
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1952
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1953
-         *                                                  derived from the incoming query parameters.
1954
-         *                                                  @see details on the structure of this array in the phpdocs
1955
-         *                                                  for the `_get_ids_for_delete_method`
1956
-         *
1957
-         */
1958
-        do_action(
1959
-            'AHEE__EEM_Base__delete__before_query',
1960
-            $this,
1961
-            $query_params,
1962
-            $allow_blocking,
1963
-            $columns_and_ids_for_deleting
1964
-        );
1965
-        if ($deletion_where_query_part) {
1966
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1967
-            $table_aliases = array_keys($this->_tables);
1968
-            $SQL = "DELETE "
1969
-                   . implode(", ", $table_aliases)
1970
-                   . " FROM "
1971
-                   . $model_query_info->get_full_join_sql()
1972
-                   . " WHERE "
1973
-                   . $deletion_where_query_part;
1974
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1975
-        } else {
1976
-            $rows_deleted = 0;
1977
-        }
1978
-
1979
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1980
-        // there was no error with the delete query.
1981
-        if ($this->has_primary_key_field()
1982
-            && $rows_deleted !== false
1983
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1984
-        ) {
1985
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1986
-            foreach ($ids_for_removal as $id) {
1987
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1989
-                }
1990
-            }
1991
-
1992
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1993
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1994
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1995
-            // (although it is possible).
1996
-            // Note this can be skipped by using the provided filter and returning false.
1997
-            if (apply_filters(
1998
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1999
-                ! $this instanceof EEM_Extra_Meta,
2000
-                $this
2001
-            )) {
2002
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2003
-                    0 => array(
2004
-                        'EXM_type' => $this->get_this_model_name(),
2005
-                        'OBJ_ID'   => array(
2006
-                            'IN',
2007
-                            $ids_for_removal
2008
-                        )
2009
-                    )
2010
-                ));
2011
-            }
2012
-        }
2013
-
2014
-        /**
2015
-         * Action called just after performing a real deletion query. Although at this point the
2016
-         * items should have been deleted
2017
-         *
2018
-         * @param EEM_Base $model
2019
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2020
-         * @param int      $rows_deleted
2021
-         */
2022
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
-        return $rows_deleted;// how many supposedly got deleted
2024
-    }
2025
-
2026
-
2027
-
2028
-    /**
2029
-     * Checks all the relations that throw error messages when there are blocking related objects
2030
-     * for related model objects. If there are any related model objects on those relations,
2031
-     * adds an EE_Error, and return true
2032
-     *
2033
-     * @param EE_Base_Class|int $this_model_obj_or_id
2034
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2035
-     *                                                 should be ignored when determining whether there are related
2036
-     *                                                 model objects which block this model object's deletion. Useful
2037
-     *                                                 if you know A is related to B and are considering deleting A,
2038
-     *                                                 but want to see if A has any other objects blocking its deletion
2039
-     *                                                 before removing the relation between A and B
2040
-     * @return boolean
2041
-     * @throws EE_Error
2042
-     */
2043
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2044
-    {
2045
-        // first, if $ignore_this_model_obj was supplied, get its model
2046
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2047
-            $ignored_model = $ignore_this_model_obj->get_model();
2048
-        } else {
2049
-            $ignored_model = null;
2050
-        }
2051
-        // now check all the relations of $this_model_obj_or_id and see if there
2052
-        // are any related model objects blocking it?
2053
-        $is_blocked = false;
2054
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2055
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2056
-                // if $ignore_this_model_obj was supplied, then for the query
2057
-                // on that model needs to be told to ignore $ignore_this_model_obj
2058
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2059
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2060
-                        array(
2061
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2062
-                                '!=',
2063
-                                $ignore_this_model_obj->ID(),
2064
-                            ),
2065
-                        ),
2066
-                    ));
2067
-                } else {
2068
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2069
-                }
2070
-                if ($related_model_objects) {
2071
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2072
-                    $is_blocked = true;
2073
-                }
2074
-            }
2075
-        }
2076
-        return $is_blocked;
2077
-    }
2078
-
2079
-
2080
-    /**
2081
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2082
-     * @param array $row_results_for_deleting
2083
-     * @param bool  $allow_blocking
2084
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2085
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2086
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2087
-     *                 deleted. Example:
2088
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2089
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2090
-     *                 where each element is a group of columns and values that get deleted. Example:
2091
-     *                      array(
2092
-     *                          0 => array(
2093
-     *                              'Term_Relationship.object_id' => 1
2094
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2095
-     *                          ),
2096
-     *                          1 => array(
2097
-     *                              'Term_Relationship.object_id' => 1
2098
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2099
-     *                          )
2100
-     *                      )
2101
-     * @throws EE_Error
2102
-     */
2103
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2104
-    {
2105
-        $ids_to_delete_indexed_by_column = array();
2106
-        if ($this->has_primary_key_field()) {
2107
-            $primary_table = $this->_get_main_table();
2108
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2109
-            $other_tables = $this->_get_other_tables();
2110
-            $ids_to_delete_indexed_by_column = $query = array();
2111
-            foreach ($row_results_for_deleting as $item_to_delete) {
2112
-                // before we mark this item for deletion,
2113
-                // make sure there's no related entities blocking its deletion (if we're checking)
2114
-                if ($allow_blocking
2115
-                    && $this->delete_is_blocked_by_related_models(
2116
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2117
-                    )
2118
-                ) {
2119
-                    continue;
2120
-                }
2121
-                // primary table deletes
2122
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2125
-                }
2126
-            }
2127
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2128
-            $fields = $this->get_combined_primary_key_fields();
2129
-            foreach ($row_results_for_deleting as $item_to_delete) {
2130
-                $ids_to_delete_indexed_by_column_for_row = array();
2131
-                foreach ($fields as $cpk_field) {
2132
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2133
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2135
-                    }
2136
-                }
2137
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2138
-            }
2139
-        } else {
2140
-            // so there's no primary key and no combined key...
2141
-            // sorry, can't help you
2142
-            throw new EE_Error(
2143
-                sprintf(
2144
-                    __(
2145
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2146
-                        "event_espresso"
2147
-                    ),
2148
-                    get_class($this)
2149
-                )
2150
-            );
2151
-        }
2152
-        return $ids_to_delete_indexed_by_column;
2153
-    }
2154
-
2155
-
2156
-    /**
2157
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2158
-     * the corresponding query_part for the query performing the delete.
2159
-     *
2160
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2161
-     * @return string
2162
-     * @throws EE_Error
2163
-     */
2164
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2165
-    {
2166
-        $query_part = '';
2167
-        if (empty($ids_to_delete_indexed_by_column)) {
2168
-            return $query_part;
2169
-        } elseif ($this->has_primary_key_field()) {
2170
-            $query = array();
2171
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
-                // make sure we have unique $ids
2173
-                $ids = array_unique($ids);
2174
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2175
-            }
2176
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2177
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2178
-            $ways_to_identify_a_row = array();
2179
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2180
-                $values_for_each_combined_primary_key_for_a_row = array();
2181
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2182
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2183
-                }
2184
-                $ways_to_identify_a_row[] = '('
2185
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2186
-                                            . ')';
2187
-            }
2188
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2189
-        }
2190
-        return $query_part;
2191
-    }
2192
-
2193
-
2194
-
2195
-    /**
2196
-     * Gets the model field by the fully qualified name
2197
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2198
-     * @return EE_Model_Field_Base
2199
-     */
2200
-    public function get_field_by_column($qualified_column_name)
2201
-    {
2202
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2203
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2204
-                return $field_obj;
2205
-            }
2206
-        }
2207
-        throw new EE_Error(
2208
-            sprintf(
2209
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2210
-                $this->get_this_model_name(),
2211
-                $qualified_column_name
2212
-            )
2213
-        );
2214
-    }
2215
-
2216
-
2217
-
2218
-    /**
2219
-     * Count all the rows that match criteria the model query params.
2220
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2221
-     * column
2222
-     *
2223
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2224
-     * @param string $field_to_count field on model to count by (not column name)
2225
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2226
-     *                               that by the setting $distinct to TRUE;
2227
-     * @return int
2228
-     * @throws EE_Error
2229
-     */
2230
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2231
-    {
2232
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2233
-        if ($field_to_count) {
2234
-            $field_obj = $this->field_settings_for($field_to_count);
2235
-            $column_to_count = $field_obj->get_qualified_column();
2236
-        } elseif ($this->has_primary_key_field()) {
2237
-            $pk_field_obj = $this->get_primary_key_field();
2238
-            $column_to_count = $pk_field_obj->get_qualified_column();
2239
-        } else {
2240
-            // there's no primary key
2241
-            // if we're counting distinct items, and there's no primary key,
2242
-            // we need to list out the columns for distinction;
2243
-            // otherwise we can just use star
2244
-            if ($distinct) {
2245
-                $columns_to_use = array();
2246
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2247
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2248
-                }
2249
-                $column_to_count = implode(',', $columns_to_use);
2250
-            } else {
2251
-                $column_to_count = '*';
2252
-            }
2253
-        }
2254
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2255
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2256
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2257
-    }
2258
-
2259
-
2260
-
2261
-    /**
2262
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2263
-     *
2264
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2265
-     * @param string $field_to_sum name of field (array key in $_fields array)
2266
-     * @return float
2267
-     * @throws EE_Error
2268
-     */
2269
-    public function sum($query_params, $field_to_sum = null)
2270
-    {
2271
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
-        if ($field_to_sum) {
2273
-            $field_obj = $this->field_settings_for($field_to_sum);
2274
-        } else {
2275
-            $field_obj = $this->get_primary_key_field();
2276
-        }
2277
-        $column_to_count = $field_obj->get_qualified_column();
2278
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2279
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2280
-        $data_type = $field_obj->get_wpdb_data_type();
2281
-        if ($data_type === '%d' || $data_type === '%s') {
2282
-            return (float) $return_value;
2283
-        }
2284
-        // must be %f
2285
-        return (float) $return_value;
2286
-    }
2287
-
2288
-
2289
-
2290
-    /**
2291
-     * Just calls the specified method on $wpdb with the given arguments
2292
-     * Consolidates a little extra error handling code
2293
-     *
2294
-     * @param string $wpdb_method
2295
-     * @param array  $arguments_to_provide
2296
-     * @throws EE_Error
2297
-     * @global wpdb  $wpdb
2298
-     * @return mixed
2299
-     */
2300
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2301
-    {
2302
-        // if we're in maintenance mode level 2, DON'T run any queries
2303
-        // because level 2 indicates the database needs updating and
2304
-        // is probably out of sync with the code
2305
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2306
-            throw new EE_Error(sprintf(__(
2307
-                "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.",
2308
-                "event_espresso"
2309
-            )));
2310
-        }
2311
-        /** @type WPDB $wpdb */
2312
-        global $wpdb;
2313
-        if (! method_exists($wpdb, $wpdb_method)) {
2314
-            throw new EE_Error(sprintf(__(
2315
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2316
-                'event_espresso'
2317
-            ), $wpdb_method));
2318
-        }
2319
-        if (WP_DEBUG) {
2320
-            $old_show_errors_value = $wpdb->show_errors;
2321
-            $wpdb->show_errors(false);
2322
-        }
2323
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2324
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2325
-        if (WP_DEBUG) {
2326
-            $wpdb->show_errors($old_show_errors_value);
2327
-            if (! empty($wpdb->last_error)) {
2328
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2329
-            }
2330
-            if ($result === false) {
2331
-                throw new EE_Error(sprintf(__(
2332
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2333
-                    'event_espresso'
2334
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2335
-            }
2336
-        } elseif ($result === false) {
2337
-            EE_Error::add_error(
2338
-                sprintf(
2339
-                    __(
2340
-                        '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"',
2341
-                        'event_espresso'
2342
-                    ),
2343
-                    $wpdb_method,
2344
-                    var_export($arguments_to_provide, true),
2345
-                    $wpdb->last_error
2346
-                ),
2347
-                __FILE__,
2348
-                __FUNCTION__,
2349
-                __LINE__
2350
-            );
2351
-        }
2352
-        return $result;
2353
-    }
2354
-
2355
-
2356
-
2357
-    /**
2358
-     * Attempts to run the indicated WPDB method with the provided arguments,
2359
-     * and if there's an error tries to verify the DB is correct. Uses
2360
-     * the static property EEM_Base::$_db_verification_level to determine whether
2361
-     * we should try to fix the EE core db, the addons, or just give up
2362
-     *
2363
-     * @param string $wpdb_method
2364
-     * @param array  $arguments_to_provide
2365
-     * @return mixed
2366
-     */
2367
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2368
-    {
2369
-        /** @type WPDB $wpdb */
2370
-        global $wpdb;
2371
-        $wpdb->last_error = null;
2372
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2373
-        // was there an error running the query? but we don't care on new activations
2374
-        // (we're going to setup the DB anyway on new activations)
2375
-        if (($result === false || ! empty($wpdb->last_error))
2376
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2377
-        ) {
2378
-            switch (EEM_Base::$_db_verification_level) {
2379
-                case EEM_Base::db_verified_none:
2380
-                    // let's double-check core's DB
2381
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2382
-                    break;
2383
-                case EEM_Base::db_verified_core:
2384
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2385
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2386
-                    break;
2387
-                case EEM_Base::db_verified_addons:
2388
-                    // ummmm... you in trouble
2389
-                    return $result;
2390
-                    break;
2391
-            }
2392
-            if (! empty($error_message)) {
2393
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2394
-                trigger_error($error_message);
2395
-            }
2396
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2397
-        }
2398
-        return $result;
2399
-    }
2400
-
2401
-
2402
-
2403
-    /**
2404
-     * Verifies the EE core database is up-to-date and records that we've done it on
2405
-     * EEM_Base::$_db_verification_level
2406
-     *
2407
-     * @param string $wpdb_method
2408
-     * @param array  $arguments_to_provide
2409
-     * @return string
2410
-     */
2411
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2412
-    {
2413
-        /** @type WPDB $wpdb */
2414
-        global $wpdb;
2415
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2416
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2417
-        $error_message = sprintf(
2418
-            __(
2419
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2420
-                'event_espresso'
2421
-            ),
2422
-            $wpdb->last_error,
2423
-            $wpdb_method,
2424
-            wp_json_encode($arguments_to_provide)
2425
-        );
2426
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2427
-        return $error_message;
2428
-    }
2429
-
2430
-
2431
-
2432
-    /**
2433
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2434
-     * EEM_Base::$_db_verification_level
2435
-     *
2436
-     * @param $wpdb_method
2437
-     * @param $arguments_to_provide
2438
-     * @return string
2439
-     */
2440
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2441
-    {
2442
-        /** @type WPDB $wpdb */
2443
-        global $wpdb;
2444
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2445
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2446
-        $error_message = sprintf(
2447
-            __(
2448
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2449
-                'event_espresso'
2450
-            ),
2451
-            $wpdb->last_error,
2452
-            $wpdb_method,
2453
-            wp_json_encode($arguments_to_provide)
2454
-        );
2455
-        EE_System::instance()->initialize_addons();
2456
-        return $error_message;
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2463
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2464
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2465
-     * ..."
2466
-     *
2467
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2468
-     * @return string
2469
-     */
2470
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2471
-    {
2472
-        return " FROM " . $model_query_info->get_full_join_sql() .
2473
-               $model_query_info->get_where_sql() .
2474
-               $model_query_info->get_group_by_sql() .
2475
-               $model_query_info->get_having_sql() .
2476
-               $model_query_info->get_order_by_sql() .
2477
-               $model_query_info->get_limit_sql();
2478
-    }
2479
-
2480
-
2481
-
2482
-    /**
2483
-     * Set to easily debug the next X queries ran from this model.
2484
-     *
2485
-     * @param int $count
2486
-     */
2487
-    public function show_next_x_db_queries($count = 1)
2488
-    {
2489
-        $this->_show_next_x_db_queries = $count;
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * @param $sql_query
2496
-     */
2497
-    public function show_db_query_if_previously_requested($sql_query)
2498
-    {
2499
-        if ($this->_show_next_x_db_queries > 0) {
2500
-            echo $sql_query;
2501
-            $this->_show_next_x_db_queries--;
2502
-        }
2503
-    }
2504
-
2505
-
2506
-
2507
-    /**
2508
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2509
-     * There are the 3 cases:
2510
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2511
-     * $otherModelObject has no ID, it is first saved.
2512
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2513
-     * has no ID, it is first saved.
2514
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2515
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2516
-     * join table
2517
-     *
2518
-     * @param        EE_Base_Class                     /int $thisModelObject
2519
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2520
-     * @param string $relationName                     , key in EEM_Base::_relations
2521
-     *                                                 an attendee to a group, you also want to specify which role they
2522
-     *                                                 will have in that group. So you would use this parameter to
2523
-     *                                                 specify array('role-column-name'=>'role-id')
2524
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2525
-     *                                                 to for relation to methods that allow you to further specify
2526
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2527
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2528
-     *                                                 because these will be inserted in any new rows created as well.
2529
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2530
-     * @throws EE_Error
2531
-     */
2532
-    public function add_relationship_to(
2533
-        $id_or_obj,
2534
-        $other_model_id_or_obj,
2535
-        $relationName,
2536
-        $extra_join_model_fields_n_values = array()
2537
-    ) {
2538
-        $relation_obj = $this->related_settings_for($relationName);
2539
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2540
-    }
2541
-
2542
-
2543
-
2544
-    /**
2545
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2546
-     * There are the 3 cases:
2547
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2548
-     * error
2549
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2550
-     * an error
2551
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2552
-     *
2553
-     * @param        EE_Base_Class /int $id_or_obj
2554
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2555
-     * @param string $relationName key in EEM_Base::_relations
2556
-     * @return boolean of success
2557
-     * @throws EE_Error
2558
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2559
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2560
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2561
-     *                             because these will be inserted in any new rows created as well.
2562
-     */
2563
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2564
-    {
2565
-        $relation_obj = $this->related_settings_for($relationName);
2566
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2567
-    }
2568
-
2569
-
2570
-
2571
-    /**
2572
-     * @param mixed           $id_or_obj
2573
-     * @param string          $relationName
2574
-     * @param array           $where_query_params
2575
-     * @param EE_Base_Class[] objects to which relations were removed
2576
-     * @return \EE_Base_Class[]
2577
-     * @throws EE_Error
2578
-     */
2579
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2580
-    {
2581
-        $relation_obj = $this->related_settings_for($relationName);
2582
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2583
-    }
2584
-
2585
-
2586
-
2587
-    /**
2588
-     * Gets all the related items of the specified $model_name, using $query_params.
2589
-     * Note: by default, we remove the "default query params"
2590
-     * because we want to get even deleted items etc.
2591
-     *
2592
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2593
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2594
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2595
-     * @return EE_Base_Class[]
2596
-     * @throws EE_Error
2597
-     */
2598
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2599
-    {
2600
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2601
-        $relation_settings = $this->related_settings_for($model_name);
2602
-        return $relation_settings->get_all_related($model_obj, $query_params);
2603
-    }
2604
-
2605
-
2606
-
2607
-    /**
2608
-     * Deletes all the model objects across the relation indicated by $model_name
2609
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2610
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2611
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2612
-     *
2613
-     * @param EE_Base_Class|int|string $id_or_obj
2614
-     * @param string                   $model_name
2615
-     * @param array                    $query_params
2616
-     * @return int how many deleted
2617
-     * @throws EE_Error
2618
-     */
2619
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2620
-    {
2621
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2622
-        $relation_settings = $this->related_settings_for($model_name);
2623
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2624
-    }
2625
-
2626
-
2627
-
2628
-    /**
2629
-     * Hard deletes all the model objects across the relation indicated by $model_name
2630
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2631
-     * the model objects can't be hard deleted because of blocking related model objects,
2632
-     * just does a soft-delete on them instead.
2633
-     *
2634
-     * @param EE_Base_Class|int|string $id_or_obj
2635
-     * @param string                   $model_name
2636
-     * @param array                    $query_params
2637
-     * @return int how many deleted
2638
-     * @throws EE_Error
2639
-     */
2640
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2641
-    {
2642
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2643
-        $relation_settings = $this->related_settings_for($model_name);
2644
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2645
-    }
2646
-
2647
-
2648
-
2649
-    /**
2650
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2651
-     * unless otherwise specified in the $query_params
2652
-     *
2653
-     * @param        int             /EE_Base_Class $id_or_obj
2654
-     * @param string $model_name     like 'Event', or 'Registration'
2655
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2656
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2657
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2658
-     *                               that by the setting $distinct to TRUE;
2659
-     * @return int
2660
-     * @throws EE_Error
2661
-     */
2662
-    public function count_related(
2663
-        $id_or_obj,
2664
-        $model_name,
2665
-        $query_params = array(),
2666
-        $field_to_count = null,
2667
-        $distinct = false
2668
-    ) {
2669
-        $related_model = $this->get_related_model_obj($model_name);
2670
-        // we're just going to use the query params on the related model's normal get_all query,
2671
-        // except add a condition to say to match the current mod
2672
-        if (! isset($query_params['default_where_conditions'])) {
2673
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2674
-        }
2675
-        $this_model_name = $this->get_this_model_name();
2676
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2677
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2678
-        return $related_model->count($query_params, $field_to_count, $distinct);
2679
-    }
2680
-
2681
-
2682
-
2683
-    /**
2684
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2685
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2686
-     *
2687
-     * @param        int           /EE_Base_Class $id_or_obj
2688
-     * @param string $model_name   like 'Event', or 'Registration'
2689
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2690
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2691
-     * @return float
2692
-     * @throws EE_Error
2693
-     */
2694
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2695
-    {
2696
-        $related_model = $this->get_related_model_obj($model_name);
2697
-        if (! is_array($query_params)) {
2698
-            EE_Error::doing_it_wrong(
2699
-                'EEM_Base::sum_related',
2700
-                sprintf(
2701
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2702
-                    gettype($query_params)
2703
-                ),
2704
-                '4.6.0'
2705
-            );
2706
-            $query_params = array();
2707
-        }
2708
-        // we're just going to use the query params on the related model's normal get_all query,
2709
-        // except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2711
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
-        }
2713
-        $this_model_name = $this->get_this_model_name();
2714
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2716
-        return $related_model->sum($query_params, $field_to_sum);
2717
-    }
2718
-
2719
-
2720
-
2721
-    /**
2722
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
-     * $modelObject
2724
-     *
2725
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2728
-     * @return EE_Base_Class
2729
-     * @throws EE_Error
2730
-     */
2731
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
-    {
2733
-        $query_params['limit'] = 1;
2734
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
-        if ($results) {
2736
-            return array_shift($results);
2737
-        }
2738
-        return null;
2739
-    }
2740
-
2741
-
2742
-
2743
-    /**
2744
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
-     *
2746
-     * @return string
2747
-     */
2748
-    public function get_this_model_name()
2749
-    {
2750
-        return str_replace("EEM_", "", get_class($this));
2751
-    }
2752
-
2753
-
2754
-
2755
-    /**
2756
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
-     *
2758
-     * @return EE_Any_Foreign_Model_Name_Field
2759
-     * @throws EE_Error
2760
-     */
2761
-    public function get_field_containing_related_model_name()
2762
-    {
2763
-        foreach ($this->field_settings(true) as $field) {
2764
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
-                $field_with_model_name = $field;
2766
-            }
2767
-        }
2768
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
-            throw new EE_Error(sprintf(
2770
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2771
-                $this->get_this_model_name()
2772
-            ));
2773
-        }
2774
-        return $field_with_model_name;
2775
-    }
2776
-
2777
-
2778
-
2779
-    /**
2780
-     * Inserts a new entry into the database, for each table.
2781
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2782
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2783
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2784
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2785
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2786
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2787
-     *
2788
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2789
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2790
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2791
-     *                              of EEM_Base)
2792
-     * @return int|string new primary key on main table that got inserted
2793
-     * @throws EE_Error
2794
-     */
2795
-    public function insert($field_n_values)
2796
-    {
2797
-        /**
2798
-         * Filters the fields and their values before inserting an item using the models
2799
-         *
2800
-         * @param array    $fields_n_values keys are the fields and values are their new values
2801
-         * @param EEM_Base $model           the model used
2802
-         */
2803
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2804
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2805
-            $main_table = $this->_get_main_table();
2806
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2807
-            if ($new_id !== false) {
2808
-                foreach ($this->_get_other_tables() as $other_table) {
2809
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2810
-                }
2811
-            }
2812
-            /**
2813
-             * Done just after attempting to insert a new model object
2814
-             *
2815
-             * @param EEM_Base   $model           used
2816
-             * @param array      $fields_n_values fields and their values
2817
-             * @param int|string the              ID of the newly-inserted model object
2818
-             */
2819
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2820
-            return $new_id;
2821
-        }
2822
-        return false;
2823
-    }
2824
-
2825
-
2826
-
2827
-    /**
2828
-     * Checks that the result would satisfy the unique indexes on this model
2829
-     *
2830
-     * @param array  $field_n_values
2831
-     * @param string $action
2832
-     * @return boolean
2833
-     * @throws EE_Error
2834
-     */
2835
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2836
-    {
2837
-        foreach ($this->unique_indexes() as $index_name => $index) {
2838
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2839
-            if ($this->exists(array($uniqueness_where_params))) {
2840
-                EE_Error::add_error(
2841
-                    sprintf(
2842
-                        __(
2843
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2844
-                            "event_espresso"
2845
-                        ),
2846
-                        $action,
2847
-                        $this->_get_class_name(),
2848
-                        $index_name,
2849
-                        implode(",", $index->field_names()),
2850
-                        http_build_query($uniqueness_where_params)
2851
-                    ),
2852
-                    __FILE__,
2853
-                    __FUNCTION__,
2854
-                    __LINE__
2855
-                );
2856
-                return false;
2857
-            }
2858
-        }
2859
-        return true;
2860
-    }
2861
-
2862
-
2863
-
2864
-    /**
2865
-     * Checks the database for an item that conflicts (ie, if this item were
2866
-     * saved to the DB would break some uniqueness requirement, like a primary key
2867
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2868
-     * can be either an EE_Base_Class or an array of fields n values
2869
-     *
2870
-     * @param EE_Base_Class|array $obj_or_fields_array
2871
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2872
-     *                                                 when looking for conflicts
2873
-     *                                                 (ie, if false, we ignore the model object's primary key
2874
-     *                                                 when finding "conflicts". If true, it's also considered).
2875
-     *                                                 Only works for INT primary key,
2876
-     *                                                 STRING primary keys cannot be ignored
2877
-     * @throws EE_Error
2878
-     * @return EE_Base_Class|array
2879
-     */
2880
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2881
-    {
2882
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2883
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2884
-        } elseif (is_array($obj_or_fields_array)) {
2885
-            $fields_n_values = $obj_or_fields_array;
2886
-        } else {
2887
-            throw new EE_Error(
2888
-                sprintf(
2889
-                    __(
2890
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2891
-                        "event_espresso"
2892
-                    ),
2893
-                    get_class($this),
2894
-                    $obj_or_fields_array
2895
-                )
2896
-            );
2897
-        }
2898
-        $query_params = array();
2899
-        if ($this->has_primary_key_field()
2900
-            && ($include_primary_key
2901
-                || $this->get_primary_key_field()
2902
-                   instanceof
2903
-                   EE_Primary_Key_String_Field)
2904
-            && isset($fields_n_values[ $this->primary_key_name() ])
2905
-        ) {
2906
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2907
-        }
2908
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2909
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2910
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2911
-        }
2912
-        // if there is nothing to base this search on, then we shouldn't find anything
2913
-        if (empty($query_params)) {
2914
-            return array();
2915
-        }
2916
-        return $this->get_one($query_params);
2917
-    }
2918
-
2919
-
2920
-
2921
-    /**
2922
-     * Like count, but is optimized and returns a boolean instead of an int
2923
-     *
2924
-     * @param array $query_params
2925
-     * @return boolean
2926
-     * @throws EE_Error
2927
-     */
2928
-    public function exists($query_params)
2929
-    {
2930
-        $query_params['limit'] = 1;
2931
-        return $this->count($query_params) > 0;
2932
-    }
2933
-
2934
-
2935
-
2936
-    /**
2937
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2938
-     *
2939
-     * @param int|string $id
2940
-     * @return boolean
2941
-     * @throws EE_Error
2942
-     */
2943
-    public function exists_by_ID($id)
2944
-    {
2945
-        return $this->exists(
2946
-            array(
2947
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2948
-                array(
2949
-                    $this->primary_key_name() => $id,
2950
-                ),
2951
-            )
2952
-        );
2953
-    }
2954
-
2955
-
2956
-
2957
-    /**
2958
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2959
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2960
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2961
-     * on the main table)
2962
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2963
-     * cases where we want to call it directly rather than via insert().
2964
-     *
2965
-     * @access   protected
2966
-     * @param EE_Table_Base $table
2967
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2968
-     *                                       float
2969
-     * @param int           $new_id          for now we assume only int keys
2970
-     * @throws EE_Error
2971
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2972
-     * @return int ID of new row inserted, or FALSE on failure
2973
-     */
2974
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2975
-    {
2976
-        global $wpdb;
2977
-        $insertion_col_n_values = array();
2978
-        $format_for_insertion = array();
2979
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2980
-        foreach ($fields_on_table as $field_name => $field_obj) {
2981
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2982
-            if ($field_obj->is_auto_increment()) {
2983
-                continue;
2984
-            }
2985
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2986
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2987
-            if ($prepared_value !== null) {
2988
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2989
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2990
-            }
2991
-        }
2992
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2993
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2994
-            // so add the fk to the main table as a column
2995
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2996
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2997
-        }
2998
-        // insert the new entry
2999
-        $result = $this->_do_wpdb_query(
3000
-            'insert',
3001
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3002
-        );
3003
-        if ($result === false) {
3004
-            return false;
3005
-        }
3006
-        // ok, now what do we return for the ID of the newly-inserted thing?
3007
-        if ($this->has_primary_key_field()) {
3008
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3009
-                return $wpdb->insert_id;
3010
-            }
3011
-            // it's not an auto-increment primary key, so
3012
-            // it must have been supplied
3013
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3014
-        }
3015
-        // we can't return a  primary key because there is none. instead return
3016
-        // a unique string indicating this model
3017
-        return $this->get_index_primary_key_string($fields_n_values);
3018
-    }
3019
-
3020
-
3021
-
3022
-    /**
3023
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3024
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3025
-     * and there is no default, we pass it along. WPDB will take care of it)
3026
-     *
3027
-     * @param EE_Model_Field_Base $field_obj
3028
-     * @param array               $fields_n_values
3029
-     * @return mixed string|int|float depending on what the table column will be expecting
3030
-     * @throws EE_Error
3031
-     */
3032
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3033
-    {
3034
-        // if this field doesn't allow nullable, don't allow it
3035
-        if (! $field_obj->is_nullable()
3036
-            && (
3037
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3038
-                || $fields_n_values[ $field_obj->get_name() ] === null
3039
-            )
3040
-        ) {
3041
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3042
-        }
3043
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3044
-            ? $fields_n_values[ $field_obj->get_name() ]
3045
-            : null;
3046
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3047
-    }
3048
-
3049
-
3050
-
3051
-    /**
3052
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3053
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3054
-     * the field's prepare_for_set() method.
3055
-     *
3056
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3057
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3058
-     *                                   top of file)
3059
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3060
-     *                                   $value is a custom selection
3061
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3062
-     */
3063
-    private function _prepare_value_for_use_in_db($value, $field)
3064
-    {
3065
-        if ($field && $field instanceof EE_Model_Field_Base) {
3066
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3067
-            switch ($this->_values_already_prepared_by_model_object) {
3068
-                /** @noinspection PhpMissingBreakStatementInspection */
3069
-                case self::not_prepared_by_model_object:
3070
-                    $value = $field->prepare_for_set($value);
3071
-                // purposefully left out "return"
3072
-                case self::prepared_by_model_object:
3073
-                    /** @noinspection SuspiciousAssignmentsInspection */
3074
-                    $value = $field->prepare_for_use_in_db($value);
3075
-                case self::prepared_for_use_in_db:
3076
-                    // leave the value alone
3077
-            }
3078
-            return $value;
3079
-            // phpcs:enable
3080
-        }
3081
-        return $value;
3082
-    }
3083
-
3084
-
3085
-
3086
-    /**
3087
-     * Returns the main table on this model
3088
-     *
3089
-     * @return EE_Primary_Table
3090
-     * @throws EE_Error
3091
-     */
3092
-    protected function _get_main_table()
3093
-    {
3094
-        foreach ($this->_tables as $table) {
3095
-            if ($table instanceof EE_Primary_Table) {
3096
-                return $table;
3097
-            }
3098
-        }
3099
-        throw new EE_Error(sprintf(__(
3100
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3101
-            'event_espresso'
3102
-        ), get_class($this)));
3103
-    }
3104
-
3105
-
3106
-
3107
-    /**
3108
-     * table
3109
-     * returns EE_Primary_Table table name
3110
-     *
3111
-     * @return string
3112
-     * @throws EE_Error
3113
-     */
3114
-    public function table()
3115
-    {
3116
-        return $this->_get_main_table()->get_table_name();
3117
-    }
3118
-
3119
-
3120
-
3121
-    /**
3122
-     * table
3123
-     * returns first EE_Secondary_Table table name
3124
-     *
3125
-     * @return string
3126
-     */
3127
-    public function second_table()
3128
-    {
3129
-        // grab second table from tables array
3130
-        $second_table = end($this->_tables);
3131
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3132
-    }
3133
-
3134
-
3135
-
3136
-    /**
3137
-     * get_table_obj_by_alias
3138
-     * returns table name given it's alias
3139
-     *
3140
-     * @param string $table_alias
3141
-     * @return EE_Primary_Table | EE_Secondary_Table
3142
-     */
3143
-    public function get_table_obj_by_alias($table_alias = '')
3144
-    {
3145
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3146
-    }
3147
-
3148
-
3149
-
3150
-    /**
3151
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3152
-     *
3153
-     * @return EE_Secondary_Table[]
3154
-     */
3155
-    protected function _get_other_tables()
3156
-    {
3157
-        $other_tables = array();
3158
-        foreach ($this->_tables as $table_alias => $table) {
3159
-            if ($table instanceof EE_Secondary_Table) {
3160
-                $other_tables[ $table_alias ] = $table;
3161
-            }
3162
-        }
3163
-        return $other_tables;
3164
-    }
3165
-
3166
-
3167
-
3168
-    /**
3169
-     * Finds all the fields that correspond to the given table
3170
-     *
3171
-     * @param string $table_alias , array key in EEM_Base::_tables
3172
-     * @return EE_Model_Field_Base[]
3173
-     */
3174
-    public function _get_fields_for_table($table_alias)
3175
-    {
3176
-        return $this->_fields[ $table_alias ];
3177
-    }
3178
-
3179
-
3180
-
3181
-    /**
3182
-     * Recurses through all the where parameters, and finds all the related models we'll need
3183
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3184
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3185
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3186
-     * related Registration, Transaction, and Payment models.
3187
-     *
3188
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3189
-     * @return EE_Model_Query_Info_Carrier
3190
-     * @throws EE_Error
3191
-     */
3192
-    public function _extract_related_models_from_query($query_params)
3193
-    {
3194
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3195
-        if (array_key_exists(0, $query_params)) {
3196
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3197
-        }
3198
-        if (array_key_exists('group_by', $query_params)) {
3199
-            if (is_array($query_params['group_by'])) {
3200
-                $this->_extract_related_models_from_sub_params_array_values(
3201
-                    $query_params['group_by'],
3202
-                    $query_info_carrier,
3203
-                    'group_by'
3204
-                );
3205
-            } elseif (! empty($query_params['group_by'])) {
3206
-                $this->_extract_related_model_info_from_query_param(
3207
-                    $query_params['group_by'],
3208
-                    $query_info_carrier,
3209
-                    'group_by'
3210
-                );
3211
-            }
3212
-        }
3213
-        if (array_key_exists('having', $query_params)) {
3214
-            $this->_extract_related_models_from_sub_params_array_keys(
3215
-                $query_params[0],
3216
-                $query_info_carrier,
3217
-                'having'
3218
-            );
3219
-        }
3220
-        if (array_key_exists('order_by', $query_params)) {
3221
-            if (is_array($query_params['order_by'])) {
3222
-                $this->_extract_related_models_from_sub_params_array_keys(
3223
-                    $query_params['order_by'],
3224
-                    $query_info_carrier,
3225
-                    'order_by'
3226
-                );
3227
-            } elseif (! empty($query_params['order_by'])) {
3228
-                $this->_extract_related_model_info_from_query_param(
3229
-                    $query_params['order_by'],
3230
-                    $query_info_carrier,
3231
-                    'order_by'
3232
-                );
3233
-            }
3234
-        }
3235
-        if (array_key_exists('force_join', $query_params)) {
3236
-            $this->_extract_related_models_from_sub_params_array_values(
3237
-                $query_params['force_join'],
3238
-                $query_info_carrier,
3239
-                'force_join'
3240
-            );
3241
-        }
3242
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3243
-        return $query_info_carrier;
3244
-    }
3245
-
3246
-
3247
-
3248
-    /**
3249
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3250
-     *
3251
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3252
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3253
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3254
-     * @throws EE_Error
3255
-     * @return \EE_Model_Query_Info_Carrier
3256
-     */
3257
-    private function _extract_related_models_from_sub_params_array_keys(
3258
-        $sub_query_params,
3259
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3260
-        $query_param_type
3261
-    ) {
3262
-        if (! empty($sub_query_params)) {
3263
-            $sub_query_params = (array) $sub_query_params;
3264
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3265
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3266
-                $this->_extract_related_model_info_from_query_param(
3267
-                    $param,
3268
-                    $model_query_info_carrier,
3269
-                    $query_param_type
3270
-                );
3271
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3272
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3273
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3274
-                // of array('Registration.TXN_ID'=>23)
3275
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3276
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3277
-                    if (! is_array($possibly_array_of_params)) {
3278
-                        throw new EE_Error(sprintf(
3279
-                            __(
3280
-                                "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'))",
3281
-                                "event_espresso"
3282
-                            ),
3283
-                            $param,
3284
-                            $possibly_array_of_params
3285
-                        ));
3286
-                    }
3287
-                    $this->_extract_related_models_from_sub_params_array_keys(
3288
-                        $possibly_array_of_params,
3289
-                        $model_query_info_carrier,
3290
-                        $query_param_type
3291
-                    );
3292
-                } elseif ($query_param_type === 0 // ie WHERE
3293
-                          && is_array($possibly_array_of_params)
3294
-                          && isset($possibly_array_of_params[2])
3295
-                          && $possibly_array_of_params[2] == true
3296
-                ) {
3297
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3298
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3299
-                    // from which we should extract query parameters!
3300
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3301
-                        throw new EE_Error(sprintf(__(
3302
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303
-                            "event_espresso"
3304
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3305
-                    }
3306
-                    $this->_extract_related_model_info_from_query_param(
3307
-                        $possibly_array_of_params[1],
3308
-                        $model_query_info_carrier,
3309
-                        $query_param_type
3310
-                    );
3311
-                }
3312
-            }
3313
-        }
3314
-        return $model_query_info_carrier;
3315
-    }
3316
-
3317
-
3318
-
3319
-    /**
3320
-     * For extracting related models from forced_joins, where the array values contain the info about what
3321
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3322
-     *
3323
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3324
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3325
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3326
-     * @throws EE_Error
3327
-     * @return \EE_Model_Query_Info_Carrier
3328
-     */
3329
-    private function _extract_related_models_from_sub_params_array_values(
3330
-        $sub_query_params,
3331
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3332
-        $query_param_type
3333
-    ) {
3334
-        if (! empty($sub_query_params)) {
3335
-            if (! is_array($sub_query_params)) {
3336
-                throw new EE_Error(sprintf(
3337
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3338
-                    $sub_query_params
3339
-                ));
3340
-            }
3341
-            foreach ($sub_query_params as $param) {
3342
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3343
-                $this->_extract_related_model_info_from_query_param(
3344
-                    $param,
3345
-                    $model_query_info_carrier,
3346
-                    $query_param_type
3347
-                );
3348
-            }
3349
-        }
3350
-        return $model_query_info_carrier;
3351
-    }
3352
-
3353
-
3354
-    /**
3355
-     * Extract all the query parts from  model query params
3356
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3357
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3358
-     * but use them in a different order. Eg, we need to know what models we are querying
3359
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3360
-     * other models before we can finalize the where clause SQL.
3361
-     *
3362
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3363
-     * @throws EE_Error
3364
-     * @return EE_Model_Query_Info_Carrier
3365
-     * @throws ModelConfigurationException
3366
-     */
3367
-    public function _create_model_query_info_carrier($query_params)
3368
-    {
3369
-        if (! is_array($query_params)) {
3370
-            EE_Error::doing_it_wrong(
3371
-                'EEM_Base::_create_model_query_info_carrier',
3372
-                sprintf(
3373
-                    __(
3374
-                        '$query_params should be an array, you passed a variable of type %s',
3375
-                        'event_espresso'
3376
-                    ),
3377
-                    gettype($query_params)
3378
-                ),
3379
-                '4.6.0'
3380
-            );
3381
-            $query_params = array();
3382
-        }
3383
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3384
-        // first check if we should alter the query to account for caps or not
3385
-        // because the caps might require us to do extra joins
3386
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3387
-            $query_params[0] = array_replace_recursive(
3388
-                $query_params[0],
3389
-                $this->caps_where_conditions(
3390
-                    $query_params['caps']
3391
-                )
3392
-            );
3393
-        }
3394
-
3395
-        // check if we should alter the query to remove data related to protected
3396
-        // custom post types
3397
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3398
-            $where_param_key_for_password = $this->modelChainAndPassword();
3399
-            // only include if related to a cpt where no password has been set
3400
-            $query_params[0]['OR*nopassword'] = array(
3401
-                $where_param_key_for_password => '',
3402
-                $where_param_key_for_password . '*' => array('IS_NULL')
3403
-            );
3404
-        }
3405
-        $query_object = $this->_extract_related_models_from_query($query_params);
3406
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3407
-        foreach ($query_params[0] as $key => $value) {
3408
-            if (is_int($key)) {
3409
-                throw new EE_Error(
3410
-                    sprintf(
3411
-                        __(
3412
-                            "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.",
3413
-                            "event_espresso"
3414
-                        ),
3415
-                        $key,
3416
-                        var_export($value, true),
3417
-                        var_export($query_params, true),
3418
-                        get_class($this)
3419
-                    )
3420
-                );
3421
-            }
3422
-        }
3423
-        if (array_key_exists('default_where_conditions', $query_params)
3424
-            && ! empty($query_params['default_where_conditions'])
3425
-        ) {
3426
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3427
-        } else {
3428
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3429
-        }
3430
-        $query_params[0] = array_merge(
3431
-            $this->_get_default_where_conditions_for_models_in_query(
3432
-                $query_object,
3433
-                $use_default_where_conditions,
3434
-                $query_params[0]
3435
-            ),
3436
-            $query_params[0]
3437
-        );
3438
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3439
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3440
-        // So we need to setup a subquery and use that for the main join.
3441
-        // Note for now this only works on the primary table for the model.
3442
-        // So for instance, you could set the limit array like this:
3443
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3444
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3445
-            $query_object->set_main_model_join_sql(
3446
-                $this->_construct_limit_join_select(
3447
-                    $query_params['on_join_limit'][0],
3448
-                    $query_params['on_join_limit'][1]
3449
-                )
3450
-            );
3451
-        }
3452
-        // set limit
3453
-        if (array_key_exists('limit', $query_params)) {
3454
-            if (is_array($query_params['limit'])) {
3455
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3456
-                    $e = sprintf(
3457
-                        __(
3458
-                            "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)",
3459
-                            "event_espresso"
3460
-                        ),
3461
-                        http_build_query($query_params['limit'])
3462
-                    );
3463
-                    throw new EE_Error($e . "|" . $e);
3464
-                }
3465
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3466
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3467
-            } elseif (! empty($query_params['limit'])) {
3468
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3469
-            }
3470
-        }
3471
-        // set order by
3472
-        if (array_key_exists('order_by', $query_params)) {
3473
-            if (is_array($query_params['order_by'])) {
3474
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3475
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3476
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3477
-                if (array_key_exists('order', $query_params)) {
3478
-                    throw new EE_Error(
3479
-                        sprintf(
3480
-                            __(
3481
-                                "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 ",
3482
-                                "event_espresso"
3483
-                            ),
3484
-                            get_class($this),
3485
-                            implode(", ", array_keys($query_params['order_by'])),
3486
-                            implode(", ", $query_params['order_by']),
3487
-                            $query_params['order']
3488
-                        )
3489
-                    );
3490
-                }
3491
-                $this->_extract_related_models_from_sub_params_array_keys(
3492
-                    $query_params['order_by'],
3493
-                    $query_object,
3494
-                    'order_by'
3495
-                );
3496
-                // assume it's an array of fields to order by
3497
-                $order_array = array();
3498
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3499
-                    $order = $this->_extract_order($order);
3500
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3501
-                }
3502
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3503
-            } elseif (! empty($query_params['order_by'])) {
3504
-                $this->_extract_related_model_info_from_query_param(
3505
-                    $query_params['order_by'],
3506
-                    $query_object,
3507
-                    'order',
3508
-                    $query_params['order_by']
3509
-                );
3510
-                $order = isset($query_params['order'])
3511
-                    ? $this->_extract_order($query_params['order'])
3512
-                    : 'DESC';
3513
-                $query_object->set_order_by_sql(
3514
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3515
-                );
3516
-            }
3517
-        }
3518
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3519
-        if (! array_key_exists('order_by', $query_params)
3520
-            && array_key_exists('order', $query_params)
3521
-            && ! empty($query_params['order'])
3522
-        ) {
3523
-            $pk_field = $this->get_primary_key_field();
3524
-            $order = $this->_extract_order($query_params['order']);
3525
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3526
-        }
3527
-        // set group by
3528
-        if (array_key_exists('group_by', $query_params)) {
3529
-            if (is_array($query_params['group_by'])) {
3530
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3531
-                $group_by_array = array();
3532
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3533
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3534
-                }
3535
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3536
-            } elseif (! empty($query_params['group_by'])) {
3537
-                $query_object->set_group_by_sql(
3538
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3539
-                );
3540
-            }
3541
-        }
3542
-        // set having
3543
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3544
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3545
-        }
3546
-        // now, just verify they didn't pass anything wack
3547
-        foreach ($query_params as $query_key => $query_value) {
3548
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3549
-                throw new EE_Error(
3550
-                    sprintf(
3551
-                        __(
3552
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3553
-                            'event_espresso'
3554
-                        ),
3555
-                        $query_key,
3556
-                        get_class($this),
3557
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3558
-                        implode(',', $this->_allowed_query_params)
3559
-                    )
3560
-                );
3561
-            }
3562
-        }
3563
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3564
-        if (empty($main_model_join_sql)) {
3565
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3566
-        }
3567
-        return $query_object;
3568
-    }
3569
-
3570
-
3571
-
3572
-    /**
3573
-     * Gets the where conditions that should be imposed on the query based on the
3574
-     * context (eg reading frontend, backend, edit or delete).
3575
-     *
3576
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3577
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3578
-     * @throws EE_Error
3579
-     */
3580
-    public function caps_where_conditions($context = self::caps_read)
3581
-    {
3582
-        EEM_Base::verify_is_valid_cap_context($context);
3583
-        $cap_where_conditions = array();
3584
-        $cap_restrictions = $this->caps_missing($context);
3585
-        /**
3586
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3587
-         */
3588
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3589
-            $cap_where_conditions = array_replace_recursive(
3590
-                $cap_where_conditions,
3591
-                $restriction_if_no_cap->get_default_where_conditions()
3592
-            );
3593
-        }
3594
-        return apply_filters(
3595
-            'FHEE__EEM_Base__caps_where_conditions__return',
3596
-            $cap_where_conditions,
3597
-            $this,
3598
-            $context,
3599
-            $cap_restrictions
3600
-        );
3601
-    }
3602
-
3603
-
3604
-
3605
-    /**
3606
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3607
-     * otherwise throws an exception
3608
-     *
3609
-     * @param string $should_be_order_string
3610
-     * @return string either ASC, asc, DESC or desc
3611
-     * @throws EE_Error
3612
-     */
3613
-    private function _extract_order($should_be_order_string)
3614
-    {
3615
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3616
-            return $should_be_order_string;
3617
-        }
3618
-        throw new EE_Error(
3619
-            sprintf(
3620
-                __(
3621
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3622
-                    "event_espresso"
3623
-                ),
3624
-                get_class($this),
3625
-                $should_be_order_string
3626
-            )
3627
-        );
3628
-    }
3629
-
3630
-
3631
-
3632
-    /**
3633
-     * Looks at all the models which are included in this query, and asks each
3634
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3635
-     * so they can be merged
3636
-     *
3637
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3638
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3639
-     *                                                                  'none' means NO default where conditions will
3640
-     *                                                                  be used AT ALL during this query.
3641
-     *                                                                  'other_models_only' means default where
3642
-     *                                                                  conditions from other models will be used, but
3643
-     *                                                                  not for this primary model. 'all', the default,
3644
-     *                                                                  means default where conditions will apply as
3645
-     *                                                                  normal
3646
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3647
-     * @throws EE_Error
3648
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3649
-     */
3650
-    private function _get_default_where_conditions_for_models_in_query(
3651
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3652
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3653
-        $where_query_params = array()
3654
-    ) {
3655
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3656
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3657
-            throw new EE_Error(sprintf(
3658
-                __(
3659
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3660
-                    "event_espresso"
3661
-                ),
3662
-                $use_default_where_conditions,
3663
-                implode(", ", $allowed_used_default_where_conditions_values)
3664
-            ));
3665
-        }
3666
-        $universal_query_params = array();
3667
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3668
-            $universal_query_params = $this->_get_default_where_conditions();
3669
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3670
-            $universal_query_params = $this->_get_minimum_where_conditions();
3671
-        }
3672
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3673
-            $related_model = $this->get_related_model_obj($model_name);
3674
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3675
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3676
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3677
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3678
-            } else {
3679
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3680
-                continue;
3681
-            }
3682
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3683
-                $related_model_universal_where_params,
3684
-                $where_query_params,
3685
-                $related_model,
3686
-                $model_relation_path
3687
-            );
3688
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3689
-                $universal_query_params,
3690
-                $overrides
3691
-            );
3692
-        }
3693
-        return $universal_query_params;
3694
-    }
3695
-
3696
-
3697
-
3698
-    /**
3699
-     * Determines whether or not we should use default where conditions for the model in question
3700
-     * (this model, or other related models).
3701
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3702
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3703
-     * We should use default where conditions on related models when they requested to use default where conditions
3704
-     * on all models, or specifically just on other related models
3705
-     * @param      $default_where_conditions_value
3706
-     * @param bool $for_this_model false means this is for OTHER related models
3707
-     * @return bool
3708
-     */
3709
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3710
-    {
3711
-        return (
3712
-                   $for_this_model
3713
-                   && in_array(
3714
-                       $default_where_conditions_value,
3715
-                       array(
3716
-                           EEM_Base::default_where_conditions_all,
3717
-                           EEM_Base::default_where_conditions_this_only,
3718
-                           EEM_Base::default_where_conditions_minimum_others,
3719
-                       ),
3720
-                       true
3721
-                   )
3722
-               )
3723
-               || (
3724
-                   ! $for_this_model
3725
-                   && in_array(
3726
-                       $default_where_conditions_value,
3727
-                       array(
3728
-                           EEM_Base::default_where_conditions_all,
3729
-                           EEM_Base::default_where_conditions_others_only,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               );
3734
-    }
3735
-
3736
-    /**
3737
-     * Determines whether or not we should use default minimum conditions for the model in question
3738
-     * (this model, or other related models).
3739
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3740
-     * where conditions.
3741
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3742
-     * on this model or others
3743
-     * @param      $default_where_conditions_value
3744
-     * @param bool $for_this_model false means this is for OTHER related models
3745
-     * @return bool
3746
-     */
3747
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3748
-    {
3749
-        return (
3750
-                   $for_this_model
3751
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3752
-               )
3753
-               || (
3754
-                   ! $for_this_model
3755
-                   && in_array(
3756
-                       $default_where_conditions_value,
3757
-                       array(
3758
-                           EEM_Base::default_where_conditions_minimum_others,
3759
-                           EEM_Base::default_where_conditions_minimum_all,
3760
-                       ),
3761
-                       true
3762
-                   )
3763
-               );
3764
-    }
3765
-
3766
-
3767
-    /**
3768
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3769
-     * then we also add a special where condition which allows for that model's primary key
3770
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3771
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3772
-     *
3773
-     * @param array    $default_where_conditions
3774
-     * @param array    $provided_where_conditions
3775
-     * @param EEM_Base $model
3776
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3777
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3778
-     * @throws EE_Error
3779
-     */
3780
-    private function _override_defaults_or_make_null_friendly(
3781
-        $default_where_conditions,
3782
-        $provided_where_conditions,
3783
-        $model,
3784
-        $model_relation_path
3785
-    ) {
3786
-        $null_friendly_where_conditions = array();
3787
-        $none_overridden = true;
3788
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3789
-        foreach ($default_where_conditions as $key => $val) {
3790
-            if (isset($provided_where_conditions[ $key ])) {
3791
-                $none_overridden = false;
3792
-            } else {
3793
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3794
-            }
3795
-        }
3796
-        if ($none_overridden && $default_where_conditions) {
3797
-            if ($model->has_primary_key_field()) {
3798
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3799
-                                                                                . "."
3800
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3801
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	private static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					__(
561
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							__(
680
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
+	 *                                        array( array(
852
+	 *                                        'OR'=>array(
853
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
+	 *                                        )
856
+	 *                                        ),
857
+	 *                                        'limit'=>10,
858
+	 *                                        'group_by'=>'TXN_ID'
859
+	 *                                        ));
860
+	 *                                        get all the answers to the question titled "shirt size" for event with id
861
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
+	 *                                        'Question.QST_display_text'=>'shirt size',
863
+	 *                                        'Registration.Event.EVT_ID'=>12
864
+	 *                                        ),
865
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
866
+	 *                                        ));
867
+	 * @throws EE_Error
868
+	 */
869
+	public function get_all($query_params = array())
870
+	{
871
+		if (isset($query_params['limit'])
872
+			&& ! isset($query_params['group_by'])
873
+		) {
874
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
+		}
876
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
+	}
878
+
879
+
880
+
881
+	/**
882
+	 * Modifies the query parameters so we only get back model objects
883
+	 * that "belong" to the current user
884
+	 *
885
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 */
888
+	public function alter_query_params_to_only_include_mine($query_params = array())
889
+	{
890
+		$wp_user_field_name = $this->wp_user_field_name();
891
+		if ($wp_user_field_name) {
892
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
+		}
894
+		return $query_params;
895
+	}
896
+
897
+
898
+
899
+	/**
900
+	 * Returns the name of the field's name that points to the WP_User table
901
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
+	 * foreign key to the WP_User table)
903
+	 *
904
+	 * @return string|boolean string on success, boolean false when there is no
905
+	 * foreign key to the WP_User table
906
+	 */
907
+	public function wp_user_field_name()
908
+	{
909
+		try {
910
+			if (! empty($this->_model_chain_to_wp_user)) {
911
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
+				$last_model_name = end($models_to_follow_to_wp_users);
913
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
+			} else {
916
+				$model_with_fk_to_wp_users = $this;
917
+				$model_chain_to_wp_user = '';
918
+			}
919
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
921
+		} catch (EE_Error $e) {
922
+			return false;
923
+		}
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
930
+	 * (or transiently-related model) has a foreign key to the wp_users table;
931
+	 * useful for finding if model objects of this type are 'owned' by the current user.
932
+	 * This is an empty string when the foreign key is on this model and when it isn't,
933
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
934
+	 * (or transiently-related model)
935
+	 *
936
+	 * @return string
937
+	 */
938
+	public function model_chain_to_wp_user()
939
+	{
940
+		return $this->_model_chain_to_wp_user;
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
+	 * like how registrations don't have a foreign key to wp_users, but the
948
+	 * events they are for are), or is unrelated to wp users.
949
+	 * generally available
950
+	 *
951
+	 * @return boolean
952
+	 */
953
+	public function is_owned()
954
+	{
955
+		if ($this->model_chain_to_wp_user()) {
956
+			return true;
957
+		}
958
+		try {
959
+			$this->get_foreign_key_to('WP_User');
960
+			return true;
961
+		} catch (EE_Error $e) {
962
+			return false;
963
+		}
964
+	}
965
+
966
+
967
+	/**
968
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
+	 * the model)
971
+	 *
972
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
976
+	 *                                  override this and set the select to "*", or a specific column name, like
977
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
+	 *                                  the aliases used to refer to this selection, and values are to be
980
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
+	 * @throws EE_Error
984
+	 * @throws InvalidArgumentException
985
+	 */
986
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
+	{
988
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
+		;
990
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
991
+		$select_expressions = $columns_to_select === null
992
+			? $this->_construct_default_select_sql($model_query_info)
993
+			: '';
994
+		if ($this->_custom_selections instanceof CustomSelects) {
995
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
+			$select_expressions .= $select_expressions
997
+				? ', ' . $custom_expressions
998
+				: $custom_expressions;
999
+		}
1000
+
1001
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
+	 * method of including extra select information.
1010
+	 *
1011
+	 * @param array             $query_params
1012
+	 * @param null|array|string $columns_to_select
1013
+	 * @return null|CustomSelects
1014
+	 * @throws InvalidArgumentException
1015
+	 */
1016
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
+	{
1018
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
+			return null;
1020
+		}
1021
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
+		return new CustomSelects($selects);
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1030
+	 * but you can use the model query params to more easily
1031
+	 * take care of joins, field preparation etc.
1032
+	 *
1033
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
+	}
1050
+
1051
+
1052
+
1053
+	/**
1054
+	 * For creating a custom select statement
1055
+	 *
1056
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
+	 *                                 SQL, and 1=>is the datatype
1059
+	 * @throws EE_Error
1060
+	 * @return string
1061
+	 */
1062
+	private function _construct_select_from_input($columns_to_select)
1063
+	{
1064
+		if (is_array($columns_to_select)) {
1065
+			$select_sql_array = array();
1066
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
+					throw new EE_Error(
1069
+						sprintf(
1070
+							__(
1071
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
+								'event_espresso'
1073
+							),
1074
+							$selection_and_datatype,
1075
+							$alias
1076
+						)
1077
+					);
1078
+				}
1079
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
+					throw new EE_Error(
1081
+						sprintf(
1082
+							esc_html__(
1083
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
+								'event_espresso'
1085
+							),
1086
+							$selection_and_datatype[1],
1087
+							$selection_and_datatype[0],
1088
+							$alias,
1089
+							implode(', ', $this->_valid_wpdb_data_types)
1090
+						)
1091
+					);
1092
+				}
1093
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
+			}
1095
+			$columns_to_select_string = implode(', ', $select_sql_array);
1096
+		} else {
1097
+			$columns_to_select_string = $columns_to_select;
1098
+		}
1099
+		return $columns_to_select_string;
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
+	 *
1107
+	 * @return string
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function primary_key_name()
1111
+	{
1112
+		return $this->get_primary_key_field()->get_name();
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1118
+	 * If there is no primary key on this model, $id is treated as primary key string
1119
+	 *
1120
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1121
+	 * @return EE_Base_Class
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function get_one_by_ID($id)
1125
+	{
1126
+		if ($this->get_from_entity_map($id)) {
1127
+			return $this->get_from_entity_map($id);
1128
+		}
1129
+		$model_object = $this->get_one(
1130
+			$this->alter_query_params_to_restrict_by_ID(
1131
+				$id,
1132
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
+			)
1134
+		);
1135
+		$className = $this->_get_class_name();
1136
+		if ($model_object instanceof $className) {
1137
+			// make sure valid objects get added to the entity map
1138
+			// so that the next call to this method doesn't trigger another trip to the db
1139
+			$this->add_to_entity_map($model_object);
1140
+		}
1141
+		return $model_object;
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Alters query parameters to only get items with this ID are returned.
1148
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1149
+	 * or could just be a simple primary key ID
1150
+	 *
1151
+	 * @param int   $id
1152
+	 * @param array $query_params
1153
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157
+	{
1158
+		if (! isset($query_params[0])) {
1159
+			$query_params[0] = array();
1160
+		}
1161
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1162
+		if ($conditions_from_id === null) {
1163
+			$query_params[0][ $this->primary_key_name() ] = $id;
1164
+		} else {
1165
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1166
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1167
+		}
1168
+		return $query_params;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1175
+	 * array. If no item is found, null is returned.
1176
+	 *
1177
+	 * @param array $query_params like EEM_Base's $query_params variable.
1178
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1179
+	 * @throws EE_Error
1180
+	 */
1181
+	public function get_one($query_params = array())
1182
+	{
1183
+		if (! is_array($query_params)) {
1184
+			EE_Error::doing_it_wrong(
1185
+				'EEM_Base::get_one',
1186
+				sprintf(
1187
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1188
+					gettype($query_params)
1189
+				),
1190
+				'4.6.0'
1191
+			);
1192
+			$query_params = array();
1193
+		}
1194
+		$query_params['limit'] = 1;
1195
+		$items = $this->get_all($query_params);
1196
+		if (empty($items)) {
1197
+			return null;
1198
+		}
1199
+		return array_shift($items);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Returns the next x number of items in sequence from the given value as
1206
+	 * found in the database matching the given query conditions.
1207
+	 *
1208
+	 * @param mixed $current_field_value    Value used for the reference point.
1209
+	 * @param null  $field_to_order_by      What field is used for the
1210
+	 *                                      reference point.
1211
+	 * @param int   $limit                  How many to return.
1212
+	 * @param array $query_params           Extra conditions on the query.
1213
+	 * @param null  $columns_to_select      If left null, then an array of
1214
+	 *                                      EE_Base_Class objects is returned,
1215
+	 *                                      otherwise you can indicate just the
1216
+	 *                                      columns you want returned.
1217
+	 * @return EE_Base_Class[]|array
1218
+	 * @throws EE_Error
1219
+	 */
1220
+	public function next_x(
1221
+		$current_field_value,
1222
+		$field_to_order_by = null,
1223
+		$limit = 1,
1224
+		$query_params = array(),
1225
+		$columns_to_select = null
1226
+	) {
1227
+		return $this->_get_consecutive(
1228
+			$current_field_value,
1229
+			'>',
1230
+			$field_to_order_by,
1231
+			$limit,
1232
+			$query_params,
1233
+			$columns_to_select
1234
+		);
1235
+	}
1236
+
1237
+
1238
+
1239
+	/**
1240
+	 * Returns the previous x number of items in sequence from the given value
1241
+	 * as found in the database matching the given query conditions.
1242
+	 *
1243
+	 * @param mixed $current_field_value    Value used for the reference point.
1244
+	 * @param null  $field_to_order_by      What field is used for the
1245
+	 *                                      reference point.
1246
+	 * @param int   $limit                  How many to return.
1247
+	 * @param array $query_params           Extra conditions on the query.
1248
+	 * @param null  $columns_to_select      If left null, then an array of
1249
+	 *                                      EE_Base_Class objects is returned,
1250
+	 *                                      otherwise you can indicate just the
1251
+	 *                                      columns you want returned.
1252
+	 * @return EE_Base_Class[]|array
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function previous_x(
1256
+		$current_field_value,
1257
+		$field_to_order_by = null,
1258
+		$limit = 1,
1259
+		$query_params = array(),
1260
+		$columns_to_select = null
1261
+	) {
1262
+		return $this->_get_consecutive(
1263
+			$current_field_value,
1264
+			'<',
1265
+			$field_to_order_by,
1266
+			$limit,
1267
+			$query_params,
1268
+			$columns_to_select
1269
+		);
1270
+	}
1271
+
1272
+
1273
+
1274
+	/**
1275
+	 * Returns the next item in sequence from the given value as found in the
1276
+	 * database matching the given query conditions.
1277
+	 *
1278
+	 * @param mixed $current_field_value    Value used for the reference point.
1279
+	 * @param null  $field_to_order_by      What field is used for the
1280
+	 *                                      reference point.
1281
+	 * @param array $query_params           Extra conditions on the query.
1282
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1283
+	 *                                      object is returned, otherwise you
1284
+	 *                                      can indicate just the columns you
1285
+	 *                                      want and a single array indexed by
1286
+	 *                                      the columns will be returned.
1287
+	 * @return EE_Base_Class|null|array()
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function next(
1291
+		$current_field_value,
1292
+		$field_to_order_by = null,
1293
+		$query_params = array(),
1294
+		$columns_to_select = null
1295
+	) {
1296
+		$results = $this->_get_consecutive(
1297
+			$current_field_value,
1298
+			'>',
1299
+			$field_to_order_by,
1300
+			1,
1301
+			$query_params,
1302
+			$columns_to_select
1303
+		);
1304
+		return empty($results) ? null : reset($results);
1305
+	}
1306
+
1307
+
1308
+
1309
+	/**
1310
+	 * Returns the previous item in sequence from the given value as found in
1311
+	 * the database matching the given query conditions.
1312
+	 *
1313
+	 * @param mixed $current_field_value    Value used for the reference point.
1314
+	 * @param null  $field_to_order_by      What field is used for the
1315
+	 *                                      reference point.
1316
+	 * @param array $query_params           Extra conditions on the query.
1317
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1318
+	 *                                      object is returned, otherwise you
1319
+	 *                                      can indicate just the columns you
1320
+	 *                                      want and a single array indexed by
1321
+	 *                                      the columns will be returned.
1322
+	 * @return EE_Base_Class|null|array()
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	public function previous(
1326
+		$current_field_value,
1327
+		$field_to_order_by = null,
1328
+		$query_params = array(),
1329
+		$columns_to_select = null
1330
+	) {
1331
+		$results = $this->_get_consecutive(
1332
+			$current_field_value,
1333
+			'<',
1334
+			$field_to_order_by,
1335
+			1,
1336
+			$query_params,
1337
+			$columns_to_select
1338
+		);
1339
+		return empty($results) ? null : reset($results);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Returns the a consecutive number of items in sequence from the given
1346
+	 * value as found in the database matching the given query conditions.
1347
+	 *
1348
+	 * @param mixed  $current_field_value   Value used for the reference point.
1349
+	 * @param string $operand               What operand is used for the sequence.
1350
+	 * @param string $field_to_order_by     What field is used for the reference point.
1351
+	 * @param int    $limit                 How many to return.
1352
+	 * @param array  $query_params          Extra conditions on the query.
1353
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
+	 *                                      otherwise you can indicate just the columns you want returned.
1355
+	 * @return EE_Base_Class[]|array
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	protected function _get_consecutive(
1359
+		$current_field_value,
1360
+		$operand = '>',
1361
+		$field_to_order_by = null,
1362
+		$limit = 1,
1363
+		$query_params = array(),
1364
+		$columns_to_select = null
1365
+	) {
1366
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
+		if (empty($field_to_order_by)) {
1368
+			if ($this->has_primary_key_field()) {
1369
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1370
+			} else {
1371
+				if (WP_DEBUG) {
1372
+					throw new EE_Error(__(
1373
+						'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).',
1374
+						'event_espresso'
1375
+					));
1376
+				}
1377
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1378
+				return array();
1379
+			}
1380
+		}
1381
+		if (! is_array($query_params)) {
1382
+			EE_Error::doing_it_wrong(
1383
+				'EEM_Base::_get_consecutive',
1384
+				sprintf(
1385
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1386
+					gettype($query_params)
1387
+				),
1388
+				'4.6.0'
1389
+			);
1390
+			$query_params = array();
1391
+		}
1392
+		// let's add the where query param for consecutive look up.
1393
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
+		$query_params['limit'] = $limit;
1395
+		// set direction
1396
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1397
+		$query_params['order_by'] = $operand === '>'
1398
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1399
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1400
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1401
+		if (empty($columns_to_select)) {
1402
+			return $this->get_all($query_params);
1403
+		}
1404
+		// getting just the fields
1405
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1406
+	}
1407
+
1408
+
1409
+
1410
+	/**
1411
+	 * This sets the _timezone property after model object has been instantiated.
1412
+	 *
1413
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1414
+	 */
1415
+	public function set_timezone($timezone)
1416
+	{
1417
+		if ($timezone !== null) {
1418
+			$this->_timezone = $timezone;
1419
+		}
1420
+		// note we need to loop through relations and set the timezone on those objects as well.
1421
+		foreach ($this->_model_relations as $relation) {
1422
+			$relation->set_timezone($timezone);
1423
+		}
1424
+		// and finally we do the same for any datetime fields
1425
+		foreach ($this->_fields as $field) {
1426
+			if ($field instanceof EE_Datetime_Field) {
1427
+				$field->set_timezone($timezone);
1428
+			}
1429
+		}
1430
+	}
1431
+
1432
+
1433
+
1434
+	/**
1435
+	 * This just returns whatever is set for the current timezone.
1436
+	 *
1437
+	 * @access public
1438
+	 * @return string
1439
+	 */
1440
+	public function get_timezone()
1441
+	{
1442
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1443
+		if (empty($this->_timezone)) {
1444
+			foreach ($this->_fields as $field) {
1445
+				if ($field instanceof EE_Datetime_Field) {
1446
+					$this->set_timezone($field->get_timezone());
1447
+					break;
1448
+				}
1449
+			}
1450
+		}
1451
+		// if timezone STILL empty then return the default timezone for the site.
1452
+		if (empty($this->_timezone)) {
1453
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1454
+		}
1455
+		return $this->_timezone;
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This returns the date formats set for the given field name and also ensures that
1462
+	 * $this->_timezone property is set correctly.
1463
+	 *
1464
+	 * @since 4.6.x
1465
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1466
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1467
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1468
+	 * @return array formats in an array with the date format first, and the time format last.
1469
+	 */
1470
+	public function get_formats_for($field_name, $pretty = false)
1471
+	{
1472
+		$field_settings = $this->field_settings_for($field_name);
1473
+		// if not a valid EE_Datetime_Field then throw error
1474
+		if (! $field_settings instanceof EE_Datetime_Field) {
1475
+			throw new EE_Error(sprintf(__(
1476
+				'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.',
1477
+				'event_espresso'
1478
+			), $field_name));
1479
+		}
1480
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1481
+		// the field.
1482
+		$this->_timezone = $field_settings->get_timezone();
1483
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1484
+	}
1485
+
1486
+
1487
+
1488
+	/**
1489
+	 * This returns the current time in a format setup for a query on this model.
1490
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1491
+	 * it will return:
1492
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1493
+	 *  NOW
1494
+	 *  - or a unix timestamp (equivalent to time())
1495
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1496
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1497
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1498
+	 * @since 4.6.x
1499
+	 * @param string $field_name       The field the current time is needed for.
1500
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1501
+	 *                                 formatted string matching the set format for the field in the set timezone will
1502
+	 *                                 be returned.
1503
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1504
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1505
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1506
+	 *                                 exception is triggered.
1507
+	 */
1508
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1509
+	{
1510
+		$formats = $this->get_formats_for($field_name);
1511
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1512
+		if ($timestamp) {
1513
+			return $DateTime->format('U');
1514
+		}
1515
+		// not returning timestamp, so return formatted string in timezone.
1516
+		switch ($what) {
1517
+			case 'time':
1518
+				return $DateTime->format($formats[1]);
1519
+				break;
1520
+			case 'date':
1521
+				return $DateTime->format($formats[0]);
1522
+				break;
1523
+			default:
1524
+				return $DateTime->format(implode(' ', $formats));
1525
+				break;
1526
+		}
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1533
+	 * for the model are.  Returns a DateTime object.
1534
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1535
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1536
+	 * ignored.
1537
+	 *
1538
+	 * @param string $field_name      The field being setup.
1539
+	 * @param string $timestring      The date time string being used.
1540
+	 * @param string $incoming_format The format for the time string.
1541
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1542
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1543
+	 *                                format is
1544
+	 *                                'U', this is ignored.
1545
+	 * @return DateTime
1546
+	 * @throws EE_Error
1547
+	 */
1548
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1549
+	{
1550
+		// just using this to ensure the timezone is set correctly internally
1551
+		$this->get_formats_for($field_name);
1552
+		// load EEH_DTT_Helper
1553
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1554
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1555
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1556
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1563
+	 *
1564
+	 * @return EE_Table_Base[]
1565
+	 */
1566
+	public function get_tables()
1567
+	{
1568
+		return $this->_tables;
1569
+	}
1570
+
1571
+
1572
+
1573
+	/**
1574
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1575
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1576
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1577
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1578
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1579
+	 * model object with EVT_ID = 1
1580
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1581
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1582
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1583
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1584
+	 * are not specified)
1585
+	 *
1586
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1587
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1588
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1589
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1590
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1591
+	 *                                         ID=34, we'd use this method as follows:
1592
+	 *                                         EEM_Transaction::instance()->update(
1593
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1594
+	 *                                         array(array('TXN_ID'=>34)));
1595
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1596
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1597
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1598
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1599
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1600
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1601
+	 *                                         TRUE, it is assumed that you've already called
1602
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1603
+	 *                                         malicious javascript. However, if
1604
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1605
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1606
+	 *                                         and every other field, before insertion. We provide this parameter
1607
+	 *                                         because model objects perform their prepare_for_set function on all
1608
+	 *                                         their values, and so don't need to be called again (and in many cases,
1609
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1610
+	 *                                         prepare_for_set method...)
1611
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1612
+	 *                                         in this model's entity map according to $fields_n_values that match
1613
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1614
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1615
+	 *                                         could get out-of-sync with the database
1616
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1617
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1618
+	 *                                         bad)
1619
+	 * @throws EE_Error
1620
+	 */
1621
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622
+	{
1623
+		if (! is_array($query_params)) {
1624
+			EE_Error::doing_it_wrong(
1625
+				'EEM_Base::update',
1626
+				sprintf(
1627
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1628
+					gettype($query_params)
1629
+				),
1630
+				'4.6.0'
1631
+			);
1632
+			$query_params = array();
1633
+		}
1634
+		/**
1635
+		 * Action called before a model update call has been made.
1636
+		 *
1637
+		 * @param EEM_Base $model
1638
+		 * @param array    $fields_n_values the updated fields and their new values
1639
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1640
+		 */
1641
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1642
+		/**
1643
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1644
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1645
+		 *
1646
+		 * @param array    $fields_n_values fields and their new values
1647
+		 * @param EEM_Base $model           the model being queried
1648
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1649
+		 */
1650
+		$fields_n_values = (array) apply_filters(
1651
+			'FHEE__EEM_Base__update__fields_n_values',
1652
+			$fields_n_values,
1653
+			$this,
1654
+			$query_params
1655
+		);
1656
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1657
+		// to do that, for each table, verify that it's PK isn't null.
1658
+		$tables = $this->get_tables();
1659
+		// 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
1660
+		// NOTE: we should make this code more efficient by NOT querying twice
1661
+		// before the real update, but that needs to first go through ALPHA testing
1662
+		// as it's dangerous. says Mike August 8 2014
1663
+		// we want to make sure the default_where strategy is ignored
1664
+		$this->_ignore_where_strategy = true;
1665
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1666
+		foreach ($wpdb_select_results as $wpdb_result) {
1667
+			// type cast stdClass as array
1668
+			$wpdb_result = (array) $wpdb_result;
1669
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670
+			if ($this->has_primary_key_field()) {
1671
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
+			} else {
1673
+				// 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)
1674
+				$main_table_pk_value = null;
1675
+			}
1676
+			// 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
1677
+			// 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
1678
+			if (count($tables) > 1) {
1679
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1680
+				// in that table, and so we'll want to insert one
1681
+				foreach ($tables as $table_obj) {
1682
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683
+					// if there is no private key for this table on the results, it means there's no entry
1684
+					// in this table, right? so insert a row in the current table, using any fields available
1685
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
+						   && $wpdb_result[ $this_table_pk_column ])
1687
+					) {
1688
+						$success = $this->_insert_into_specific_table(
1689
+							$table_obj,
1690
+							$fields_n_values,
1691
+							$main_table_pk_value
1692
+						);
1693
+						// if we died here, report the error
1694
+						if (! $success) {
1695
+							return false;
1696
+						}
1697
+					}
1698
+				}
1699
+			}
1700
+			//              //and now check that if we have cached any models by that ID on the model, that
1701
+			//              //they also get updated properly
1702
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1703
+			//              if( $model_object ){
1704
+			//                  foreach( $fields_n_values as $field => $value ){
1705
+			//                      $model_object->set($field, $value);
1706
+			// let's make sure default_where strategy is followed now
1707
+			$this->_ignore_where_strategy = false;
1708
+		}
1709
+		// if we want to keep model objects in sync, AND
1710
+		// if this wasn't called from a model object (to update itself)
1711
+		// then we want to make sure we keep all the existing
1712
+		// model objects in sync with the db
1713
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1714
+			if ($this->has_primary_key_field()) {
1715
+				$model_objs_affected_ids = $this->get_col($query_params);
1716
+			} else {
1717
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1718
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1719
+				$model_objs_affected_ids = array();
1720
+				foreach ($models_affected_key_columns as $row) {
1721
+					$combined_index_key = $this->get_index_primary_key_string($row);
1722
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1723
+				}
1724
+			}
1725
+			if (! $model_objs_affected_ids) {
1726
+				// wait wait wait- if nothing was affected let's stop here
1727
+				return 0;
1728
+			}
1729
+			foreach ($model_objs_affected_ids as $id) {
1730
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1731
+				if ($model_obj_in_entity_map) {
1732
+					foreach ($fields_n_values as $field => $new_value) {
1733
+						$model_obj_in_entity_map->set($field, $new_value);
1734
+					}
1735
+				}
1736
+			}
1737
+			// if there is a primary key on this model, we can now do a slight optimization
1738
+			if ($this->has_primary_key_field()) {
1739
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1740
+				$query_params = array(
1741
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1742
+					'limit'                    => count($model_objs_affected_ids),
1743
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1744
+				);
1745
+			}
1746
+		}
1747
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
+		$SQL = "UPDATE "
1749
+			   . $model_query_info->get_full_join_sql()
1750
+			   . " SET "
1751
+			   . $this->_construct_update_sql($fields_n_values)
1752
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754
+		/**
1755
+		 * Action called after a model update call has been made.
1756
+		 *
1757
+		 * @param EEM_Base $model
1758
+		 * @param array    $fields_n_values the updated fields and their new values
1759
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1760
+		 * @param int      $rows_affected
1761
+		 */
1762
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
+		return $rows_affected;// how many supposedly got updated
1764
+	}
1765
+
1766
+
1767
+
1768
+	/**
1769
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1770
+	 * are teh values of the field specified (or by default the primary key field)
1771
+	 * that matched the query params. Note that you should pass the name of the
1772
+	 * model FIELD, not the database table's column name.
1773
+	 *
1774
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1775
+	 * @param string $field_to_select
1776
+	 * @return array just like $wpdb->get_col()
1777
+	 * @throws EE_Error
1778
+	 */
1779
+	public function get_col($query_params = array(), $field_to_select = null)
1780
+	{
1781
+		if ($field_to_select) {
1782
+			$field = $this->field_settings_for($field_to_select);
1783
+		} elseif ($this->has_primary_key_field()) {
1784
+			$field = $this->get_primary_key_field();
1785
+		} else {
1786
+			// no primary key, just grab the first column
1787
+			$field = reset($this->field_settings());
1788
+		}
1789
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1790
+		$select_expressions = $field->get_qualified_column();
1791
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1792
+		return $this->_do_wpdb_query('get_col', array($SQL));
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Returns a single column value for a single row from the database
1799
+	 *
1800
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1801
+	 * @param string $field_to_select @see EEM_Base::get_col()
1802
+	 * @return string
1803
+	 * @throws EE_Error
1804
+	 */
1805
+	public function get_var($query_params = array(), $field_to_select = null)
1806
+	{
1807
+		$query_params['limit'] = 1;
1808
+		$col = $this->get_col($query_params, $field_to_select);
1809
+		if (! empty($col)) {
1810
+			return reset($col);
1811
+		}
1812
+		return null;
1813
+	}
1814
+
1815
+
1816
+
1817
+	/**
1818
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1819
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1820
+	 * injection, but currently no further filtering is done
1821
+	 *
1822
+	 * @global      $wpdb
1823
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1824
+	 *                               be updated to in the DB
1825
+	 * @return string of SQL
1826
+	 * @throws EE_Error
1827
+	 */
1828
+	public function _construct_update_sql($fields_n_values)
1829
+	{
1830
+		/** @type WPDB $wpdb */
1831
+		global $wpdb;
1832
+		$cols_n_values = array();
1833
+		foreach ($fields_n_values as $field_name => $value) {
1834
+			$field_obj = $this->field_settings_for($field_name);
1835
+			// if the value is NULL, we want to assign the value to that.
1836
+			// wpdb->prepare doesn't really handle that properly
1837
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838
+			$value_sql = $prepared_value === null ? 'NULL'
1839
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1841
+		}
1842
+		return implode(",", $cols_n_values);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
+	 * Performs a HARD delete, meaning the database row should always be removed,
1850
+	 * not just have a flag field on it switched
1851
+	 * Wrapper for EEM_Base::delete_permanently()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @param boolean $allow_blocking
1855
+	 * @return int the number of rows deleted
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1859
+	{
1860
+		return $this->delete_permanently(
1861
+			array(
1862
+				array($this->get_primary_key_field()->get_name() => $id),
1863
+				'limit' => 1,
1864
+			),
1865
+			$allow_blocking
1866
+		);
1867
+	}
1868
+
1869
+
1870
+
1871
+	/**
1872
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1873
+	 * Wrapper for EEM_Base::delete()
1874
+	 *
1875
+	 * @param mixed $id
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int the number of rows deleted
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function delete_by_ID($id, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete(
1883
+			array(
1884
+				array($this->get_primary_key_field()->get_name() => $id),
1885
+				'limit' => 1,
1886
+			),
1887
+			$allow_blocking
1888
+		);
1889
+	}
1890
+
1891
+
1892
+
1893
+	/**
1894
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1895
+	 * meaning if the model has a field that indicates its been "trashed" or
1896
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1897
+	 *
1898
+	 * @see EEM_Base::delete_permanently
1899
+	 * @param array   $query_params
1900
+	 * @param boolean $allow_blocking
1901
+	 * @return int how many rows got deleted
1902
+	 * @throws EE_Error
1903
+	 */
1904
+	public function delete($query_params, $allow_blocking = true)
1905
+	{
1906
+		return $this->delete_permanently($query_params, $allow_blocking);
1907
+	}
1908
+
1909
+
1910
+
1911
+	/**
1912
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1913
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1914
+	 * as archived, not actually deleted
1915
+	 *
1916
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1917
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1918
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1919
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1920
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1921
+	 *                                DB
1922
+	 * @return int how many rows got deleted
1923
+	 * @throws EE_Error
1924
+	 */
1925
+	public function delete_permanently($query_params, $allow_blocking = true)
1926
+	{
1927
+		/**
1928
+		 * Action called just before performing a real deletion query. You can use the
1929
+		 * model and its $query_params to find exactly which items will be deleted
1930
+		 *
1931
+		 * @param EEM_Base $model
1932
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1933
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1934
+		 *                                 to block (prevent) this deletion
1935
+		 */
1936
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1937
+		// some MySQL databases may be running safe mode, which may restrict
1938
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1939
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1940
+		// to delete them
1941
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1942
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1943
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1944
+			$columns_and_ids_for_deleting
1945
+		);
1946
+		/**
1947
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1948
+		 *
1949
+		 * @param EEM_Base $this  The model instance being acted on.
1950
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1951
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1952
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1953
+		 *                                                  derived from the incoming query parameters.
1954
+		 *                                                  @see details on the structure of this array in the phpdocs
1955
+		 *                                                  for the `_get_ids_for_delete_method`
1956
+		 *
1957
+		 */
1958
+		do_action(
1959
+			'AHEE__EEM_Base__delete__before_query',
1960
+			$this,
1961
+			$query_params,
1962
+			$allow_blocking,
1963
+			$columns_and_ids_for_deleting
1964
+		);
1965
+		if ($deletion_where_query_part) {
1966
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1967
+			$table_aliases = array_keys($this->_tables);
1968
+			$SQL = "DELETE "
1969
+				   . implode(", ", $table_aliases)
1970
+				   . " FROM "
1971
+				   . $model_query_info->get_full_join_sql()
1972
+				   . " WHERE "
1973
+				   . $deletion_where_query_part;
1974
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1975
+		} else {
1976
+			$rows_deleted = 0;
1977
+		}
1978
+
1979
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1980
+		// there was no error with the delete query.
1981
+		if ($this->has_primary_key_field()
1982
+			&& $rows_deleted !== false
1983
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1984
+		) {
1985
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1986
+			foreach ($ids_for_removal as $id) {
1987
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1989
+				}
1990
+			}
1991
+
1992
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1993
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1994
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1995
+			// (although it is possible).
1996
+			// Note this can be skipped by using the provided filter and returning false.
1997
+			if (apply_filters(
1998
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1999
+				! $this instanceof EEM_Extra_Meta,
2000
+				$this
2001
+			)) {
2002
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2003
+					0 => array(
2004
+						'EXM_type' => $this->get_this_model_name(),
2005
+						'OBJ_ID'   => array(
2006
+							'IN',
2007
+							$ids_for_removal
2008
+						)
2009
+					)
2010
+				));
2011
+			}
2012
+		}
2013
+
2014
+		/**
2015
+		 * Action called just after performing a real deletion query. Although at this point the
2016
+		 * items should have been deleted
2017
+		 *
2018
+		 * @param EEM_Base $model
2019
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2020
+		 * @param int      $rows_deleted
2021
+		 */
2022
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
+		return $rows_deleted;// how many supposedly got deleted
2024
+	}
2025
+
2026
+
2027
+
2028
+	/**
2029
+	 * Checks all the relations that throw error messages when there are blocking related objects
2030
+	 * for related model objects. If there are any related model objects on those relations,
2031
+	 * adds an EE_Error, and return true
2032
+	 *
2033
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2034
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2035
+	 *                                                 should be ignored when determining whether there are related
2036
+	 *                                                 model objects which block this model object's deletion. Useful
2037
+	 *                                                 if you know A is related to B and are considering deleting A,
2038
+	 *                                                 but want to see if A has any other objects blocking its deletion
2039
+	 *                                                 before removing the relation between A and B
2040
+	 * @return boolean
2041
+	 * @throws EE_Error
2042
+	 */
2043
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2044
+	{
2045
+		// first, if $ignore_this_model_obj was supplied, get its model
2046
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2047
+			$ignored_model = $ignore_this_model_obj->get_model();
2048
+		} else {
2049
+			$ignored_model = null;
2050
+		}
2051
+		// now check all the relations of $this_model_obj_or_id and see if there
2052
+		// are any related model objects blocking it?
2053
+		$is_blocked = false;
2054
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2055
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2056
+				// if $ignore_this_model_obj was supplied, then for the query
2057
+				// on that model needs to be told to ignore $ignore_this_model_obj
2058
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2059
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2060
+						array(
2061
+							$ignored_model->get_primary_key_field()->get_name() => array(
2062
+								'!=',
2063
+								$ignore_this_model_obj->ID(),
2064
+							),
2065
+						),
2066
+					));
2067
+				} else {
2068
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2069
+				}
2070
+				if ($related_model_objects) {
2071
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2072
+					$is_blocked = true;
2073
+				}
2074
+			}
2075
+		}
2076
+		return $is_blocked;
2077
+	}
2078
+
2079
+
2080
+	/**
2081
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2082
+	 * @param array $row_results_for_deleting
2083
+	 * @param bool  $allow_blocking
2084
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2085
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2086
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2087
+	 *                 deleted. Example:
2088
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2089
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2090
+	 *                 where each element is a group of columns and values that get deleted. Example:
2091
+	 *                      array(
2092
+	 *                          0 => array(
2093
+	 *                              'Term_Relationship.object_id' => 1
2094
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2095
+	 *                          ),
2096
+	 *                          1 => array(
2097
+	 *                              'Term_Relationship.object_id' => 1
2098
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2099
+	 *                          )
2100
+	 *                      )
2101
+	 * @throws EE_Error
2102
+	 */
2103
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2104
+	{
2105
+		$ids_to_delete_indexed_by_column = array();
2106
+		if ($this->has_primary_key_field()) {
2107
+			$primary_table = $this->_get_main_table();
2108
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2109
+			$other_tables = $this->_get_other_tables();
2110
+			$ids_to_delete_indexed_by_column = $query = array();
2111
+			foreach ($row_results_for_deleting as $item_to_delete) {
2112
+				// before we mark this item for deletion,
2113
+				// make sure there's no related entities blocking its deletion (if we're checking)
2114
+				if ($allow_blocking
2115
+					&& $this->delete_is_blocked_by_related_models(
2116
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2117
+					)
2118
+				) {
2119
+					continue;
2120
+				}
2121
+				// primary table deletes
2122
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2125
+				}
2126
+			}
2127
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2128
+			$fields = $this->get_combined_primary_key_fields();
2129
+			foreach ($row_results_for_deleting as $item_to_delete) {
2130
+				$ids_to_delete_indexed_by_column_for_row = array();
2131
+				foreach ($fields as $cpk_field) {
2132
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2133
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2135
+					}
2136
+				}
2137
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2138
+			}
2139
+		} else {
2140
+			// so there's no primary key and no combined key...
2141
+			// sorry, can't help you
2142
+			throw new EE_Error(
2143
+				sprintf(
2144
+					__(
2145
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2146
+						"event_espresso"
2147
+					),
2148
+					get_class($this)
2149
+				)
2150
+			);
2151
+		}
2152
+		return $ids_to_delete_indexed_by_column;
2153
+	}
2154
+
2155
+
2156
+	/**
2157
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2158
+	 * the corresponding query_part for the query performing the delete.
2159
+	 *
2160
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2161
+	 * @return string
2162
+	 * @throws EE_Error
2163
+	 */
2164
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2165
+	{
2166
+		$query_part = '';
2167
+		if (empty($ids_to_delete_indexed_by_column)) {
2168
+			return $query_part;
2169
+		} elseif ($this->has_primary_key_field()) {
2170
+			$query = array();
2171
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
+				// make sure we have unique $ids
2173
+				$ids = array_unique($ids);
2174
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2175
+			}
2176
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2177
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2178
+			$ways_to_identify_a_row = array();
2179
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2180
+				$values_for_each_combined_primary_key_for_a_row = array();
2181
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2182
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2183
+				}
2184
+				$ways_to_identify_a_row[] = '('
2185
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2186
+											. ')';
2187
+			}
2188
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2189
+		}
2190
+		return $query_part;
2191
+	}
2192
+
2193
+
2194
+
2195
+	/**
2196
+	 * Gets the model field by the fully qualified name
2197
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2198
+	 * @return EE_Model_Field_Base
2199
+	 */
2200
+	public function get_field_by_column($qualified_column_name)
2201
+	{
2202
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2203
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2204
+				return $field_obj;
2205
+			}
2206
+		}
2207
+		throw new EE_Error(
2208
+			sprintf(
2209
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2210
+				$this->get_this_model_name(),
2211
+				$qualified_column_name
2212
+			)
2213
+		);
2214
+	}
2215
+
2216
+
2217
+
2218
+	/**
2219
+	 * Count all the rows that match criteria the model query params.
2220
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2221
+	 * column
2222
+	 *
2223
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2224
+	 * @param string $field_to_count field on model to count by (not column name)
2225
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2226
+	 *                               that by the setting $distinct to TRUE;
2227
+	 * @return int
2228
+	 * @throws EE_Error
2229
+	 */
2230
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2231
+	{
2232
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2233
+		if ($field_to_count) {
2234
+			$field_obj = $this->field_settings_for($field_to_count);
2235
+			$column_to_count = $field_obj->get_qualified_column();
2236
+		} elseif ($this->has_primary_key_field()) {
2237
+			$pk_field_obj = $this->get_primary_key_field();
2238
+			$column_to_count = $pk_field_obj->get_qualified_column();
2239
+		} else {
2240
+			// there's no primary key
2241
+			// if we're counting distinct items, and there's no primary key,
2242
+			// we need to list out the columns for distinction;
2243
+			// otherwise we can just use star
2244
+			if ($distinct) {
2245
+				$columns_to_use = array();
2246
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2247
+					$columns_to_use[] = $field_obj->get_qualified_column();
2248
+				}
2249
+				$column_to_count = implode(',', $columns_to_use);
2250
+			} else {
2251
+				$column_to_count = '*';
2252
+			}
2253
+		}
2254
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2255
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2256
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2257
+	}
2258
+
2259
+
2260
+
2261
+	/**
2262
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2263
+	 *
2264
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2265
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2266
+	 * @return float
2267
+	 * @throws EE_Error
2268
+	 */
2269
+	public function sum($query_params, $field_to_sum = null)
2270
+	{
2271
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
+		if ($field_to_sum) {
2273
+			$field_obj = $this->field_settings_for($field_to_sum);
2274
+		} else {
2275
+			$field_obj = $this->get_primary_key_field();
2276
+		}
2277
+		$column_to_count = $field_obj->get_qualified_column();
2278
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2279
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2280
+		$data_type = $field_obj->get_wpdb_data_type();
2281
+		if ($data_type === '%d' || $data_type === '%s') {
2282
+			return (float) $return_value;
2283
+		}
2284
+		// must be %f
2285
+		return (float) $return_value;
2286
+	}
2287
+
2288
+
2289
+
2290
+	/**
2291
+	 * Just calls the specified method on $wpdb with the given arguments
2292
+	 * Consolidates a little extra error handling code
2293
+	 *
2294
+	 * @param string $wpdb_method
2295
+	 * @param array  $arguments_to_provide
2296
+	 * @throws EE_Error
2297
+	 * @global wpdb  $wpdb
2298
+	 * @return mixed
2299
+	 */
2300
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2301
+	{
2302
+		// if we're in maintenance mode level 2, DON'T run any queries
2303
+		// because level 2 indicates the database needs updating and
2304
+		// is probably out of sync with the code
2305
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2306
+			throw new EE_Error(sprintf(__(
2307
+				"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.",
2308
+				"event_espresso"
2309
+			)));
2310
+		}
2311
+		/** @type WPDB $wpdb */
2312
+		global $wpdb;
2313
+		if (! method_exists($wpdb, $wpdb_method)) {
2314
+			throw new EE_Error(sprintf(__(
2315
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2316
+				'event_espresso'
2317
+			), $wpdb_method));
2318
+		}
2319
+		if (WP_DEBUG) {
2320
+			$old_show_errors_value = $wpdb->show_errors;
2321
+			$wpdb->show_errors(false);
2322
+		}
2323
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2324
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2325
+		if (WP_DEBUG) {
2326
+			$wpdb->show_errors($old_show_errors_value);
2327
+			if (! empty($wpdb->last_error)) {
2328
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2329
+			}
2330
+			if ($result === false) {
2331
+				throw new EE_Error(sprintf(__(
2332
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2333
+					'event_espresso'
2334
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2335
+			}
2336
+		} elseif ($result === false) {
2337
+			EE_Error::add_error(
2338
+				sprintf(
2339
+					__(
2340
+						'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"',
2341
+						'event_espresso'
2342
+					),
2343
+					$wpdb_method,
2344
+					var_export($arguments_to_provide, true),
2345
+					$wpdb->last_error
2346
+				),
2347
+				__FILE__,
2348
+				__FUNCTION__,
2349
+				__LINE__
2350
+			);
2351
+		}
2352
+		return $result;
2353
+	}
2354
+
2355
+
2356
+
2357
+	/**
2358
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2359
+	 * and if there's an error tries to verify the DB is correct. Uses
2360
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2361
+	 * we should try to fix the EE core db, the addons, or just give up
2362
+	 *
2363
+	 * @param string $wpdb_method
2364
+	 * @param array  $arguments_to_provide
2365
+	 * @return mixed
2366
+	 */
2367
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2368
+	{
2369
+		/** @type WPDB $wpdb */
2370
+		global $wpdb;
2371
+		$wpdb->last_error = null;
2372
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2373
+		// was there an error running the query? but we don't care on new activations
2374
+		// (we're going to setup the DB anyway on new activations)
2375
+		if (($result === false || ! empty($wpdb->last_error))
2376
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2377
+		) {
2378
+			switch (EEM_Base::$_db_verification_level) {
2379
+				case EEM_Base::db_verified_none:
2380
+					// let's double-check core's DB
2381
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2382
+					break;
2383
+				case EEM_Base::db_verified_core:
2384
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2385
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2386
+					break;
2387
+				case EEM_Base::db_verified_addons:
2388
+					// ummmm... you in trouble
2389
+					return $result;
2390
+					break;
2391
+			}
2392
+			if (! empty($error_message)) {
2393
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2394
+				trigger_error($error_message);
2395
+			}
2396
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2397
+		}
2398
+		return $result;
2399
+	}
2400
+
2401
+
2402
+
2403
+	/**
2404
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2405
+	 * EEM_Base::$_db_verification_level
2406
+	 *
2407
+	 * @param string $wpdb_method
2408
+	 * @param array  $arguments_to_provide
2409
+	 * @return string
2410
+	 */
2411
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2412
+	{
2413
+		/** @type WPDB $wpdb */
2414
+		global $wpdb;
2415
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2416
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2417
+		$error_message = sprintf(
2418
+			__(
2419
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2420
+				'event_espresso'
2421
+			),
2422
+			$wpdb->last_error,
2423
+			$wpdb_method,
2424
+			wp_json_encode($arguments_to_provide)
2425
+		);
2426
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2427
+		return $error_message;
2428
+	}
2429
+
2430
+
2431
+
2432
+	/**
2433
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2434
+	 * EEM_Base::$_db_verification_level
2435
+	 *
2436
+	 * @param $wpdb_method
2437
+	 * @param $arguments_to_provide
2438
+	 * @return string
2439
+	 */
2440
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2441
+	{
2442
+		/** @type WPDB $wpdb */
2443
+		global $wpdb;
2444
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2445
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2446
+		$error_message = sprintf(
2447
+			__(
2448
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2449
+				'event_espresso'
2450
+			),
2451
+			$wpdb->last_error,
2452
+			$wpdb_method,
2453
+			wp_json_encode($arguments_to_provide)
2454
+		);
2455
+		EE_System::instance()->initialize_addons();
2456
+		return $error_message;
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2463
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2464
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2465
+	 * ..."
2466
+	 *
2467
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2468
+	 * @return string
2469
+	 */
2470
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2471
+	{
2472
+		return " FROM " . $model_query_info->get_full_join_sql() .
2473
+			   $model_query_info->get_where_sql() .
2474
+			   $model_query_info->get_group_by_sql() .
2475
+			   $model_query_info->get_having_sql() .
2476
+			   $model_query_info->get_order_by_sql() .
2477
+			   $model_query_info->get_limit_sql();
2478
+	}
2479
+
2480
+
2481
+
2482
+	/**
2483
+	 * Set to easily debug the next X queries ran from this model.
2484
+	 *
2485
+	 * @param int $count
2486
+	 */
2487
+	public function show_next_x_db_queries($count = 1)
2488
+	{
2489
+		$this->_show_next_x_db_queries = $count;
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * @param $sql_query
2496
+	 */
2497
+	public function show_db_query_if_previously_requested($sql_query)
2498
+	{
2499
+		if ($this->_show_next_x_db_queries > 0) {
2500
+			echo $sql_query;
2501
+			$this->_show_next_x_db_queries--;
2502
+		}
2503
+	}
2504
+
2505
+
2506
+
2507
+	/**
2508
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2509
+	 * There are the 3 cases:
2510
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2511
+	 * $otherModelObject has no ID, it is first saved.
2512
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2513
+	 * has no ID, it is first saved.
2514
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2515
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2516
+	 * join table
2517
+	 *
2518
+	 * @param        EE_Base_Class                     /int $thisModelObject
2519
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2520
+	 * @param string $relationName                     , key in EEM_Base::_relations
2521
+	 *                                                 an attendee to a group, you also want to specify which role they
2522
+	 *                                                 will have in that group. So you would use this parameter to
2523
+	 *                                                 specify array('role-column-name'=>'role-id')
2524
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2525
+	 *                                                 to for relation to methods that allow you to further specify
2526
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2527
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2528
+	 *                                                 because these will be inserted in any new rows created as well.
2529
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2530
+	 * @throws EE_Error
2531
+	 */
2532
+	public function add_relationship_to(
2533
+		$id_or_obj,
2534
+		$other_model_id_or_obj,
2535
+		$relationName,
2536
+		$extra_join_model_fields_n_values = array()
2537
+	) {
2538
+		$relation_obj = $this->related_settings_for($relationName);
2539
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2540
+	}
2541
+
2542
+
2543
+
2544
+	/**
2545
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2546
+	 * There are the 3 cases:
2547
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2548
+	 * error
2549
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2550
+	 * an error
2551
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2552
+	 *
2553
+	 * @param        EE_Base_Class /int $id_or_obj
2554
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2555
+	 * @param string $relationName key in EEM_Base::_relations
2556
+	 * @return boolean of success
2557
+	 * @throws EE_Error
2558
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2559
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2560
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2561
+	 *                             because these will be inserted in any new rows created as well.
2562
+	 */
2563
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2564
+	{
2565
+		$relation_obj = $this->related_settings_for($relationName);
2566
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2567
+	}
2568
+
2569
+
2570
+
2571
+	/**
2572
+	 * @param mixed           $id_or_obj
2573
+	 * @param string          $relationName
2574
+	 * @param array           $where_query_params
2575
+	 * @param EE_Base_Class[] objects to which relations were removed
2576
+	 * @return \EE_Base_Class[]
2577
+	 * @throws EE_Error
2578
+	 */
2579
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2580
+	{
2581
+		$relation_obj = $this->related_settings_for($relationName);
2582
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2583
+	}
2584
+
2585
+
2586
+
2587
+	/**
2588
+	 * Gets all the related items of the specified $model_name, using $query_params.
2589
+	 * Note: by default, we remove the "default query params"
2590
+	 * because we want to get even deleted items etc.
2591
+	 *
2592
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2593
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2594
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2595
+	 * @return EE_Base_Class[]
2596
+	 * @throws EE_Error
2597
+	 */
2598
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2599
+	{
2600
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2601
+		$relation_settings = $this->related_settings_for($model_name);
2602
+		return $relation_settings->get_all_related($model_obj, $query_params);
2603
+	}
2604
+
2605
+
2606
+
2607
+	/**
2608
+	 * Deletes all the model objects across the relation indicated by $model_name
2609
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2610
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2611
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2612
+	 *
2613
+	 * @param EE_Base_Class|int|string $id_or_obj
2614
+	 * @param string                   $model_name
2615
+	 * @param array                    $query_params
2616
+	 * @return int how many deleted
2617
+	 * @throws EE_Error
2618
+	 */
2619
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2620
+	{
2621
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2622
+		$relation_settings = $this->related_settings_for($model_name);
2623
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2624
+	}
2625
+
2626
+
2627
+
2628
+	/**
2629
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2630
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2631
+	 * the model objects can't be hard deleted because of blocking related model objects,
2632
+	 * just does a soft-delete on them instead.
2633
+	 *
2634
+	 * @param EE_Base_Class|int|string $id_or_obj
2635
+	 * @param string                   $model_name
2636
+	 * @param array                    $query_params
2637
+	 * @return int how many deleted
2638
+	 * @throws EE_Error
2639
+	 */
2640
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2641
+	{
2642
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2643
+		$relation_settings = $this->related_settings_for($model_name);
2644
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2645
+	}
2646
+
2647
+
2648
+
2649
+	/**
2650
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2651
+	 * unless otherwise specified in the $query_params
2652
+	 *
2653
+	 * @param        int             /EE_Base_Class $id_or_obj
2654
+	 * @param string $model_name     like 'Event', or 'Registration'
2655
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2656
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2657
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2658
+	 *                               that by the setting $distinct to TRUE;
2659
+	 * @return int
2660
+	 * @throws EE_Error
2661
+	 */
2662
+	public function count_related(
2663
+		$id_or_obj,
2664
+		$model_name,
2665
+		$query_params = array(),
2666
+		$field_to_count = null,
2667
+		$distinct = false
2668
+	) {
2669
+		$related_model = $this->get_related_model_obj($model_name);
2670
+		// we're just going to use the query params on the related model's normal get_all query,
2671
+		// except add a condition to say to match the current mod
2672
+		if (! isset($query_params['default_where_conditions'])) {
2673
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2674
+		}
2675
+		$this_model_name = $this->get_this_model_name();
2676
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2677
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2678
+		return $related_model->count($query_params, $field_to_count, $distinct);
2679
+	}
2680
+
2681
+
2682
+
2683
+	/**
2684
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2685
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2686
+	 *
2687
+	 * @param        int           /EE_Base_Class $id_or_obj
2688
+	 * @param string $model_name   like 'Event', or 'Registration'
2689
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2690
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2691
+	 * @return float
2692
+	 * @throws EE_Error
2693
+	 */
2694
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2695
+	{
2696
+		$related_model = $this->get_related_model_obj($model_name);
2697
+		if (! is_array($query_params)) {
2698
+			EE_Error::doing_it_wrong(
2699
+				'EEM_Base::sum_related',
2700
+				sprintf(
2701
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2702
+					gettype($query_params)
2703
+				),
2704
+				'4.6.0'
2705
+			);
2706
+			$query_params = array();
2707
+		}
2708
+		// we're just going to use the query params on the related model's normal get_all query,
2709
+		// except add a condition to say to match the current mod
2710
+		if (! isset($query_params['default_where_conditions'])) {
2711
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
+		}
2713
+		$this_model_name = $this->get_this_model_name();
2714
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2716
+		return $related_model->sum($query_params, $field_to_sum);
2717
+	}
2718
+
2719
+
2720
+
2721
+	/**
2722
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
+	 * $modelObject
2724
+	 *
2725
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2728
+	 * @return EE_Base_Class
2729
+	 * @throws EE_Error
2730
+	 */
2731
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
+	{
2733
+		$query_params['limit'] = 1;
2734
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
+		if ($results) {
2736
+			return array_shift($results);
2737
+		}
2738
+		return null;
2739
+	}
2740
+
2741
+
2742
+
2743
+	/**
2744
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
+	 *
2746
+	 * @return string
2747
+	 */
2748
+	public function get_this_model_name()
2749
+	{
2750
+		return str_replace("EEM_", "", get_class($this));
2751
+	}
2752
+
2753
+
2754
+
2755
+	/**
2756
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
+	 *
2758
+	 * @return EE_Any_Foreign_Model_Name_Field
2759
+	 * @throws EE_Error
2760
+	 */
2761
+	public function get_field_containing_related_model_name()
2762
+	{
2763
+		foreach ($this->field_settings(true) as $field) {
2764
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
+				$field_with_model_name = $field;
2766
+			}
2767
+		}
2768
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
+			throw new EE_Error(sprintf(
2770
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2771
+				$this->get_this_model_name()
2772
+			));
2773
+		}
2774
+		return $field_with_model_name;
2775
+	}
2776
+
2777
+
2778
+
2779
+	/**
2780
+	 * Inserts a new entry into the database, for each table.
2781
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2782
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2783
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2784
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2785
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2786
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2787
+	 *
2788
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2789
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2790
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2791
+	 *                              of EEM_Base)
2792
+	 * @return int|string new primary key on main table that got inserted
2793
+	 * @throws EE_Error
2794
+	 */
2795
+	public function insert($field_n_values)
2796
+	{
2797
+		/**
2798
+		 * Filters the fields and their values before inserting an item using the models
2799
+		 *
2800
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2801
+		 * @param EEM_Base $model           the model used
2802
+		 */
2803
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2804
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2805
+			$main_table = $this->_get_main_table();
2806
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2807
+			if ($new_id !== false) {
2808
+				foreach ($this->_get_other_tables() as $other_table) {
2809
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2810
+				}
2811
+			}
2812
+			/**
2813
+			 * Done just after attempting to insert a new model object
2814
+			 *
2815
+			 * @param EEM_Base   $model           used
2816
+			 * @param array      $fields_n_values fields and their values
2817
+			 * @param int|string the              ID of the newly-inserted model object
2818
+			 */
2819
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2820
+			return $new_id;
2821
+		}
2822
+		return false;
2823
+	}
2824
+
2825
+
2826
+
2827
+	/**
2828
+	 * Checks that the result would satisfy the unique indexes on this model
2829
+	 *
2830
+	 * @param array  $field_n_values
2831
+	 * @param string $action
2832
+	 * @return boolean
2833
+	 * @throws EE_Error
2834
+	 */
2835
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2836
+	{
2837
+		foreach ($this->unique_indexes() as $index_name => $index) {
2838
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2839
+			if ($this->exists(array($uniqueness_where_params))) {
2840
+				EE_Error::add_error(
2841
+					sprintf(
2842
+						__(
2843
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2844
+							"event_espresso"
2845
+						),
2846
+						$action,
2847
+						$this->_get_class_name(),
2848
+						$index_name,
2849
+						implode(",", $index->field_names()),
2850
+						http_build_query($uniqueness_where_params)
2851
+					),
2852
+					__FILE__,
2853
+					__FUNCTION__,
2854
+					__LINE__
2855
+				);
2856
+				return false;
2857
+			}
2858
+		}
2859
+		return true;
2860
+	}
2861
+
2862
+
2863
+
2864
+	/**
2865
+	 * Checks the database for an item that conflicts (ie, if this item were
2866
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2867
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2868
+	 * can be either an EE_Base_Class or an array of fields n values
2869
+	 *
2870
+	 * @param EE_Base_Class|array $obj_or_fields_array
2871
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2872
+	 *                                                 when looking for conflicts
2873
+	 *                                                 (ie, if false, we ignore the model object's primary key
2874
+	 *                                                 when finding "conflicts". If true, it's also considered).
2875
+	 *                                                 Only works for INT primary key,
2876
+	 *                                                 STRING primary keys cannot be ignored
2877
+	 * @throws EE_Error
2878
+	 * @return EE_Base_Class|array
2879
+	 */
2880
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2881
+	{
2882
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2883
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2884
+		} elseif (is_array($obj_or_fields_array)) {
2885
+			$fields_n_values = $obj_or_fields_array;
2886
+		} else {
2887
+			throw new EE_Error(
2888
+				sprintf(
2889
+					__(
2890
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2891
+						"event_espresso"
2892
+					),
2893
+					get_class($this),
2894
+					$obj_or_fields_array
2895
+				)
2896
+			);
2897
+		}
2898
+		$query_params = array();
2899
+		if ($this->has_primary_key_field()
2900
+			&& ($include_primary_key
2901
+				|| $this->get_primary_key_field()
2902
+				   instanceof
2903
+				   EE_Primary_Key_String_Field)
2904
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2905
+		) {
2906
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2907
+		}
2908
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2909
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2910
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2911
+		}
2912
+		// if there is nothing to base this search on, then we shouldn't find anything
2913
+		if (empty($query_params)) {
2914
+			return array();
2915
+		}
2916
+		return $this->get_one($query_params);
2917
+	}
2918
+
2919
+
2920
+
2921
+	/**
2922
+	 * Like count, but is optimized and returns a boolean instead of an int
2923
+	 *
2924
+	 * @param array $query_params
2925
+	 * @return boolean
2926
+	 * @throws EE_Error
2927
+	 */
2928
+	public function exists($query_params)
2929
+	{
2930
+		$query_params['limit'] = 1;
2931
+		return $this->count($query_params) > 0;
2932
+	}
2933
+
2934
+
2935
+
2936
+	/**
2937
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2938
+	 *
2939
+	 * @param int|string $id
2940
+	 * @return boolean
2941
+	 * @throws EE_Error
2942
+	 */
2943
+	public function exists_by_ID($id)
2944
+	{
2945
+		return $this->exists(
2946
+			array(
2947
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2948
+				array(
2949
+					$this->primary_key_name() => $id,
2950
+				),
2951
+			)
2952
+		);
2953
+	}
2954
+
2955
+
2956
+
2957
+	/**
2958
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2959
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2960
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2961
+	 * on the main table)
2962
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2963
+	 * cases where we want to call it directly rather than via insert().
2964
+	 *
2965
+	 * @access   protected
2966
+	 * @param EE_Table_Base $table
2967
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2968
+	 *                                       float
2969
+	 * @param int           $new_id          for now we assume only int keys
2970
+	 * @throws EE_Error
2971
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2972
+	 * @return int ID of new row inserted, or FALSE on failure
2973
+	 */
2974
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2975
+	{
2976
+		global $wpdb;
2977
+		$insertion_col_n_values = array();
2978
+		$format_for_insertion = array();
2979
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2980
+		foreach ($fields_on_table as $field_name => $field_obj) {
2981
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2982
+			if ($field_obj->is_auto_increment()) {
2983
+				continue;
2984
+			}
2985
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2986
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2987
+			if ($prepared_value !== null) {
2988
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2989
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2990
+			}
2991
+		}
2992
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2993
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2994
+			// so add the fk to the main table as a column
2995
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2996
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2997
+		}
2998
+		// insert the new entry
2999
+		$result = $this->_do_wpdb_query(
3000
+			'insert',
3001
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3002
+		);
3003
+		if ($result === false) {
3004
+			return false;
3005
+		}
3006
+		// ok, now what do we return for the ID of the newly-inserted thing?
3007
+		if ($this->has_primary_key_field()) {
3008
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3009
+				return $wpdb->insert_id;
3010
+			}
3011
+			// it's not an auto-increment primary key, so
3012
+			// it must have been supplied
3013
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3014
+		}
3015
+		// we can't return a  primary key because there is none. instead return
3016
+		// a unique string indicating this model
3017
+		return $this->get_index_primary_key_string($fields_n_values);
3018
+	}
3019
+
3020
+
3021
+
3022
+	/**
3023
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3024
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3025
+	 * and there is no default, we pass it along. WPDB will take care of it)
3026
+	 *
3027
+	 * @param EE_Model_Field_Base $field_obj
3028
+	 * @param array               $fields_n_values
3029
+	 * @return mixed string|int|float depending on what the table column will be expecting
3030
+	 * @throws EE_Error
3031
+	 */
3032
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3033
+	{
3034
+		// if this field doesn't allow nullable, don't allow it
3035
+		if (! $field_obj->is_nullable()
3036
+			&& (
3037
+				! isset($fields_n_values[ $field_obj->get_name() ])
3038
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3039
+			)
3040
+		) {
3041
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3042
+		}
3043
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3044
+			? $fields_n_values[ $field_obj->get_name() ]
3045
+			: null;
3046
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3047
+	}
3048
+
3049
+
3050
+
3051
+	/**
3052
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3053
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3054
+	 * the field's prepare_for_set() method.
3055
+	 *
3056
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3057
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3058
+	 *                                   top of file)
3059
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3060
+	 *                                   $value is a custom selection
3061
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3062
+	 */
3063
+	private function _prepare_value_for_use_in_db($value, $field)
3064
+	{
3065
+		if ($field && $field instanceof EE_Model_Field_Base) {
3066
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3067
+			switch ($this->_values_already_prepared_by_model_object) {
3068
+				/** @noinspection PhpMissingBreakStatementInspection */
3069
+				case self::not_prepared_by_model_object:
3070
+					$value = $field->prepare_for_set($value);
3071
+				// purposefully left out "return"
3072
+				case self::prepared_by_model_object:
3073
+					/** @noinspection SuspiciousAssignmentsInspection */
3074
+					$value = $field->prepare_for_use_in_db($value);
3075
+				case self::prepared_for_use_in_db:
3076
+					// leave the value alone
3077
+			}
3078
+			return $value;
3079
+			// phpcs:enable
3080
+		}
3081
+		return $value;
3082
+	}
3083
+
3084
+
3085
+
3086
+	/**
3087
+	 * Returns the main table on this model
3088
+	 *
3089
+	 * @return EE_Primary_Table
3090
+	 * @throws EE_Error
3091
+	 */
3092
+	protected function _get_main_table()
3093
+	{
3094
+		foreach ($this->_tables as $table) {
3095
+			if ($table instanceof EE_Primary_Table) {
3096
+				return $table;
3097
+			}
3098
+		}
3099
+		throw new EE_Error(sprintf(__(
3100
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3101
+			'event_espresso'
3102
+		), get_class($this)));
3103
+	}
3104
+
3105
+
3106
+
3107
+	/**
3108
+	 * table
3109
+	 * returns EE_Primary_Table table name
3110
+	 *
3111
+	 * @return string
3112
+	 * @throws EE_Error
3113
+	 */
3114
+	public function table()
3115
+	{
3116
+		return $this->_get_main_table()->get_table_name();
3117
+	}
3118
+
3119
+
3120
+
3121
+	/**
3122
+	 * table
3123
+	 * returns first EE_Secondary_Table table name
3124
+	 *
3125
+	 * @return string
3126
+	 */
3127
+	public function second_table()
3128
+	{
3129
+		// grab second table from tables array
3130
+		$second_table = end($this->_tables);
3131
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3132
+	}
3133
+
3134
+
3135
+
3136
+	/**
3137
+	 * get_table_obj_by_alias
3138
+	 * returns table name given it's alias
3139
+	 *
3140
+	 * @param string $table_alias
3141
+	 * @return EE_Primary_Table | EE_Secondary_Table
3142
+	 */
3143
+	public function get_table_obj_by_alias($table_alias = '')
3144
+	{
3145
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3146
+	}
3147
+
3148
+
3149
+
3150
+	/**
3151
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3152
+	 *
3153
+	 * @return EE_Secondary_Table[]
3154
+	 */
3155
+	protected function _get_other_tables()
3156
+	{
3157
+		$other_tables = array();
3158
+		foreach ($this->_tables as $table_alias => $table) {
3159
+			if ($table instanceof EE_Secondary_Table) {
3160
+				$other_tables[ $table_alias ] = $table;
3161
+			}
3162
+		}
3163
+		return $other_tables;
3164
+	}
3165
+
3166
+
3167
+
3168
+	/**
3169
+	 * Finds all the fields that correspond to the given table
3170
+	 *
3171
+	 * @param string $table_alias , array key in EEM_Base::_tables
3172
+	 * @return EE_Model_Field_Base[]
3173
+	 */
3174
+	public function _get_fields_for_table($table_alias)
3175
+	{
3176
+		return $this->_fields[ $table_alias ];
3177
+	}
3178
+
3179
+
3180
+
3181
+	/**
3182
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3183
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3184
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3185
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3186
+	 * related Registration, Transaction, and Payment models.
3187
+	 *
3188
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3189
+	 * @return EE_Model_Query_Info_Carrier
3190
+	 * @throws EE_Error
3191
+	 */
3192
+	public function _extract_related_models_from_query($query_params)
3193
+	{
3194
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3195
+		if (array_key_exists(0, $query_params)) {
3196
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3197
+		}
3198
+		if (array_key_exists('group_by', $query_params)) {
3199
+			if (is_array($query_params['group_by'])) {
3200
+				$this->_extract_related_models_from_sub_params_array_values(
3201
+					$query_params['group_by'],
3202
+					$query_info_carrier,
3203
+					'group_by'
3204
+				);
3205
+			} elseif (! empty($query_params['group_by'])) {
3206
+				$this->_extract_related_model_info_from_query_param(
3207
+					$query_params['group_by'],
3208
+					$query_info_carrier,
3209
+					'group_by'
3210
+				);
3211
+			}
3212
+		}
3213
+		if (array_key_exists('having', $query_params)) {
3214
+			$this->_extract_related_models_from_sub_params_array_keys(
3215
+				$query_params[0],
3216
+				$query_info_carrier,
3217
+				'having'
3218
+			);
3219
+		}
3220
+		if (array_key_exists('order_by', $query_params)) {
3221
+			if (is_array($query_params['order_by'])) {
3222
+				$this->_extract_related_models_from_sub_params_array_keys(
3223
+					$query_params['order_by'],
3224
+					$query_info_carrier,
3225
+					'order_by'
3226
+				);
3227
+			} elseif (! empty($query_params['order_by'])) {
3228
+				$this->_extract_related_model_info_from_query_param(
3229
+					$query_params['order_by'],
3230
+					$query_info_carrier,
3231
+					'order_by'
3232
+				);
3233
+			}
3234
+		}
3235
+		if (array_key_exists('force_join', $query_params)) {
3236
+			$this->_extract_related_models_from_sub_params_array_values(
3237
+				$query_params['force_join'],
3238
+				$query_info_carrier,
3239
+				'force_join'
3240
+			);
3241
+		}
3242
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3243
+		return $query_info_carrier;
3244
+	}
3245
+
3246
+
3247
+
3248
+	/**
3249
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3250
+	 *
3251
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3252
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3253
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3254
+	 * @throws EE_Error
3255
+	 * @return \EE_Model_Query_Info_Carrier
3256
+	 */
3257
+	private function _extract_related_models_from_sub_params_array_keys(
3258
+		$sub_query_params,
3259
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3260
+		$query_param_type
3261
+	) {
3262
+		if (! empty($sub_query_params)) {
3263
+			$sub_query_params = (array) $sub_query_params;
3264
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3265
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3266
+				$this->_extract_related_model_info_from_query_param(
3267
+					$param,
3268
+					$model_query_info_carrier,
3269
+					$query_param_type
3270
+				);
3271
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3272
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3273
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3274
+				// of array('Registration.TXN_ID'=>23)
3275
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3276
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3277
+					if (! is_array($possibly_array_of_params)) {
3278
+						throw new EE_Error(sprintf(
3279
+							__(
3280
+								"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'))",
3281
+								"event_espresso"
3282
+							),
3283
+							$param,
3284
+							$possibly_array_of_params
3285
+						));
3286
+					}
3287
+					$this->_extract_related_models_from_sub_params_array_keys(
3288
+						$possibly_array_of_params,
3289
+						$model_query_info_carrier,
3290
+						$query_param_type
3291
+					);
3292
+				} elseif ($query_param_type === 0 // ie WHERE
3293
+						  && is_array($possibly_array_of_params)
3294
+						  && isset($possibly_array_of_params[2])
3295
+						  && $possibly_array_of_params[2] == true
3296
+				) {
3297
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3298
+					// indicating that $possible_array_of_params[1] is actually a field name,
3299
+					// from which we should extract query parameters!
3300
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3301
+						throw new EE_Error(sprintf(__(
3302
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303
+							"event_espresso"
3304
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3305
+					}
3306
+					$this->_extract_related_model_info_from_query_param(
3307
+						$possibly_array_of_params[1],
3308
+						$model_query_info_carrier,
3309
+						$query_param_type
3310
+					);
3311
+				}
3312
+			}
3313
+		}
3314
+		return $model_query_info_carrier;
3315
+	}
3316
+
3317
+
3318
+
3319
+	/**
3320
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3321
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3322
+	 *
3323
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3324
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3325
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3326
+	 * @throws EE_Error
3327
+	 * @return \EE_Model_Query_Info_Carrier
3328
+	 */
3329
+	private function _extract_related_models_from_sub_params_array_values(
3330
+		$sub_query_params,
3331
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3332
+		$query_param_type
3333
+	) {
3334
+		if (! empty($sub_query_params)) {
3335
+			if (! is_array($sub_query_params)) {
3336
+				throw new EE_Error(sprintf(
3337
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3338
+					$sub_query_params
3339
+				));
3340
+			}
3341
+			foreach ($sub_query_params as $param) {
3342
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3343
+				$this->_extract_related_model_info_from_query_param(
3344
+					$param,
3345
+					$model_query_info_carrier,
3346
+					$query_param_type
3347
+				);
3348
+			}
3349
+		}
3350
+		return $model_query_info_carrier;
3351
+	}
3352
+
3353
+
3354
+	/**
3355
+	 * Extract all the query parts from  model query params
3356
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3357
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3358
+	 * but use them in a different order. Eg, we need to know what models we are querying
3359
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3360
+	 * other models before we can finalize the where clause SQL.
3361
+	 *
3362
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3363
+	 * @throws EE_Error
3364
+	 * @return EE_Model_Query_Info_Carrier
3365
+	 * @throws ModelConfigurationException
3366
+	 */
3367
+	public function _create_model_query_info_carrier($query_params)
3368
+	{
3369
+		if (! is_array($query_params)) {
3370
+			EE_Error::doing_it_wrong(
3371
+				'EEM_Base::_create_model_query_info_carrier',
3372
+				sprintf(
3373
+					__(
3374
+						'$query_params should be an array, you passed a variable of type %s',
3375
+						'event_espresso'
3376
+					),
3377
+					gettype($query_params)
3378
+				),
3379
+				'4.6.0'
3380
+			);
3381
+			$query_params = array();
3382
+		}
3383
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3384
+		// first check if we should alter the query to account for caps or not
3385
+		// because the caps might require us to do extra joins
3386
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3387
+			$query_params[0] = array_replace_recursive(
3388
+				$query_params[0],
3389
+				$this->caps_where_conditions(
3390
+					$query_params['caps']
3391
+				)
3392
+			);
3393
+		}
3394
+
3395
+		// check if we should alter the query to remove data related to protected
3396
+		// custom post types
3397
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3398
+			$where_param_key_for_password = $this->modelChainAndPassword();
3399
+			// only include if related to a cpt where no password has been set
3400
+			$query_params[0]['OR*nopassword'] = array(
3401
+				$where_param_key_for_password => '',
3402
+				$where_param_key_for_password . '*' => array('IS_NULL')
3403
+			);
3404
+		}
3405
+		$query_object = $this->_extract_related_models_from_query($query_params);
3406
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3407
+		foreach ($query_params[0] as $key => $value) {
3408
+			if (is_int($key)) {
3409
+				throw new EE_Error(
3410
+					sprintf(
3411
+						__(
3412
+							"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.",
3413
+							"event_espresso"
3414
+						),
3415
+						$key,
3416
+						var_export($value, true),
3417
+						var_export($query_params, true),
3418
+						get_class($this)
3419
+					)
3420
+				);
3421
+			}
3422
+		}
3423
+		if (array_key_exists('default_where_conditions', $query_params)
3424
+			&& ! empty($query_params['default_where_conditions'])
3425
+		) {
3426
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3427
+		} else {
3428
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3429
+		}
3430
+		$query_params[0] = array_merge(
3431
+			$this->_get_default_where_conditions_for_models_in_query(
3432
+				$query_object,
3433
+				$use_default_where_conditions,
3434
+				$query_params[0]
3435
+			),
3436
+			$query_params[0]
3437
+		);
3438
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3439
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3440
+		// So we need to setup a subquery and use that for the main join.
3441
+		// Note for now this only works on the primary table for the model.
3442
+		// So for instance, you could set the limit array like this:
3443
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3444
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3445
+			$query_object->set_main_model_join_sql(
3446
+				$this->_construct_limit_join_select(
3447
+					$query_params['on_join_limit'][0],
3448
+					$query_params['on_join_limit'][1]
3449
+				)
3450
+			);
3451
+		}
3452
+		// set limit
3453
+		if (array_key_exists('limit', $query_params)) {
3454
+			if (is_array($query_params['limit'])) {
3455
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3456
+					$e = sprintf(
3457
+						__(
3458
+							"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)",
3459
+							"event_espresso"
3460
+						),
3461
+						http_build_query($query_params['limit'])
3462
+					);
3463
+					throw new EE_Error($e . "|" . $e);
3464
+				}
3465
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3466
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3467
+			} elseif (! empty($query_params['limit'])) {
3468
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3469
+			}
3470
+		}
3471
+		// set order by
3472
+		if (array_key_exists('order_by', $query_params)) {
3473
+			if (is_array($query_params['order_by'])) {
3474
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3475
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3476
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3477
+				if (array_key_exists('order', $query_params)) {
3478
+					throw new EE_Error(
3479
+						sprintf(
3480
+							__(
3481
+								"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 ",
3482
+								"event_espresso"
3483
+							),
3484
+							get_class($this),
3485
+							implode(", ", array_keys($query_params['order_by'])),
3486
+							implode(", ", $query_params['order_by']),
3487
+							$query_params['order']
3488
+						)
3489
+					);
3490
+				}
3491
+				$this->_extract_related_models_from_sub_params_array_keys(
3492
+					$query_params['order_by'],
3493
+					$query_object,
3494
+					'order_by'
3495
+				);
3496
+				// assume it's an array of fields to order by
3497
+				$order_array = array();
3498
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3499
+					$order = $this->_extract_order($order);
3500
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3501
+				}
3502
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3503
+			} elseif (! empty($query_params['order_by'])) {
3504
+				$this->_extract_related_model_info_from_query_param(
3505
+					$query_params['order_by'],
3506
+					$query_object,
3507
+					'order',
3508
+					$query_params['order_by']
3509
+				);
3510
+				$order = isset($query_params['order'])
3511
+					? $this->_extract_order($query_params['order'])
3512
+					: 'DESC';
3513
+				$query_object->set_order_by_sql(
3514
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3515
+				);
3516
+			}
3517
+		}
3518
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3519
+		if (! array_key_exists('order_by', $query_params)
3520
+			&& array_key_exists('order', $query_params)
3521
+			&& ! empty($query_params['order'])
3522
+		) {
3523
+			$pk_field = $this->get_primary_key_field();
3524
+			$order = $this->_extract_order($query_params['order']);
3525
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3526
+		}
3527
+		// set group by
3528
+		if (array_key_exists('group_by', $query_params)) {
3529
+			if (is_array($query_params['group_by'])) {
3530
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3531
+				$group_by_array = array();
3532
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3533
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3534
+				}
3535
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3536
+			} elseif (! empty($query_params['group_by'])) {
3537
+				$query_object->set_group_by_sql(
3538
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3539
+				);
3540
+			}
3541
+		}
3542
+		// set having
3543
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3544
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3545
+		}
3546
+		// now, just verify they didn't pass anything wack
3547
+		foreach ($query_params as $query_key => $query_value) {
3548
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3549
+				throw new EE_Error(
3550
+					sprintf(
3551
+						__(
3552
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3553
+							'event_espresso'
3554
+						),
3555
+						$query_key,
3556
+						get_class($this),
3557
+						//                      print_r( $this->_allowed_query_params, TRUE )
3558
+						implode(',', $this->_allowed_query_params)
3559
+					)
3560
+				);
3561
+			}
3562
+		}
3563
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3564
+		if (empty($main_model_join_sql)) {
3565
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3566
+		}
3567
+		return $query_object;
3568
+	}
3569
+
3570
+
3571
+
3572
+	/**
3573
+	 * Gets the where conditions that should be imposed on the query based on the
3574
+	 * context (eg reading frontend, backend, edit or delete).
3575
+	 *
3576
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3577
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3578
+	 * @throws EE_Error
3579
+	 */
3580
+	public function caps_where_conditions($context = self::caps_read)
3581
+	{
3582
+		EEM_Base::verify_is_valid_cap_context($context);
3583
+		$cap_where_conditions = array();
3584
+		$cap_restrictions = $this->caps_missing($context);
3585
+		/**
3586
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3587
+		 */
3588
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3589
+			$cap_where_conditions = array_replace_recursive(
3590
+				$cap_where_conditions,
3591
+				$restriction_if_no_cap->get_default_where_conditions()
3592
+			);
3593
+		}
3594
+		return apply_filters(
3595
+			'FHEE__EEM_Base__caps_where_conditions__return',
3596
+			$cap_where_conditions,
3597
+			$this,
3598
+			$context,
3599
+			$cap_restrictions
3600
+		);
3601
+	}
3602
+
3603
+
3604
+
3605
+	/**
3606
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3607
+	 * otherwise throws an exception
3608
+	 *
3609
+	 * @param string $should_be_order_string
3610
+	 * @return string either ASC, asc, DESC or desc
3611
+	 * @throws EE_Error
3612
+	 */
3613
+	private function _extract_order($should_be_order_string)
3614
+	{
3615
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3616
+			return $should_be_order_string;
3617
+		}
3618
+		throw new EE_Error(
3619
+			sprintf(
3620
+				__(
3621
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3622
+					"event_espresso"
3623
+				),
3624
+				get_class($this),
3625
+				$should_be_order_string
3626
+			)
3627
+		);
3628
+	}
3629
+
3630
+
3631
+
3632
+	/**
3633
+	 * Looks at all the models which are included in this query, and asks each
3634
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3635
+	 * so they can be merged
3636
+	 *
3637
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3638
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3639
+	 *                                                                  'none' means NO default where conditions will
3640
+	 *                                                                  be used AT ALL during this query.
3641
+	 *                                                                  'other_models_only' means default where
3642
+	 *                                                                  conditions from other models will be used, but
3643
+	 *                                                                  not for this primary model. 'all', the default,
3644
+	 *                                                                  means default where conditions will apply as
3645
+	 *                                                                  normal
3646
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3647
+	 * @throws EE_Error
3648
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3649
+	 */
3650
+	private function _get_default_where_conditions_for_models_in_query(
3651
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3652
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3653
+		$where_query_params = array()
3654
+	) {
3655
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3656
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3657
+			throw new EE_Error(sprintf(
3658
+				__(
3659
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3660
+					"event_espresso"
3661
+				),
3662
+				$use_default_where_conditions,
3663
+				implode(", ", $allowed_used_default_where_conditions_values)
3664
+			));
3665
+		}
3666
+		$universal_query_params = array();
3667
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3668
+			$universal_query_params = $this->_get_default_where_conditions();
3669
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3670
+			$universal_query_params = $this->_get_minimum_where_conditions();
3671
+		}
3672
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3673
+			$related_model = $this->get_related_model_obj($model_name);
3674
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3675
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3676
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3677
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3678
+			} else {
3679
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3680
+				continue;
3681
+			}
3682
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3683
+				$related_model_universal_where_params,
3684
+				$where_query_params,
3685
+				$related_model,
3686
+				$model_relation_path
3687
+			);
3688
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3689
+				$universal_query_params,
3690
+				$overrides
3691
+			);
3692
+		}
3693
+		return $universal_query_params;
3694
+	}
3695
+
3696
+
3697
+
3698
+	/**
3699
+	 * Determines whether or not we should use default where conditions for the model in question
3700
+	 * (this model, or other related models).
3701
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3702
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3703
+	 * We should use default where conditions on related models when they requested to use default where conditions
3704
+	 * on all models, or specifically just on other related models
3705
+	 * @param      $default_where_conditions_value
3706
+	 * @param bool $for_this_model false means this is for OTHER related models
3707
+	 * @return bool
3708
+	 */
3709
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3710
+	{
3711
+		return (
3712
+				   $for_this_model
3713
+				   && in_array(
3714
+					   $default_where_conditions_value,
3715
+					   array(
3716
+						   EEM_Base::default_where_conditions_all,
3717
+						   EEM_Base::default_where_conditions_this_only,
3718
+						   EEM_Base::default_where_conditions_minimum_others,
3719
+					   ),
3720
+					   true
3721
+				   )
3722
+			   )
3723
+			   || (
3724
+				   ! $for_this_model
3725
+				   && in_array(
3726
+					   $default_where_conditions_value,
3727
+					   array(
3728
+						   EEM_Base::default_where_conditions_all,
3729
+						   EEM_Base::default_where_conditions_others_only,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   );
3734
+	}
3735
+
3736
+	/**
3737
+	 * Determines whether or not we should use default minimum conditions for the model in question
3738
+	 * (this model, or other related models).
3739
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3740
+	 * where conditions.
3741
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3742
+	 * on this model or others
3743
+	 * @param      $default_where_conditions_value
3744
+	 * @param bool $for_this_model false means this is for OTHER related models
3745
+	 * @return bool
3746
+	 */
3747
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3748
+	{
3749
+		return (
3750
+				   $for_this_model
3751
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3752
+			   )
3753
+			   || (
3754
+				   ! $for_this_model
3755
+				   && in_array(
3756
+					   $default_where_conditions_value,
3757
+					   array(
3758
+						   EEM_Base::default_where_conditions_minimum_others,
3759
+						   EEM_Base::default_where_conditions_minimum_all,
3760
+					   ),
3761
+					   true
3762
+				   )
3763
+			   );
3764
+	}
3765
+
3766
+
3767
+	/**
3768
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3769
+	 * then we also add a special where condition which allows for that model's primary key
3770
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3771
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3772
+	 *
3773
+	 * @param array    $default_where_conditions
3774
+	 * @param array    $provided_where_conditions
3775
+	 * @param EEM_Base $model
3776
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3777
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3778
+	 * @throws EE_Error
3779
+	 */
3780
+	private function _override_defaults_or_make_null_friendly(
3781
+		$default_where_conditions,
3782
+		$provided_where_conditions,
3783
+		$model,
3784
+		$model_relation_path
3785
+	) {
3786
+		$null_friendly_where_conditions = array();
3787
+		$none_overridden = true;
3788
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3789
+		foreach ($default_where_conditions as $key => $val) {
3790
+			if (isset($provided_where_conditions[ $key ])) {
3791
+				$none_overridden = false;
3792
+			} else {
3793
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3794
+			}
3795
+		}
3796
+		if ($none_overridden && $default_where_conditions) {
3797
+			if ($model->has_primary_key_field()) {
3798
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3799
+																				. "."
3800
+																				. $model->primary_key_name() ] = array('IS NULL');
3801
+			}/*else{
3802 3802
                 //@todo NO PK, use other defaults
3803 3803
             }*/
3804
-        }
3805
-        return $null_friendly_where_conditions;
3806
-    }
3807
-
3808
-
3809
-
3810
-    /**
3811
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3812
-     * default where conditions on all get_all, update, and delete queries done by this model.
3813
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3814
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3815
-     *
3816
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3817
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3818
-     */
3819
-    private function _get_default_where_conditions($model_relation_path = null)
3820
-    {
3821
-        if ($this->_ignore_where_strategy) {
3822
-            return array();
3823
-        }
3824
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3825
-    }
3826
-
3827
-
3828
-
3829
-    /**
3830
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3831
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3832
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3833
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3834
-     * Similar to _get_default_where_conditions
3835
-     *
3836
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3837
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
-     */
3839
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3840
-    {
3841
-        if ($this->_ignore_where_strategy) {
3842
-            return array();
3843
-        }
3844
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3845
-    }
3846
-
3847
-
3848
-
3849
-    /**
3850
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3851
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3852
-     *
3853
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3854
-     * @return string
3855
-     * @throws EE_Error
3856
-     */
3857
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3858
-    {
3859
-        $selects = $this->_get_columns_to_select_for_this_model();
3860
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3861
-            $name_of_other_model_included) {
3862
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3863
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3864
-            foreach ($other_model_selects as $key => $value) {
3865
-                $selects[] = $value;
3866
-            }
3867
-        }
3868
-        return implode(", ", $selects);
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3875
-     * So that's going to be the columns for all the fields on the model
3876
-     *
3877
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3878
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3879
-     */
3880
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3881
-    {
3882
-        $fields = $this->field_settings();
3883
-        $selects = array();
3884
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3885
-            $model_relation_chain,
3886
-            $this->get_this_model_name()
3887
-        );
3888
-        foreach ($fields as $field_obj) {
3889
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3890
-                         . $field_obj->get_table_alias()
3891
-                         . "."
3892
-                         . $field_obj->get_table_column()
3893
-                         . " AS '"
3894
-                         . $table_alias_with_model_relation_chain_prefix
3895
-                         . $field_obj->get_table_alias()
3896
-                         . "."
3897
-                         . $field_obj->get_table_column()
3898
-                         . "'";
3899
-        }
3900
-        // make sure we are also getting the PKs of each table
3901
-        $tables = $this->get_tables();
3902
-        if (count($tables) > 1) {
3903
-            foreach ($tables as $table_obj) {
3904
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3905
-                                       . $table_obj->get_fully_qualified_pk_column();
3906
-                if (! in_array($qualified_pk_column, $selects)) {
3907
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3908
-                }
3909
-            }
3910
-        }
3911
-        return $selects;
3912
-    }
3913
-
3914
-
3915
-
3916
-    /**
3917
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3918
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3919
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3920
-     * SQL for joining, and the data types
3921
-     *
3922
-     * @param null|string                 $original_query_param
3923
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3924
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3925
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3926
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3927
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3928
-     *                                                          or 'Registration's
3929
-     * @param string                      $original_query_param what it originally was (eg
3930
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3931
-     *                                                          matches $query_param
3932
-     * @throws EE_Error
3933
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3934
-     */
3935
-    private function _extract_related_model_info_from_query_param(
3936
-        $query_param,
3937
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3938
-        $query_param_type,
3939
-        $original_query_param = null
3940
-    ) {
3941
-        if ($original_query_param === null) {
3942
-            $original_query_param = $query_param;
3943
-        }
3944
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3945
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3946
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3947
-        $allow_fields = in_array(
3948
-            $query_param_type,
3949
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3950
-            true
3951
-        );
3952
-        // check to see if we have a field on this model
3953
-        $this_model_fields = $this->field_settings(true);
3954
-        if (array_key_exists($query_param, $this_model_fields)) {
3955
-            if ($allow_fields) {
3956
-                return;
3957
-            }
3958
-            throw new EE_Error(
3959
-                sprintf(
3960
-                    __(
3961
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3962
-                        "event_espresso"
3963
-                    ),
3964
-                    $query_param,
3965
-                    get_class($this),
3966
-                    $query_param_type,
3967
-                    $original_query_param
3968
-                )
3969
-            );
3970
-        }
3971
-        // check if this is a special logic query param
3972
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3973
-            if ($allow_logic_query_params) {
3974
-                return;
3975
-            }
3976
-            throw new EE_Error(
3977
-                sprintf(
3978
-                    __(
3979
-                        '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',
3980
-                        'event_espresso'
3981
-                    ),
3982
-                    implode('", "', $this->_logic_query_param_keys),
3983
-                    $query_param,
3984
-                    get_class($this),
3985
-                    '<br />',
3986
-                    "\t"
3987
-                    . ' $passed_in_query_info = <pre>'
3988
-                    . print_r($passed_in_query_info, true)
3989
-                    . '</pre>'
3990
-                    . "\n\t"
3991
-                    . ' $query_param_type = '
3992
-                    . $query_param_type
3993
-                    . "\n\t"
3994
-                    . ' $original_query_param = '
3995
-                    . $original_query_param
3996
-                )
3997
-            );
3998
-        }
3999
-        // check if it's a custom selection
4000
-        if ($this->_custom_selections instanceof CustomSelects
4001
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4002
-        ) {
4003
-            return;
4004
-        }
4005
-        // check if has a model name at the beginning
4006
-        // and
4007
-        // check if it's a field on a related model
4008
-        if ($this->extractJoinModelFromQueryParams(
4009
-            $passed_in_query_info,
4010
-            $query_param,
4011
-            $original_query_param,
4012
-            $query_param_type
4013
-        )) {
4014
-            return;
4015
-        }
4016
-
4017
-        // ok so $query_param didn't start with a model name
4018
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4019
-        // it's wack, that's what it is
4020
-        throw new EE_Error(
4021
-            sprintf(
4022
-                esc_html__(
4023
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4024
-                    "event_espresso"
4025
-                ),
4026
-                $query_param,
4027
-                get_class($this),
4028
-                $query_param_type,
4029
-                $original_query_param
4030
-            )
4031
-        );
4032
-    }
4033
-
4034
-
4035
-    /**
4036
-     * Extracts any possible join model information from the provided possible_join_string.
4037
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4038
-     * parts that should be added to the query.
4039
-     *
4040
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4041
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4042
-     * @param null|string                 $original_query_param
4043
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4044
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4045
-     * @return bool  returns true if a join was added and false if not.
4046
-     * @throws EE_Error
4047
-     */
4048
-    private function extractJoinModelFromQueryParams(
4049
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4050
-        $possible_join_string,
4051
-        $original_query_param,
4052
-        $query_parameter_type
4053
-    ) {
4054
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4055
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4056
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4057
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4058
-                if ($possible_join_string === '') {
4059
-                    // nothing left to $query_param
4060
-                    // we should actually end in a field name, not a model like this!
4061
-                    throw new EE_Error(
4062
-                        sprintf(
4063
-                            esc_html__(
4064
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4065
-                                "event_espresso"
4066
-                            ),
4067
-                            $possible_join_string,
4068
-                            $query_parameter_type,
4069
-                            get_class($this),
4070
-                            $valid_related_model_name
4071
-                        )
4072
-                    );
4073
-                }
4074
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4075
-                $related_model_obj->_extract_related_model_info_from_query_param(
4076
-                    $possible_join_string,
4077
-                    $query_info_carrier,
4078
-                    $query_parameter_type,
4079
-                    $original_query_param
4080
-                );
4081
-                return true;
4082
-            }
4083
-            if ($possible_join_string === $valid_related_model_name) {
4084
-                $this->_add_join_to_model(
4085
-                    $valid_related_model_name,
4086
-                    $query_info_carrier,
4087
-                    $original_query_param
4088
-                );
4089
-                return true;
4090
-            }
4091
-        }
4092
-        return false;
4093
-    }
4094
-
4095
-
4096
-    /**
4097
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4098
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4099
-     * @throws EE_Error
4100
-     */
4101
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4102
-    {
4103
-        if ($this->_custom_selections instanceof CustomSelects
4104
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4105
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4106
-            )
4107
-        ) {
4108
-            $original_selects = $this->_custom_selections->originalSelects();
4109
-            foreach ($original_selects as $alias => $select_configuration) {
4110
-                $this->extractJoinModelFromQueryParams(
4111
-                    $query_info_carrier,
4112
-                    $select_configuration[0],
4113
-                    $select_configuration[0],
4114
-                    'custom_selects'
4115
-                );
4116
-            }
4117
-        }
4118
-    }
4119
-
4120
-
4121
-
4122
-    /**
4123
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4124
-     * and store it on $passed_in_query_info
4125
-     *
4126
-     * @param string                      $model_name
4127
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4128
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4129
-     *                                                          model and $model_name. Eg, if we are querying Event,
4130
-     *                                                          and are adding a join to 'Payment' with the original
4131
-     *                                                          query param key
4132
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4133
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4134
-     *                                                          Payment wants to add default query params so that it
4135
-     *                                                          will know what models to prepend onto its default query
4136
-     *                                                          params or in case it wants to rename tables (in case
4137
-     *                                                          there are multiple joins to the same table)
4138
-     * @return void
4139
-     * @throws EE_Error
4140
-     */
4141
-    private function _add_join_to_model(
4142
-        $model_name,
4143
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4144
-        $original_query_param
4145
-    ) {
4146
-        $relation_obj = $this->related_settings_for($model_name);
4147
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4148
-        // check if the relation is HABTM, because then we're essentially doing two joins
4149
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4150
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4151
-            $join_model_obj = $relation_obj->get_join_model();
4152
-            // replace the model specified with the join model for this relation chain, whi
4153
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4154
-                $model_name,
4155
-                $join_model_obj->get_this_model_name(),
4156
-                $model_relation_chain
4157
-            );
4158
-            $passed_in_query_info->merge(
4159
-                new EE_Model_Query_Info_Carrier(
4160
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4161
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4162
-                )
4163
-            );
4164
-        }
4165
-        // now just join to the other table pointed to by the relation object, and add its data types
4166
-        $passed_in_query_info->merge(
4167
-            new EE_Model_Query_Info_Carrier(
4168
-                array($model_relation_chain => $model_name),
4169
-                $relation_obj->get_join_statement($model_relation_chain)
4170
-            )
4171
-        );
4172
-    }
4173
-
4174
-
4175
-
4176
-    /**
4177
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4178
-     *
4179
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4180
-     * @return string of SQL
4181
-     * @throws EE_Error
4182
-     */
4183
-    private function _construct_where_clause($where_params)
4184
-    {
4185
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4186
-        if ($SQL) {
4187
-            return " WHERE " . $SQL;
4188
-        }
4189
-        return '';
4190
-    }
4191
-
4192
-
4193
-
4194
-    /**
4195
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4196
-     * and should be passed HAVING parameters, not WHERE parameters
4197
-     *
4198
-     * @param array $having_params
4199
-     * @return string
4200
-     * @throws EE_Error
4201
-     */
4202
-    private function _construct_having_clause($having_params)
4203
-    {
4204
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4205
-        if ($SQL) {
4206
-            return " HAVING " . $SQL;
4207
-        }
4208
-        return '';
4209
-    }
4210
-
4211
-
4212
-    /**
4213
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4214
-     * Event_Meta.meta_value = 'foo'))"
4215
-     *
4216
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4217
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4218
-     * @throws EE_Error
4219
-     * @return string of SQL
4220
-     */
4221
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4222
-    {
4223
-        $where_clauses = array();
4224
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4225
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4226
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4227
-                switch ($query_param) {
4228
-                    case 'not':
4229
-                    case 'NOT':
4230
-                        $where_clauses[] = "! ("
4231
-                                           . $this->_construct_condition_clause_recursive(
4232
-                                               $op_and_value_or_sub_condition,
4233
-                                               $glue
4234
-                                           )
4235
-                                           . ")";
4236
-                        break;
4237
-                    case 'and':
4238
-                    case 'AND':
4239
-                        $where_clauses[] = " ("
4240
-                                           . $this->_construct_condition_clause_recursive(
4241
-                                               $op_and_value_or_sub_condition,
4242
-                                               ' AND '
4243
-                                           )
4244
-                                           . ")";
4245
-                        break;
4246
-                    case 'or':
4247
-                    case 'OR':
4248
-                        $where_clauses[] = " ("
4249
-                                           . $this->_construct_condition_clause_recursive(
4250
-                                               $op_and_value_or_sub_condition,
4251
-                                               ' OR '
4252
-                                           )
4253
-                                           . ")";
4254
-                        break;
4255
-                }
4256
-            } else {
4257
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4258
-                // if it's not a normal field, maybe it's a custom selection?
4259
-                if (! $field_obj) {
4260
-                    if ($this->_custom_selections instanceof CustomSelects) {
4261
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4262
-                    } else {
4263
-                        throw new EE_Error(sprintf(__(
4264
-                            "%s is neither a valid model field name, nor a custom selection",
4265
-                            "event_espresso"
4266
-                        ), $query_param));
4267
-                    }
4268
-                }
4269
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4270
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4271
-            }
4272
-        }
4273
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4274
-    }
4275
-
4276
-
4277
-
4278
-    /**
4279
-     * Takes the input parameter and extract the table name (alias) and column name
4280
-     *
4281
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4282
-     * @throws EE_Error
4283
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4284
-     */
4285
-    private function _deduce_column_name_from_query_param($query_param)
4286
-    {
4287
-        $field = $this->_deduce_field_from_query_param($query_param);
4288
-        if ($field) {
4289
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4290
-                $field->get_model_name(),
4291
-                $query_param
4292
-            );
4293
-            return $table_alias_prefix . $field->get_qualified_column();
4294
-        }
4295
-        if ($this->_custom_selections instanceof CustomSelects
4296
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4297
-        ) {
4298
-            // maybe it's custom selection item?
4299
-            // if so, just use it as the "column name"
4300
-            return $query_param;
4301
-        }
4302
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4303
-            ? implode(',', $this->_custom_selections->columnAliases())
4304
-            : '';
4305
-        throw new EE_Error(
4306
-            sprintf(
4307
-                __(
4308
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4309
-                    "event_espresso"
4310
-                ),
4311
-                $query_param,
4312
-                $custom_select_aliases
4313
-            )
4314
-        );
4315
-    }
4316
-
4317
-
4318
-
4319
-    /**
4320
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4321
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4322
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4323
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4324
-     *
4325
-     * @param string $condition_query_param_key
4326
-     * @return string
4327
-     */
4328
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4329
-    {
4330
-        $pos_of_star = strpos($condition_query_param_key, '*');
4331
-        if ($pos_of_star === false) {
4332
-            return $condition_query_param_key;
4333
-        }
4334
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4335
-        return $condition_query_param_sans_star;
4336
-    }
4337
-
4338
-
4339
-
4340
-    /**
4341
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4342
-     *
4343
-     * @param                            mixed      array | string    $op_and_value
4344
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4345
-     * @throws EE_Error
4346
-     * @return string
4347
-     */
4348
-    private function _construct_op_and_value($op_and_value, $field_obj)
4349
-    {
4350
-        if (is_array($op_and_value)) {
4351
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4352
-            if (! $operator) {
4353
-                $php_array_like_string = array();
4354
-                foreach ($op_and_value as $key => $value) {
4355
-                    $php_array_like_string[] = "$key=>$value";
4356
-                }
4357
-                throw new EE_Error(
4358
-                    sprintf(
4359
-                        __(
4360
-                            "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))",
4361
-                            "event_espresso"
4362
-                        ),
4363
-                        implode(",", $php_array_like_string)
4364
-                    )
4365
-                );
4366
-            }
4367
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4368
-        } else {
4369
-            $operator = '=';
4370
-            $value = $op_and_value;
4371
-        }
4372
-        // check to see if the value is actually another field
4373
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4374
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4375
-        }
4376
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4377
-            // in this case, the value should be an array, or at least a comma-separated list
4378
-            // it will need to handle a little differently
4379
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4380
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4381
-            return $operator . SP . $cleaned_value;
4382
-        }
4383
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4384
-            // the value should be an array with count of two.
4385
-            if (count($value) !== 2) {
4386
-                throw new EE_Error(
4387
-                    sprintf(
4388
-                        __(
4389
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4390
-                            'event_espresso'
4391
-                        ),
4392
-                        "BETWEEN"
4393
-                    )
4394
-                );
4395
-            }
4396
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4397
-            return $operator . SP . $cleaned_value;
4398
-        }
4399
-        if (in_array($operator, $this->valid_null_style_operators())) {
4400
-            if ($value !== null) {
4401
-                throw new EE_Error(
4402
-                    sprintf(
4403
-                        __(
4404
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4405
-                            "event_espresso"
4406
-                        ),
4407
-                        $value,
4408
-                        $operator
4409
-                    )
4410
-                );
4411
-            }
4412
-            return $operator;
4413
-        }
4414
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4415
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4416
-            // remove other junk. So just treat it as a string.
4417
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4418
-        }
4419
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4421
-        }
4422
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4423
-            throw new EE_Error(
4424
-                sprintf(
4425
-                    __(
4426
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4427
-                        'event_espresso'
4428
-                    ),
4429
-                    $operator,
4430
-                    $operator
4431
-                )
4432
-            );
4433
-        }
4434
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4435
-            throw new EE_Error(
4436
-                sprintf(
4437
-                    __(
4438
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4439
-                        'event_espresso'
4440
-                    ),
4441
-                    $operator,
4442
-                    $operator
4443
-                )
4444
-            );
4445
-        }
4446
-        throw new EE_Error(
4447
-            sprintf(
4448
-                __(
4449
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4450
-                    "event_espresso"
4451
-                ),
4452
-                http_build_query($op_and_value)
4453
-            )
4454
-        );
4455
-    }
4456
-
4457
-
4458
-
4459
-    /**
4460
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4461
-     *
4462
-     * @param array                      $values
4463
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4464
-     *                                              '%s'
4465
-     * @return string
4466
-     * @throws EE_Error
4467
-     */
4468
-    public function _construct_between_value($values, $field_obj)
4469
-    {
4470
-        $cleaned_values = array();
4471
-        foreach ($values as $value) {
4472
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4473
-        }
4474
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4475
-    }
4476
-
4477
-
4478
-
4479
-    /**
4480
-     * Takes an array or a comma-separated list of $values and cleans them
4481
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4482
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4483
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4484
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4485
-     *
4486
-     * @param mixed                      $values    array or comma-separated string
4487
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4488
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4489
-     * @throws EE_Error
4490
-     */
4491
-    public function _construct_in_value($values, $field_obj)
4492
-    {
4493
-        // check if the value is a CSV list
4494
-        if (is_string($values)) {
4495
-            // in which case, turn it into an array
4496
-            $values = explode(",", $values);
4497
-        }
4498
-        $cleaned_values = array();
4499
-        foreach ($values as $value) {
4500
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4501
-        }
4502
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4503
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4504
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4505
-        if (empty($cleaned_values)) {
4506
-            $all_fields = $this->field_settings();
4507
-            $a_field = array_shift($all_fields);
4508
-            $main_table = $this->_get_main_table();
4509
-            $cleaned_values[] = "SELECT "
4510
-                                . $a_field->get_table_column()
4511
-                                . " FROM "
4512
-                                . $main_table->get_table_name()
4513
-                                . " WHERE FALSE";
4514
-        }
4515
-        return "(" . implode(",", $cleaned_values) . ")";
4516
-    }
4517
-
4518
-
4519
-
4520
-    /**
4521
-     * @param mixed                      $value
4522
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4523
-     * @throws EE_Error
4524
-     * @return false|null|string
4525
-     */
4526
-    private function _wpdb_prepare_using_field($value, $field_obj)
4527
-    {
4528
-        /** @type WPDB $wpdb */
4529
-        global $wpdb;
4530
-        if ($field_obj instanceof EE_Model_Field_Base) {
4531
-            return $wpdb->prepare(
4532
-                $field_obj->get_wpdb_data_type(),
4533
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4534
-            );
4535
-        } //$field_obj should really just be a data type
4536
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4537
-            throw new EE_Error(
4538
-                sprintf(
4539
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4540
-                    $field_obj,
4541
-                    implode(",", $this->_valid_wpdb_data_types)
4542
-                )
4543
-            );
4544
-        }
4545
-        return $wpdb->prepare($field_obj, $value);
4546
-    }
4547
-
4548
-
4549
-
4550
-    /**
4551
-     * Takes the input parameter and finds the model field that it indicates.
4552
-     *
4553
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4554
-     * @throws EE_Error
4555
-     * @return EE_Model_Field_Base
4556
-     */
4557
-    protected function _deduce_field_from_query_param($query_param_name)
4558
-    {
4559
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4560
-        // which will help us find the database table and column
4561
-        $query_param_parts = explode(".", $query_param_name);
4562
-        if (empty($query_param_parts)) {
4563
-            throw new EE_Error(sprintf(__(
4564
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4565
-                'event_espresso'
4566
-            ), $query_param_name));
4567
-        }
4568
-        $number_of_parts = count($query_param_parts);
4569
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4570
-        if ($number_of_parts === 1) {
4571
-            $field_name = $last_query_param_part;
4572
-            $model_obj = $this;
4573
-        } else {// $number_of_parts >= 2
4574
-            // the last part is the column name, and there are only 2parts. therefore...
4575
-            $field_name = $last_query_param_part;
4576
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4577
-        }
4578
-        try {
4579
-            return $model_obj->field_settings_for($field_name);
4580
-        } catch (EE_Error $e) {
4581
-            return null;
4582
-        }
4583
-    }
4584
-
4585
-
4586
-
4587
-    /**
4588
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4589
-     * alias and column which corresponds to it
4590
-     *
4591
-     * @param string $field_name
4592
-     * @throws EE_Error
4593
-     * @return string
4594
-     */
4595
-    public function _get_qualified_column_for_field($field_name)
4596
-    {
4597
-        $all_fields = $this->field_settings();
4598
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4599
-        if ($field) {
4600
-            return $field->get_qualified_column();
4601
-        }
4602
-        throw new EE_Error(
4603
-            sprintf(
4604
-                __(
4605
-                    "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.",
4606
-                    'event_espresso'
4607
-                ),
4608
-                $field_name,
4609
-                get_class($this)
4610
-            )
4611
-        );
4612
-    }
4613
-
4614
-
4615
-
4616
-    /**
4617
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4618
-     * Example usage:
4619
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4620
-     *      array(),
4621
-     *      ARRAY_A,
4622
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4623
-     *  );
4624
-     * is equivalent to
4625
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4626
-     * and
4627
-     *  EEM_Event::instance()->get_all_wpdb_results(
4628
-     *      array(
4629
-     *          array(
4630
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4631
-     *          ),
4632
-     *          ARRAY_A,
4633
-     *          implode(
4634
-     *              ', ',
4635
-     *              array_merge(
4636
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4637
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4638
-     *              )
4639
-     *          )
4640
-     *      )
4641
-     *  );
4642
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4643
-     *
4644
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4645
-     *                                            and the one whose fields you are selecting for example: when querying
4646
-     *                                            tickets model and selecting fields from the tickets model you would
4647
-     *                                            leave this parameter empty, because no models are needed to join
4648
-     *                                            between the queried model and the selected one. Likewise when
4649
-     *                                            querying the datetime model and selecting fields from the tickets
4650
-     *                                            model, it would also be left empty, because there is a direct
4651
-     *                                            relation from datetimes to tickets, so no model is needed to join
4652
-     *                                            them together. However, when querying from the event model and
4653
-     *                                            selecting fields from the ticket model, you should provide the string
4654
-     *                                            'Datetime', indicating that the event model must first join to the
4655
-     *                                            datetime model in order to find its relation to ticket model.
4656
-     *                                            Also, when querying from the venue model and selecting fields from
4657
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4658
-     *                                            indicating you need to join the venue model to the event model,
4659
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4660
-     *                                            This string is used to deduce the prefix that gets added onto the
4661
-     *                                            models' tables qualified columns
4662
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4663
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4664
-     *                                            qualified column names
4665
-     * @return array|string
4666
-     */
4667
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4668
-    {
4669
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4670
-        $qualified_columns = array();
4671
-        foreach ($this->field_settings() as $field_name => $field) {
4672
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4673
-        }
4674
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4675
-    }
4676
-
4677
-
4678
-
4679
-    /**
4680
-     * constructs the select use on special limit joins
4681
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4682
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4683
-     * (as that is typically where the limits would be set).
4684
-     *
4685
-     * @param  string       $table_alias The table the select is being built for
4686
-     * @param  mixed|string $limit       The limit for this select
4687
-     * @return string                The final select join element for the query.
4688
-     */
4689
-    public function _construct_limit_join_select($table_alias, $limit)
4690
-    {
4691
-        $SQL = '';
4692
-        foreach ($this->_tables as $table_obj) {
4693
-            if ($table_obj instanceof EE_Primary_Table) {
4694
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4695
-                    ? $table_obj->get_select_join_limit($limit)
4696
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4697
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4698
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4699
-                    ? $table_obj->get_select_join_limit_join($limit)
4700
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4701
-            }
4702
-        }
4703
-        return $SQL;
4704
-    }
4705
-
4706
-
4707
-
4708
-    /**
4709
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4710
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4711
-     *
4712
-     * @return string SQL
4713
-     * @throws EE_Error
4714
-     */
4715
-    public function _construct_internal_join()
4716
-    {
4717
-        $SQL = $this->_get_main_table()->get_table_sql();
4718
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4719
-        return $SQL;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Constructs the SQL for joining all the tables on this model.
4726
-     * Normally $alias should be the primary table's alias, but in cases where
4727
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4728
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4729
-     * alias, this will construct SQL like:
4730
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4731
-     * With $alias being a secondary table's alias, this will construct SQL like:
4732
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4733
-     *
4734
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4735
-     * @return string
4736
-     */
4737
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4738
-    {
4739
-        $SQL = '';
4740
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4741
-        foreach ($this->_tables as $table_obj) {
4742
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4743
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4744
-                    // so we're joining to this table, meaning the table is already in
4745
-                    // the FROM statement, BUT the primary table isn't. So we want
4746
-                    // to add the inverse join sql
4747
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4748
-                } else {
4749
-                    // just add a regular JOIN to this table from the primary table
4750
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4751
-                }
4752
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4753
-        }
4754
-        return $SQL;
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4761
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4762
-     * their data type (eg, '%s', '%d', etc)
4763
-     *
4764
-     * @return array
4765
-     */
4766
-    public function _get_data_types()
4767
-    {
4768
-        $data_types = array();
4769
-        foreach ($this->field_settings() as $field_obj) {
4770
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4771
-            /** @var $field_obj EE_Model_Field_Base */
4772
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4773
-        }
4774
-        return $data_types;
4775
-    }
4776
-
4777
-
4778
-
4779
-    /**
4780
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4781
-     *
4782
-     * @param string $model_name
4783
-     * @throws EE_Error
4784
-     * @return EEM_Base
4785
-     */
4786
-    public function get_related_model_obj($model_name)
4787
-    {
4788
-        $model_classname = "EEM_" . $model_name;
4789
-        if (! class_exists($model_classname)) {
4790
-            throw new EE_Error(sprintf(__(
4791
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4792
-                'event_espresso'
4793
-            ), $model_name, $model_classname));
4794
-        }
4795
-        return call_user_func($model_classname . "::instance");
4796
-    }
4797
-
4798
-
4799
-
4800
-    /**
4801
-     * Returns the array of EE_ModelRelations for this model.
4802
-     *
4803
-     * @return EE_Model_Relation_Base[]
4804
-     */
4805
-    public function relation_settings()
4806
-    {
4807
-        return $this->_model_relations;
4808
-    }
4809
-
4810
-
4811
-
4812
-    /**
4813
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4814
-     * because without THOSE models, this model probably doesn't have much purpose.
4815
-     * (Eg, without an event, datetimes have little purpose.)
4816
-     *
4817
-     * @return EE_Belongs_To_Relation[]
4818
-     */
4819
-    public function belongs_to_relations()
4820
-    {
4821
-        $belongs_to_relations = array();
4822
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4823
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4824
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4825
-            }
4826
-        }
4827
-        return $belongs_to_relations;
4828
-    }
4829
-
4830
-
4831
-
4832
-    /**
4833
-     * Returns the specified EE_Model_Relation, or throws an exception
4834
-     *
4835
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4836
-     * @throws EE_Error
4837
-     * @return EE_Model_Relation_Base
4838
-     */
4839
-    public function related_settings_for($relation_name)
4840
-    {
4841
-        $relatedModels = $this->relation_settings();
4842
-        if (! array_key_exists($relation_name, $relatedModels)) {
4843
-            throw new EE_Error(
4844
-                sprintf(
4845
-                    __(
4846
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4847
-                        'event_espresso'
4848
-                    ),
4849
-                    $relation_name,
4850
-                    $this->_get_class_name(),
4851
-                    implode(', ', array_keys($relatedModels))
4852
-                )
4853
-            );
4854
-        }
4855
-        return $relatedModels[ $relation_name ];
4856
-    }
4857
-
4858
-
4859
-
4860
-    /**
4861
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4862
-     * fields
4863
-     *
4864
-     * @param string $fieldName
4865
-     * @param boolean $include_db_only_fields
4866
-     * @throws EE_Error
4867
-     * @return EE_Model_Field_Base
4868
-     */
4869
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4870
-    {
4871
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4872
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4873
-            throw new EE_Error(sprintf(
4874
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4875
-                $fieldName,
4876
-                get_class($this)
4877
-            ));
4878
-        }
4879
-        return $fieldSettings[ $fieldName ];
4880
-    }
4881
-
4882
-
4883
-
4884
-    /**
4885
-     * Checks if this field exists on this model
4886
-     *
4887
-     * @param string $fieldName a key in the model's _field_settings array
4888
-     * @return boolean
4889
-     */
4890
-    public function has_field($fieldName)
4891
-    {
4892
-        $fieldSettings = $this->field_settings(true);
4893
-        if (isset($fieldSettings[ $fieldName ])) {
4894
-            return true;
4895
-        }
4896
-        return false;
4897
-    }
4898
-
4899
-
4900
-
4901
-    /**
4902
-     * Returns whether or not this model has a relation to the specified model
4903
-     *
4904
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4905
-     * @return boolean
4906
-     */
4907
-    public function has_relation($relation_name)
4908
-    {
4909
-        $relations = $this->relation_settings();
4910
-        if (isset($relations[ $relation_name ])) {
4911
-            return true;
4912
-        }
4913
-        return false;
4914
-    }
4915
-
4916
-
4917
-
4918
-    /**
4919
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4920
-     * Eg, on EE_Answer that would be ANS_ID field object
4921
-     *
4922
-     * @param $field_obj
4923
-     * @return boolean
4924
-     */
4925
-    public function is_primary_key_field($field_obj)
4926
-    {
4927
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4928
-    }
4929
-
4930
-
4931
-
4932
-    /**
4933
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
-     * Eg, on EE_Answer that would be ANS_ID field object
4935
-     *
4936
-     * @return EE_Model_Field_Base
4937
-     * @throws EE_Error
4938
-     */
4939
-    public function get_primary_key_field()
4940
-    {
4941
-        if ($this->_primary_key_field === null) {
4942
-            foreach ($this->field_settings(true) as $field_obj) {
4943
-                if ($this->is_primary_key_field($field_obj)) {
4944
-                    $this->_primary_key_field = $field_obj;
4945
-                    break;
4946
-                }
4947
-            }
4948
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4949
-                throw new EE_Error(sprintf(
4950
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4951
-                    get_class($this)
4952
-                ));
4953
-            }
4954
-        }
4955
-        return $this->_primary_key_field;
4956
-    }
4957
-
4958
-
4959
-
4960
-    /**
4961
-     * Returns whether or not not there is a primary key on this model.
4962
-     * Internally does some caching.
4963
-     *
4964
-     * @return boolean
4965
-     */
4966
-    public function has_primary_key_field()
4967
-    {
4968
-        if ($this->_has_primary_key_field === null) {
4969
-            try {
4970
-                $this->get_primary_key_field();
4971
-                $this->_has_primary_key_field = true;
4972
-            } catch (EE_Error $e) {
4973
-                $this->_has_primary_key_field = false;
4974
-            }
4975
-        }
4976
-        return $this->_has_primary_key_field;
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * Finds the first field of type $field_class_name.
4983
-     *
4984
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4985
-     *                                 EE_Foreign_Key_Field, etc
4986
-     * @return EE_Model_Field_Base or null if none is found
4987
-     */
4988
-    public function get_a_field_of_type($field_class_name)
4989
-    {
4990
-        foreach ($this->field_settings() as $field) {
4991
-            if ($field instanceof $field_class_name) {
4992
-                return $field;
4993
-            }
4994
-        }
4995
-        return null;
4996
-    }
4997
-
4998
-
4999
-
5000
-    /**
5001
-     * Gets a foreign key field pointing to model.
5002
-     *
5003
-     * @param string $model_name eg Event, Registration, not EEM_Event
5004
-     * @return EE_Foreign_Key_Field_Base
5005
-     * @throws EE_Error
5006
-     */
5007
-    public function get_foreign_key_to($model_name)
5008
-    {
5009
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5010
-            foreach ($this->field_settings() as $field) {
5011
-                if ($field instanceof EE_Foreign_Key_Field_Base
5012
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5013
-                ) {
5014
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5015
-                    break;
5016
-                }
5017
-            }
5018
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5019
-                throw new EE_Error(sprintf(__(
5020
-                    "There is no foreign key field pointing to model %s on model %s",
5021
-                    'event_espresso'
5022
-                ), $model_name, get_class($this)));
5023
-            }
5024
-        }
5025
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5026
-    }
5027
-
5028
-
5029
-
5030
-    /**
5031
-     * Gets the table name (including $wpdb->prefix) for the table alias
5032
-     *
5033
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5034
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5035
-     *                            Either one works
5036
-     * @return string
5037
-     */
5038
-    public function get_table_for_alias($table_alias)
5039
-    {
5040
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5041
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5042
-    }
5043
-
5044
-
5045
-
5046
-    /**
5047
-     * Returns a flat array of all field son this model, instead of organizing them
5048
-     * by table_alias as they are in the constructor.
5049
-     *
5050
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5051
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5052
-     */
5053
-    public function field_settings($include_db_only_fields = false)
5054
-    {
5055
-        if ($include_db_only_fields) {
5056
-            if ($this->_cached_fields === null) {
5057
-                $this->_cached_fields = array();
5058
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5059
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5060
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5061
-                    }
5062
-                }
5063
-            }
5064
-            return $this->_cached_fields;
5065
-        }
5066
-        if ($this->_cached_fields_non_db_only === null) {
5067
-            $this->_cached_fields_non_db_only = array();
5068
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5069
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5070
-                    /** @var $field_obj EE_Model_Field_Base */
5071
-                    if (! $field_obj->is_db_only_field()) {
5072
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5073
-                    }
5074
-                }
5075
-            }
5076
-        }
5077
-        return $this->_cached_fields_non_db_only;
5078
-    }
5079
-
5080
-
5081
-
5082
-    /**
5083
-     *        cycle though array of attendees and create objects out of each item
5084
-     *
5085
-     * @access        private
5086
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5087
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5088
-     *                           numerically indexed)
5089
-     * @throws EE_Error
5090
-     */
5091
-    protected function _create_objects($rows = array())
5092
-    {
5093
-        $array_of_objects = array();
5094
-        if (empty($rows)) {
5095
-            return array();
5096
-        }
5097
-        $count_if_model_has_no_primary_key = 0;
5098
-        $has_primary_key = $this->has_primary_key_field();
5099
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5100
-        foreach ((array) $rows as $row) {
5101
-            if (empty($row)) {
5102
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5103
-                return array();
5104
-            }
5105
-            // check if we've already set this object in the results array,
5106
-            // in which case there's no need to process it further (again)
5107
-            if ($has_primary_key) {
5108
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5109
-                    $row,
5110
-                    $primary_key_field->get_qualified_column(),
5111
-                    $primary_key_field->get_table_column()
5112
-                );
5113
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5114
-                    continue;
5115
-                }
5116
-            }
5117
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5118
-            if (! $classInstance) {
5119
-                throw new EE_Error(
5120
-                    sprintf(
5121
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5122
-                        $this->get_this_model_name(),
5123
-                        http_build_query($row)
5124
-                    )
5125
-                );
5126
-            }
5127
-            // set the timezone on the instantiated objects
5128
-            $classInstance->set_timezone($this->_timezone);
5129
-            // make sure if there is any timezone setting present that we set the timezone for the object
5130
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5131
-            $array_of_objects[ $key ] = $classInstance;
5132
-            // also, for all the relations of type BelongsTo, see if we can cache
5133
-            // those related models
5134
-            // (we could do this for other relations too, but if there are conditions
5135
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5136
-            // so it requires a little more thought than just caching them immediately...)
5137
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5138
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5139
-                    // check if this model's INFO is present. If so, cache it on the model
5140
-                    $other_model = $relation_obj->get_other_model();
5141
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5142
-                    // if we managed to make a model object from the results, cache it on the main model object
5143
-                    if ($other_model_obj_maybe) {
5144
-                        // set timezone on these other model objects if they are present
5145
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5146
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5147
-                    }
5148
-                }
5149
-            }
5150
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5151
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5152
-            // the field in the CustomSelects object
5153
-            if ($this->_custom_selections instanceof CustomSelects) {
5154
-                $classInstance->setCustomSelectsValues(
5155
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5156
-                );
5157
-            }
5158
-        }
5159
-        return $array_of_objects;
5160
-    }
5161
-
5162
-
5163
-    /**
5164
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5165
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5166
-     *
5167
-     * @param array $db_results_row
5168
-     * @return array
5169
-     */
5170
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5171
-    {
5172
-        $results = array();
5173
-        if ($this->_custom_selections instanceof CustomSelects) {
5174
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5175
-                if (isset($db_results_row[ $alias ])) {
5176
-                    $results[ $alias ] = $this->convertValueToDataType(
5177
-                        $db_results_row[ $alias ],
5178
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5179
-                    );
5180
-                }
5181
-            }
5182
-        }
5183
-        return $results;
5184
-    }
5185
-
5186
-
5187
-    /**
5188
-     * This will set the value for the given alias
5189
-     * @param string $value
5190
-     * @param string $datatype (one of %d, %s, %f)
5191
-     * @return int|string|float (int for %d, string for %s, float for %f)
5192
-     */
5193
-    protected function convertValueToDataType($value, $datatype)
5194
-    {
5195
-        switch ($datatype) {
5196
-            case '%f':
5197
-                return (float) $value;
5198
-            case '%d':
5199
-                return (int) $value;
5200
-            default:
5201
-                return (string) $value;
5202
-        }
5203
-    }
5204
-
5205
-
5206
-    /**
5207
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5208
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5209
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5210
-     * object (as set in the model_field!).
5211
-     *
5212
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5213
-     */
5214
-    public function create_default_object()
5215
-    {
5216
-        $this_model_fields_and_values = array();
5217
-        // setup the row using default values;
5218
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5219
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5220
-        }
5221
-        $className = $this->_get_class_name();
5222
-        $classInstance = EE_Registry::instance()
5223
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5224
-        return $classInstance;
5225
-    }
5226
-
5227
-
5228
-
5229
-    /**
5230
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5231
-     *                             or an stdClass where each property is the name of a column,
5232
-     * @return EE_Base_Class
5233
-     * @throws EE_Error
5234
-     */
5235
-    public function instantiate_class_from_array_or_object($cols_n_values)
5236
-    {
5237
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5238
-            $cols_n_values = get_object_vars($cols_n_values);
5239
-        }
5240
-        $primary_key = null;
5241
-        // make sure the array only has keys that are fields/columns on this model
5242
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5243
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5245
-        }
5246
-        $className = $this->_get_class_name();
5247
-        // check we actually found results that we can use to build our model object
5248
-        // if not, return null
5249
-        if ($this->has_primary_key_field()) {
5250
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5251
-                return null;
5252
-            }
5253
-        } elseif ($this->unique_indexes()) {
5254
-            $first_column = reset($this_model_fields_n_values);
5255
-            if (empty($first_column)) {
5256
-                return null;
5257
-            }
5258
-        }
5259
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5260
-        if ($primary_key) {
5261
-            $classInstance = $this->get_from_entity_map($primary_key);
5262
-            if (! $classInstance) {
5263
-                $classInstance = EE_Registry::instance()
5264
-                                            ->load_class(
5265
-                                                $className,
5266
-                                                array($this_model_fields_n_values, $this->_timezone),
5267
-                                                true,
5268
-                                                false
5269
-                                            );
5270
-                // add this new object to the entity map
5271
-                $classInstance = $this->add_to_entity_map($classInstance);
5272
-            }
5273
-        } else {
5274
-            $classInstance = EE_Registry::instance()
5275
-                                        ->load_class(
5276
-                                            $className,
5277
-                                            array($this_model_fields_n_values, $this->_timezone),
5278
-                                            true,
5279
-                                            false
5280
-                                        );
5281
-        }
5282
-        return $classInstance;
5283
-    }
5284
-
5285
-
5286
-
5287
-    /**
5288
-     * Gets the model object from the  entity map if it exists
5289
-     *
5290
-     * @param int|string $id the ID of the model object
5291
-     * @return EE_Base_Class
5292
-     */
5293
-    public function get_from_entity_map($id)
5294
-    {
5295
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5296
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5297
-    }
5298
-
5299
-
5300
-
5301
-    /**
5302
-     * add_to_entity_map
5303
-     * Adds the object to the model's entity mappings
5304
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5305
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5306
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5307
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5308
-     *        then this method should be called immediately after the update query
5309
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5310
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5311
-     *
5312
-     * @param    EE_Base_Class $object
5313
-     * @throws EE_Error
5314
-     * @return \EE_Base_Class
5315
-     */
5316
-    public function add_to_entity_map(EE_Base_Class $object)
5317
-    {
5318
-        $className = $this->_get_class_name();
5319
-        if (! $object instanceof $className) {
5320
-            throw new EE_Error(sprintf(
5321
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5322
-                is_object($object) ? get_class($object) : $object,
5323
-                $className
5324
-            ));
5325
-        }
5326
-        /** @var $object EE_Base_Class */
5327
-        if (! $object->ID()) {
5328
-            throw new EE_Error(sprintf(__(
5329
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5330
-                "event_espresso"
5331
-            ), get_class($this)));
5332
-        }
5333
-        // double check it's not already there
5334
-        $classInstance = $this->get_from_entity_map($object->ID());
5335
-        if ($classInstance) {
5336
-            return $classInstance;
5337
-        }
5338
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5339
-        return $object;
5340
-    }
5341
-
5342
-
5343
-
5344
-    /**
5345
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5346
-     * if no identifier is provided, then the entire entity map is emptied
5347
-     *
5348
-     * @param int|string $id the ID of the model object
5349
-     * @return boolean
5350
-     */
5351
-    public function clear_entity_map($id = null)
5352
-    {
5353
-        if (empty($id)) {
5354
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5355
-            return true;
5356
-        }
5357
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5358
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5359
-            return true;
5360
-        }
5361
-        return false;
5362
-    }
5363
-
5364
-
5365
-
5366
-    /**
5367
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5368
-     * Given an array where keys are column (or column alias) names and values,
5369
-     * returns an array of their corresponding field names and database values
5370
-     *
5371
-     * @param array $cols_n_values
5372
-     * @return array
5373
-     */
5374
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5375
-    {
5376
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5377
-    }
5378
-
5379
-
5380
-
5381
-    /**
5382
-     * _deduce_fields_n_values_from_cols_n_values
5383
-     * Given an array where keys are column (or column alias) names and values,
5384
-     * returns an array of their corresponding field names and database values
5385
-     *
5386
-     * @param string $cols_n_values
5387
-     * @return array
5388
-     */
5389
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
-    {
5391
-        $this_model_fields_n_values = array();
5392
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5393
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5394
-                $cols_n_values,
5395
-                $table_obj->get_fully_qualified_pk_column(),
5396
-                $table_obj->get_pk_column()
5397
-            );
5398
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5399
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5400
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5401
-                    if (! $field_obj->is_db_only_field()) {
5402
-                        // prepare field as if its coming from db
5403
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5404
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5405
-                    }
5406
-                }
5407
-            } else {
5408
-                // the table's rows existed. Use their values
5409
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5410
-                    if (! $field_obj->is_db_only_field()) {
5411
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5412
-                            $cols_n_values,
5413
-                            $field_obj->get_qualified_column(),
5414
-                            $field_obj->get_table_column()
5415
-                        );
5416
-                    }
5417
-                }
5418
-            }
5419
-        }
5420
-        return $this_model_fields_n_values;
5421
-    }
5422
-
5423
-
5424
-    /**
5425
-     * @param $cols_n_values
5426
-     * @param $qualified_column
5427
-     * @param $regular_column
5428
-     * @return null
5429
-     * @throws EE_Error
5430
-     * @throws ReflectionException
5431
-     */
5432
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5433
-    {
5434
-        $value = null;
5435
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5436
-        // does the field on the model relate to this column retrieved from the db?
5437
-        // or is it a db-only field? (not relating to the model)
5438
-        if (isset($cols_n_values[ $qualified_column ])) {
5439
-            $value = $cols_n_values[ $qualified_column ];
5440
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5441
-            $value = $cols_n_values[ $regular_column ];
5442
-        } elseif (! empty($this->foreign_key_aliases)) {
5443
-            // no PK?  ok check if there is a foreign key alias set for this table
5444
-            // then check if that alias exists in the incoming data
5445
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5446
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5447
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5448
-                    $value = $cols_n_values[ $FK_alias ];
5449
-                    list($pk_class) = explode('.', $PK_column);
5450
-                    $pk_model_name = "EEM_{$pk_class}";
5451
-                    /** @var EEM_Base $pk_model */
5452
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5453
-                    if ($pk_model instanceof EEM_Base) {
5454
-                        // make sure object is pulled from db and added to entity map
5455
-                        $pk_model->get_one_by_ID($value);
5456
-                    }
5457
-                    break;
5458
-                }
5459
-            }
5460
-        }
5461
-        return $value;
5462
-    }
5463
-
5464
-
5465
-
5466
-    /**
5467
-     * refresh_entity_map_from_db
5468
-     * Makes sure the model object in the entity map at $id assumes the values
5469
-     * of the database (opposite of EE_base_Class::save())
5470
-     *
5471
-     * @param int|string $id
5472
-     * @return EE_Base_Class
5473
-     * @throws EE_Error
5474
-     */
5475
-    public function refresh_entity_map_from_db($id)
5476
-    {
5477
-        $obj_in_map = $this->get_from_entity_map($id);
5478
-        if ($obj_in_map) {
5479
-            $wpdb_results = $this->_get_all_wpdb_results(
5480
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5481
-            );
5482
-            if ($wpdb_results && is_array($wpdb_results)) {
5483
-                $one_row = reset($wpdb_results);
5484
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5485
-                    $obj_in_map->set_from_db($field_name, $db_value);
5486
-                }
5487
-                // clear the cache of related model objects
5488
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5489
-                    $obj_in_map->clear_cache($relation_name, null, true);
5490
-                }
5491
-            }
5492
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5493
-            return $obj_in_map;
5494
-        }
5495
-        return $this->get_one_by_ID($id);
5496
-    }
5497
-
5498
-
5499
-
5500
-    /**
5501
-     * refresh_entity_map_with
5502
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5503
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5504
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5505
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5506
-     *
5507
-     * @param int|string    $id
5508
-     * @param EE_Base_Class $replacing_model_obj
5509
-     * @return \EE_Base_Class
5510
-     * @throws EE_Error
5511
-     */
5512
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5513
-    {
5514
-        $obj_in_map = $this->get_from_entity_map($id);
5515
-        if ($obj_in_map) {
5516
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5517
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5518
-                    $obj_in_map->set($field_name, $value);
5519
-                }
5520
-                // make the model object in the entity map's cache match the $replacing_model_obj
5521
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5522
-                    $obj_in_map->clear_cache($relation_name, null, true);
5523
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5524
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5525
-                    }
5526
-                }
5527
-            }
5528
-            return $obj_in_map;
5529
-        }
5530
-        $this->add_to_entity_map($replacing_model_obj);
5531
-        return $replacing_model_obj;
5532
-    }
5533
-
5534
-
5535
-
5536
-    /**
5537
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5538
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5539
-     * require_once($this->_getClassName().".class.php");
5540
-     *
5541
-     * @return string
5542
-     */
5543
-    private function _get_class_name()
5544
-    {
5545
-        return "EE_" . $this->get_this_model_name();
5546
-    }
5547
-
5548
-
5549
-
5550
-    /**
5551
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5552
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5553
-     * it would be 'Events'.
5554
-     *
5555
-     * @param int $quantity
5556
-     * @return string
5557
-     */
5558
-    public function item_name($quantity = 1)
5559
-    {
5560
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5561
-    }
5562
-
5563
-
5564
-
5565
-    /**
5566
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5567
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5568
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5569
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5570
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5571
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5572
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5573
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5574
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5575
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5576
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5577
-     *        return $previousReturnValue.$returnString;
5578
-     * }
5579
-     * require('EEM_Answer.model.php');
5580
-     * $answer=EEM_Answer::instance();
5581
-     * echo $answer->my_callback('monkeys',100);
5582
-     * //will output "you called my_callback! and passed args:monkeys,100"
5583
-     *
5584
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5585
-     * @param array  $args       array of original arguments passed to the function
5586
-     * @throws EE_Error
5587
-     * @return mixed whatever the plugin which calls add_filter decides
5588
-     */
5589
-    public function __call($methodName, $args)
5590
-    {
5591
-        $className = get_class($this);
5592
-        $tagName = "FHEE__{$className}__{$methodName}";
5593
-        if (! has_filter($tagName)) {
5594
-            throw new EE_Error(
5595
-                sprintf(
5596
-                    __(
5597
-                        '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 );',
5598
-                        'event_espresso'
5599
-                    ),
5600
-                    $methodName,
5601
-                    $className,
5602
-                    $tagName,
5603
-                    '<br />'
5604
-                )
5605
-            );
5606
-        }
5607
-        return apply_filters($tagName, null, $this, $args);
5608
-    }
5609
-
5610
-
5611
-
5612
-    /**
5613
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5614
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5615
-     *
5616
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5617
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5618
-     *                                                       the object's class name
5619
-     *                                                       or object's ID
5620
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5621
-     *                                                       exists in the database. If it does not, we add it
5622
-     * @throws EE_Error
5623
-     * @return EE_Base_Class
5624
-     */
5625
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5626
-    {
5627
-        $className = $this->_get_class_name();
5628
-        if ($base_class_obj_or_id instanceof $className) {
5629
-            $model_object = $base_class_obj_or_id;
5630
-        } else {
5631
-            $primary_key_field = $this->get_primary_key_field();
5632
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5633
-                && (
5634
-                    is_int($base_class_obj_or_id)
5635
-                    || is_string($base_class_obj_or_id)
5636
-                )
5637
-            ) {
5638
-                // assume it's an ID.
5639
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5640
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5641
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5642
-                && is_string($base_class_obj_or_id)
5643
-            ) {
5644
-                // assume its a string representation of the object
5645
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5646
-            } else {
5647
-                throw new EE_Error(
5648
-                    sprintf(
5649
-                        __(
5650
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5651
-                            'event_espresso'
5652
-                        ),
5653
-                        $base_class_obj_or_id,
5654
-                        $this->_get_class_name(),
5655
-                        print_r($base_class_obj_or_id, true)
5656
-                    )
5657
-                );
5658
-            }
5659
-        }
5660
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5661
-            $model_object->save();
5662
-        }
5663
-        return $model_object;
5664
-    }
5665
-
5666
-
5667
-
5668
-    /**
5669
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5670
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5671
-     * returns it ID.
5672
-     *
5673
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5674
-     * @return int|string depending on the type of this model object's ID
5675
-     * @throws EE_Error
5676
-     */
5677
-    public function ensure_is_ID($base_class_obj_or_id)
5678
-    {
5679
-        $className = $this->_get_class_name();
5680
-        if ($base_class_obj_or_id instanceof $className) {
5681
-            /** @var $base_class_obj_or_id EE_Base_Class */
5682
-            $id = $base_class_obj_or_id->ID();
5683
-        } elseif (is_int($base_class_obj_or_id)) {
5684
-            // assume it's an ID
5685
-            $id = $base_class_obj_or_id;
5686
-        } elseif (is_string($base_class_obj_or_id)) {
5687
-            // assume its a string representation of the object
5688
-            $id = $base_class_obj_or_id;
5689
-        } else {
5690
-            throw new EE_Error(sprintf(
5691
-                __(
5692
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5693
-                    'event_espresso'
5694
-                ),
5695
-                $base_class_obj_or_id,
5696
-                $this->_get_class_name(),
5697
-                print_r($base_class_obj_or_id, true)
5698
-            ));
5699
-        }
5700
-        return $id;
5701
-    }
5702
-
5703
-
5704
-
5705
-    /**
5706
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5707
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5708
-     * been sanitized and converted into the appropriate domain.
5709
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5710
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5711
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5712
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5713
-     * $EVT = EEM_Event::instance(); $old_setting =
5714
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5715
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5716
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5717
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5718
-     *
5719
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5720
-     * @return void
5721
-     */
5722
-    public function assume_values_already_prepared_by_model_object(
5723
-        $values_already_prepared = self::not_prepared_by_model_object
5724
-    ) {
5725
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5726
-    }
5727
-
5728
-
5729
-
5730
-    /**
5731
-     * Read comments for assume_values_already_prepared_by_model_object()
5732
-     *
5733
-     * @return int
5734
-     */
5735
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5736
-    {
5737
-        return $this->_values_already_prepared_by_model_object;
5738
-    }
5739
-
5740
-
5741
-
5742
-    /**
5743
-     * Gets all the indexes on this model
5744
-     *
5745
-     * @return EE_Index[]
5746
-     */
5747
-    public function indexes()
5748
-    {
5749
-        return $this->_indexes;
5750
-    }
5751
-
5752
-
5753
-
5754
-    /**
5755
-     * Gets all the Unique Indexes on this model
5756
-     *
5757
-     * @return EE_Unique_Index[]
5758
-     */
5759
-    public function unique_indexes()
5760
-    {
5761
-        $unique_indexes = array();
5762
-        foreach ($this->_indexes as $name => $index) {
5763
-            if ($index instanceof EE_Unique_Index) {
5764
-                $unique_indexes [ $name ] = $index;
5765
-            }
5766
-        }
5767
-        return $unique_indexes;
5768
-    }
5769
-
5770
-
5771
-
5772
-    /**
5773
-     * Gets all the fields which, when combined, make the primary key.
5774
-     * This is usually just an array with 1 element (the primary key), but in cases
5775
-     * where there is no primary key, it's a combination of fields as defined
5776
-     * on a primary index
5777
-     *
5778
-     * @return EE_Model_Field_Base[] indexed by the field's name
5779
-     * @throws EE_Error
5780
-     */
5781
-    public function get_combined_primary_key_fields()
5782
-    {
5783
-        foreach ($this->indexes() as $index) {
5784
-            if ($index instanceof EE_Primary_Key_Index) {
5785
-                return $index->fields();
5786
-            }
5787
-        }
5788
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5789
-    }
5790
-
5791
-
5792
-
5793
-    /**
5794
-     * Used to build a primary key string (when the model has no primary key),
5795
-     * which can be used a unique string to identify this model object.
5796
-     *
5797
-     * @param array $fields_n_values keys are field names, values are their values.
5798
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5799
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5800
-     *                               before passing it to this function (that will convert it from columns-n-values
5801
-     *                               to field-names-n-values).
5802
-     * @return string
5803
-     * @throws EE_Error
5804
-     */
5805
-    public function get_index_primary_key_string($fields_n_values)
5806
-    {
5807
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5808
-            $fields_n_values,
5809
-            $this->get_combined_primary_key_fields()
5810
-        );
5811
-        return http_build_query($cols_n_values_for_primary_key_index);
5812
-    }
5813
-
5814
-
5815
-
5816
-    /**
5817
-     * Gets the field values from the primary key string
5818
-     *
5819
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5820
-     * @param string $index_primary_key_string
5821
-     * @return null|array
5822
-     * @throws EE_Error
5823
-     */
5824
-    public function parse_index_primary_key_string($index_primary_key_string)
5825
-    {
5826
-        $key_fields = $this->get_combined_primary_key_fields();
5827
-        // check all of them are in the $id
5828
-        $key_vals_in_combined_pk = array();
5829
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5830
-        foreach ($key_fields as $key_field_name => $field_obj) {
5831
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5832
-                return null;
5833
-            }
5834
-        }
5835
-        return $key_vals_in_combined_pk;
5836
-    }
5837
-
5838
-
5839
-
5840
-    /**
5841
-     * verifies that an array of key-value pairs for model fields has a key
5842
-     * for each field comprising the primary key index
5843
-     *
5844
-     * @param array $key_vals
5845
-     * @return boolean
5846
-     * @throws EE_Error
5847
-     */
5848
-    public function has_all_combined_primary_key_fields($key_vals)
5849
-    {
5850
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5851
-        foreach ($keys_it_should_have as $key) {
5852
-            if (! isset($key_vals[ $key ])) {
5853
-                return false;
5854
-            }
5855
-        }
5856
-        return true;
5857
-    }
5858
-
5859
-
5860
-
5861
-    /**
5862
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5863
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5864
-     *
5865
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5866
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5867
-     * @throws EE_Error
5868
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5869
-     *                                                              indexed)
5870
-     */
5871
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5872
-    {
5873
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5874
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5875
-        } elseif (is_array($model_object_or_attributes_array)) {
5876
-            $attributes_array = $model_object_or_attributes_array;
5877
-        } else {
5878
-            throw new EE_Error(sprintf(__(
5879
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5880
-                "event_espresso"
5881
-            ), $model_object_or_attributes_array));
5882
-        }
5883
-        // even copies obviously won't have the same ID, so remove the primary key
5884
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5885
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5886
-            unset($attributes_array[ $this->primary_key_name() ]);
5887
-        }
5888
-        if (isset($query_params[0])) {
5889
-            $query_params[0] = array_merge($attributes_array, $query_params);
5890
-        } else {
5891
-            $query_params[0] = $attributes_array;
5892
-        }
5893
-        return $this->get_all($query_params);
5894
-    }
5895
-
5896
-
5897
-
5898
-    /**
5899
-     * Gets the first copy we find. See get_all_copies for more details
5900
-     *
5901
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5902
-     * @param array $query_params
5903
-     * @return EE_Base_Class
5904
-     * @throws EE_Error
5905
-     */
5906
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5907
-    {
5908
-        if (! is_array($query_params)) {
5909
-            EE_Error::doing_it_wrong(
5910
-                'EEM_Base::get_one_copy',
5911
-                sprintf(
5912
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5913
-                    gettype($query_params)
5914
-                ),
5915
-                '4.6.0'
5916
-            );
5917
-            $query_params = array();
5918
-        }
5919
-        $query_params['limit'] = 1;
5920
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5921
-        if (is_array($copies)) {
5922
-            return array_shift($copies);
5923
-        }
5924
-        return null;
5925
-    }
5926
-
5927
-
5928
-
5929
-    /**
5930
-     * Updates the item with the specified id. Ignores default query parameters because
5931
-     * we have specified the ID, and its assumed we KNOW what we're doing
5932
-     *
5933
-     * @param array      $fields_n_values keys are field names, values are their new values
5934
-     * @param int|string $id              the value of the primary key to update
5935
-     * @return int number of rows updated
5936
-     * @throws EE_Error
5937
-     */
5938
-    public function update_by_ID($fields_n_values, $id)
5939
-    {
5940
-        $query_params = array(
5941
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5942
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5943
-        );
5944
-        return $this->update($fields_n_values, $query_params);
5945
-    }
5946
-
5947
-
5948
-
5949
-    /**
5950
-     * Changes an operator which was supplied to the models into one usable in SQL
5951
-     *
5952
-     * @param string $operator_supplied
5953
-     * @return string an operator which can be used in SQL
5954
-     * @throws EE_Error
5955
-     */
5956
-    private function _prepare_operator_for_sql($operator_supplied)
5957
-    {
5958
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5959
-            : null;
5960
-        if ($sql_operator) {
5961
-            return $sql_operator;
5962
-        }
5963
-        throw new EE_Error(
5964
-            sprintf(
5965
-                __(
5966
-                    "The operator '%s' is not in the list of valid operators: %s",
5967
-                    "event_espresso"
5968
-                ),
5969
-                $operator_supplied,
5970
-                implode(",", array_keys($this->_valid_operators))
5971
-            )
5972
-        );
5973
-    }
5974
-
5975
-
5976
-
5977
-    /**
5978
-     * Gets the valid operators
5979
-     * @return array keys are accepted strings, values are the SQL they are converted to
5980
-     */
5981
-    public function valid_operators()
5982
-    {
5983
-        return $this->_valid_operators;
5984
-    }
5985
-
5986
-
5987
-
5988
-    /**
5989
-     * Gets the between-style operators (take 2 arguments).
5990
-     * @return array keys are accepted strings, values are the SQL they are converted to
5991
-     */
5992
-    public function valid_between_style_operators()
5993
-    {
5994
-        return array_intersect(
5995
-            $this->valid_operators(),
5996
-            $this->_between_style_operators
5997
-        );
5998
-    }
5999
-
6000
-    /**
6001
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6002
-     * @return array keys are accepted strings, values are the SQL they are converted to
6003
-     */
6004
-    public function valid_like_style_operators()
6005
-    {
6006
-        return array_intersect(
6007
-            $this->valid_operators(),
6008
-            $this->_like_style_operators
6009
-        );
6010
-    }
6011
-
6012
-    /**
6013
-     * Gets the "in"-style operators
6014
-     * @return array keys are accepted strings, values are the SQL they are converted to
6015
-     */
6016
-    public function valid_in_style_operators()
6017
-    {
6018
-        return array_intersect(
6019
-            $this->valid_operators(),
6020
-            $this->_in_style_operators
6021
-        );
6022
-    }
6023
-
6024
-    /**
6025
-     * Gets the "null"-style operators (accept no arguments)
6026
-     * @return array keys are accepted strings, values are the SQL they are converted to
6027
-     */
6028
-    public function valid_null_style_operators()
6029
-    {
6030
-        return array_intersect(
6031
-            $this->valid_operators(),
6032
-            $this->_null_style_operators
6033
-        );
6034
-    }
6035
-
6036
-    /**
6037
-     * Gets an array where keys are the primary keys and values are their 'names'
6038
-     * (as determined by the model object's name() function, which is often overridden)
6039
-     *
6040
-     * @param array $query_params like get_all's
6041
-     * @return string[]
6042
-     * @throws EE_Error
6043
-     */
6044
-    public function get_all_names($query_params = array())
6045
-    {
6046
-        $objs = $this->get_all($query_params);
6047
-        $names = array();
6048
-        foreach ($objs as $obj) {
6049
-            $names[ $obj->ID() ] = $obj->name();
6050
-        }
6051
-        return $names;
6052
-    }
6053
-
6054
-
6055
-
6056
-    /**
6057
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6058
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6059
-     * this is duplicated effort and reduces efficiency) you would be better to use
6060
-     * array_keys() on $model_objects.
6061
-     *
6062
-     * @param \EE_Base_Class[] $model_objects
6063
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6064
-     *                                               in the returned array
6065
-     * @return array
6066
-     * @throws EE_Error
6067
-     */
6068
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6069
-    {
6070
-        if (! $this->has_primary_key_field()) {
6071
-            if (WP_DEBUG) {
6072
-                EE_Error::add_error(
6073
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6074
-                    __FILE__,
6075
-                    __FUNCTION__,
6076
-                    __LINE__
6077
-                );
6078
-            }
6079
-        }
6080
-        $IDs = array();
6081
-        foreach ($model_objects as $model_object) {
6082
-            $id = $model_object->ID();
6083
-            if (! $id) {
6084
-                if ($filter_out_empty_ids) {
6085
-                    continue;
6086
-                }
6087
-                if (WP_DEBUG) {
6088
-                    EE_Error::add_error(
6089
-                        __(
6090
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6091
-                            'event_espresso'
6092
-                        ),
6093
-                        __FILE__,
6094
-                        __FUNCTION__,
6095
-                        __LINE__
6096
-                    );
6097
-                }
6098
-            }
6099
-            $IDs[] = $id;
6100
-        }
6101
-        return $IDs;
6102
-    }
6103
-
6104
-
6105
-
6106
-    /**
6107
-     * Returns the string used in capabilities relating to this model. If there
6108
-     * are no capabilities that relate to this model returns false
6109
-     *
6110
-     * @return string|false
6111
-     */
6112
-    public function cap_slug()
6113
-    {
6114
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6115
-    }
6116
-
6117
-
6118
-
6119
-    /**
6120
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6121
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6122
-     * only returns the cap restrictions array in that context (ie, the array
6123
-     * at that key)
6124
-     *
6125
-     * @param string $context
6126
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6127
-     * @throws EE_Error
6128
-     */
6129
-    public function cap_restrictions($context = EEM_Base::caps_read)
6130
-    {
6131
-        EEM_Base::verify_is_valid_cap_context($context);
6132
-        // check if we ought to run the restriction generator first
6133
-        if (isset($this->_cap_restriction_generators[ $context ])
6134
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6135
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6136
-        ) {
6137
-            $this->_cap_restrictions[ $context ] = array_merge(
6138
-                $this->_cap_restrictions[ $context ],
6139
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6140
-            );
6141
-        }
6142
-        // and make sure we've finalized the construction of each restriction
6143
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6144
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6145
-                $where_conditions_obj->_finalize_construct($this);
6146
-            }
6147
-        }
6148
-        return $this->_cap_restrictions[ $context ];
6149
-    }
6150
-
6151
-
6152
-
6153
-    /**
6154
-     * Indicating whether or not this model thinks its a wp core model
6155
-     *
6156
-     * @return boolean
6157
-     */
6158
-    public function is_wp_core_model()
6159
-    {
6160
-        return $this->_wp_core_model;
6161
-    }
6162
-
6163
-
6164
-
6165
-    /**
6166
-     * Gets all the caps that are missing which impose a restriction on
6167
-     * queries made in this context
6168
-     *
6169
-     * @param string $context one of EEM_Base::caps_ constants
6170
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6171
-     * @throws EE_Error
6172
-     */
6173
-    public function caps_missing($context = EEM_Base::caps_read)
6174
-    {
6175
-        $missing_caps = array();
6176
-        $cap_restrictions = $this->cap_restrictions($context);
6177
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6178
-            if (! EE_Capabilities::instance()
6179
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6180
-            ) {
6181
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6182
-            }
6183
-        }
6184
-        return $missing_caps;
6185
-    }
6186
-
6187
-
6188
-
6189
-    /**
6190
-     * Gets the mapping from capability contexts to action strings used in capability names
6191
-     *
6192
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6193
-     * one of 'read', 'edit', or 'delete'
6194
-     */
6195
-    public function cap_contexts_to_cap_action_map()
6196
-    {
6197
-        return apply_filters(
6198
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6199
-            $this->_cap_contexts_to_cap_action_map,
6200
-            $this
6201
-        );
6202
-    }
6203
-
6204
-
6205
-
6206
-    /**
6207
-     * Gets the action string for the specified capability context
6208
-     *
6209
-     * @param string $context
6210
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6211
-     * @throws EE_Error
6212
-     */
6213
-    public function cap_action_for_context($context)
6214
-    {
6215
-        $mapping = $this->cap_contexts_to_cap_action_map();
6216
-        if (isset($mapping[ $context ])) {
6217
-            return $mapping[ $context ];
6218
-        }
6219
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6220
-            return $action;
6221
-        }
6222
-        throw new EE_Error(
6223
-            sprintf(
6224
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6225
-                $context,
6226
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6227
-            )
6228
-        );
6229
-    }
6230
-
6231
-
6232
-
6233
-    /**
6234
-     * Returns all the capability contexts which are valid when querying models
6235
-     *
6236
-     * @return array
6237
-     */
6238
-    public static function valid_cap_contexts()
6239
-    {
6240
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6241
-            self::caps_read,
6242
-            self::caps_read_admin,
6243
-            self::caps_edit,
6244
-            self::caps_delete,
6245
-        ));
6246
-    }
6247
-
6248
-
6249
-
6250
-    /**
6251
-     * Returns all valid options for 'default_where_conditions'
6252
-     *
6253
-     * @return array
6254
-     */
6255
-    public static function valid_default_where_conditions()
6256
-    {
6257
-        return array(
6258
-            EEM_Base::default_where_conditions_all,
6259
-            EEM_Base::default_where_conditions_this_only,
6260
-            EEM_Base::default_where_conditions_others_only,
6261
-            EEM_Base::default_where_conditions_minimum_all,
6262
-            EEM_Base::default_where_conditions_minimum_others,
6263
-            EEM_Base::default_where_conditions_none
6264
-        );
6265
-    }
6266
-
6267
-    // public static function default_where_conditions_full
6268
-    /**
6269
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6270
-     *
6271
-     * @param string $context
6272
-     * @return bool
6273
-     * @throws EE_Error
6274
-     */
6275
-    public static function verify_is_valid_cap_context($context)
6276
-    {
6277
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6278
-        if (in_array($context, $valid_cap_contexts)) {
6279
-            return true;
6280
-        }
6281
-        throw new EE_Error(
6282
-            sprintf(
6283
-                __(
6284
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6285
-                    'event_espresso'
6286
-                ),
6287
-                $context,
6288
-                'EEM_Base',
6289
-                implode(',', $valid_cap_contexts)
6290
-            )
6291
-        );
6292
-    }
6293
-
6294
-
6295
-
6296
-    /**
6297
-     * Clears all the models field caches. This is only useful when a sub-class
6298
-     * might have added a field or something and these caches might be invalidated
6299
-     */
6300
-    protected function _invalidate_field_caches()
6301
-    {
6302
-        $this->_cache_foreign_key_to_fields = array();
6303
-        $this->_cached_fields = null;
6304
-        $this->_cached_fields_non_db_only = null;
6305
-    }
6306
-
6307
-
6308
-
6309
-    /**
6310
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6311
-     * (eg "and", "or", "not").
6312
-     *
6313
-     * @return array
6314
-     */
6315
-    public function logic_query_param_keys()
6316
-    {
6317
-        return $this->_logic_query_param_keys;
6318
-    }
6319
-
6320
-
6321
-
6322
-    /**
6323
-     * Determines whether or not the where query param array key is for a logic query param.
6324
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6325
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6326
-     *
6327
-     * @param $query_param_key
6328
-     * @return bool
6329
-     */
6330
-    public function is_logic_query_param_key($query_param_key)
6331
-    {
6332
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6333
-            if ($query_param_key === $logic_query_param_key
6334
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6335
-            ) {
6336
-                return true;
6337
-            }
6338
-        }
6339
-        return false;
6340
-    }
6341
-
6342
-    /**
6343
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6344
-     * @since 4.9.74.p
6345
-     * @return boolean
6346
-     */
6347
-    public function hasPassword()
6348
-    {
6349
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6350
-        if ($this->has_password_field === null) {
6351
-            $password_field = $this->getPasswordField();
6352
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6353
-        }
6354
-        return $this->has_password_field;
6355
-    }
6356
-
6357
-    /**
6358
-     * Returns the password field on this model, if there is one
6359
-     * @since 4.9.74.p
6360
-     * @return EE_Password_Field|null
6361
-     */
6362
-    public function getPasswordField()
6363
-    {
6364
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6365
-        // there's no need to search for it. If we don't know yet, then find out
6366
-        if ($this->has_password_field === null && $this->password_field === null) {
6367
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6368
-        }
6369
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6370
-        return $this->password_field;
6371
-    }
6372
-
6373
-
6374
-    /**
6375
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6376
-     * @since 4.9.74.p
6377
-     * @return EE_Model_Field_Base[]
6378
-     * @throws EE_Error
6379
-     */
6380
-    public function getPasswordProtectedFields()
6381
-    {
6382
-        $password_field = $this->getPasswordField();
6383
-        $fields = array();
6384
-        if ($password_field instanceof EE_Password_Field) {
6385
-            $field_names = $password_field->protectedFields();
6386
-            foreach ($field_names as $field_name) {
6387
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6388
-            }
6389
-        }
6390
-        return $fields;
6391
-    }
6392
-
6393
-
6394
-    /**
6395
-     * Checks if the current user can perform the requested action on this model
6396
-     * @since 4.9.74.p
6397
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6398
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6399
-     * @return bool
6400
-     * @throws EE_Error
6401
-     * @throws InvalidArgumentException
6402
-     * @throws InvalidDataTypeException
6403
-     * @throws InvalidInterfaceException
6404
-     * @throws ReflectionException
6405
-     * @throws UnexpectedEntityException
6406
-     */
6407
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6408
-    {
6409
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6410
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6411
-        }
6412
-        if (!is_array($model_obj_or_fields_n_values)) {
6413
-            throw new UnexpectedEntityException(
6414
-                $model_obj_or_fields_n_values,
6415
-                'EE_Base_Class',
6416
-                sprintf(
6417
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6418
-                    __FUNCTION__
6419
-                )
6420
-            );
6421
-        }
6422
-        return $this->exists(
6423
-            $this->alter_query_params_to_restrict_by_ID(
6424
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6425
-                array(
6426
-                    'default_where_conditions' => 'none',
6427
-                    'caps'                     => $cap_to_check,
6428
-                )
6429
-            )
6430
-        );
6431
-    }
6432
-
6433
-    /**
6434
-     * Returns the query param where conditions key to the password affecting this model.
6435
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6436
-     * @since 4.9.74.p
6437
-     * @return null|string
6438
-     * @throws EE_Error
6439
-     * @throws InvalidArgumentException
6440
-     * @throws InvalidDataTypeException
6441
-     * @throws InvalidInterfaceException
6442
-     * @throws ModelConfigurationException
6443
-     * @throws ReflectionException
6444
-     */
6445
-    public function modelChainAndPassword()
6446
-    {
6447
-        if ($this->model_chain_to_password === null) {
6448
-            throw new ModelConfigurationException(
6449
-                $this,
6450
-                esc_html_x(
6451
-                // @codingStandardsIgnoreStart
6452
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6453
-                    // @codingStandardsIgnoreEnd
6454
-                    '1: model name',
6455
-                    'event_espresso'
6456
-                )
6457
-            );
6458
-        }
6459
-        if ($this->model_chain_to_password === '') {
6460
-            $model_with_password = $this;
6461
-        } else {
6462
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6463
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6464
-            } else {
6465
-                $last_model_in_chain = $this->model_chain_to_password;
6466
-            }
6467
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6468
-        }
6469
-
6470
-        $password_field = $model_with_password->getPasswordField();
6471
-        if ($password_field instanceof EE_Password_Field) {
6472
-            $password_field_name = $password_field->get_name();
6473
-        } else {
6474
-            throw new ModelConfigurationException(
6475
-                $this,
6476
-                sprintf(
6477
-                    esc_html_x(
6478
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6479
-                        '1: model name, 2: special string',
6480
-                        'event_espresso'
6481
-                    ),
6482
-                    $model_with_password->get_this_model_name(),
6483
-                    $this->model_chain_to_password
6484
-                )
6485
-            );
6486
-        }
6487
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6488
-    }
6489
-
6490
-    /**
6491
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6492
-     * or if this model itself has a password affecting access to some of its other fields.
6493
-     * @since 4.9.74.p
6494
-     * @return boolean
6495
-     */
6496
-    public function restrictedByRelatedModelPassword()
6497
-    {
6498
-        return $this->model_chain_to_password !== null;
6499
-    }
3804
+		}
3805
+		return $null_friendly_where_conditions;
3806
+	}
3807
+
3808
+
3809
+
3810
+	/**
3811
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3812
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3813
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3814
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3815
+	 *
3816
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3817
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3818
+	 */
3819
+	private function _get_default_where_conditions($model_relation_path = null)
3820
+	{
3821
+		if ($this->_ignore_where_strategy) {
3822
+			return array();
3823
+		}
3824
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3825
+	}
3826
+
3827
+
3828
+
3829
+	/**
3830
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3831
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3832
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3833
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3834
+	 * Similar to _get_default_where_conditions
3835
+	 *
3836
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3837
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
+	 */
3839
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3840
+	{
3841
+		if ($this->_ignore_where_strategy) {
3842
+			return array();
3843
+		}
3844
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3845
+	}
3846
+
3847
+
3848
+
3849
+	/**
3850
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3851
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3852
+	 *
3853
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3854
+	 * @return string
3855
+	 * @throws EE_Error
3856
+	 */
3857
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3858
+	{
3859
+		$selects = $this->_get_columns_to_select_for_this_model();
3860
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3861
+			$name_of_other_model_included) {
3862
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3863
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3864
+			foreach ($other_model_selects as $key => $value) {
3865
+				$selects[] = $value;
3866
+			}
3867
+		}
3868
+		return implode(", ", $selects);
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3875
+	 * So that's going to be the columns for all the fields on the model
3876
+	 *
3877
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3878
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3879
+	 */
3880
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3881
+	{
3882
+		$fields = $this->field_settings();
3883
+		$selects = array();
3884
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3885
+			$model_relation_chain,
3886
+			$this->get_this_model_name()
3887
+		);
3888
+		foreach ($fields as $field_obj) {
3889
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3890
+						 . $field_obj->get_table_alias()
3891
+						 . "."
3892
+						 . $field_obj->get_table_column()
3893
+						 . " AS '"
3894
+						 . $table_alias_with_model_relation_chain_prefix
3895
+						 . $field_obj->get_table_alias()
3896
+						 . "."
3897
+						 . $field_obj->get_table_column()
3898
+						 . "'";
3899
+		}
3900
+		// make sure we are also getting the PKs of each table
3901
+		$tables = $this->get_tables();
3902
+		if (count($tables) > 1) {
3903
+			foreach ($tables as $table_obj) {
3904
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3905
+									   . $table_obj->get_fully_qualified_pk_column();
3906
+				if (! in_array($qualified_pk_column, $selects)) {
3907
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3908
+				}
3909
+			}
3910
+		}
3911
+		return $selects;
3912
+	}
3913
+
3914
+
3915
+
3916
+	/**
3917
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3918
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3919
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3920
+	 * SQL for joining, and the data types
3921
+	 *
3922
+	 * @param null|string                 $original_query_param
3923
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3924
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3925
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3926
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3927
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3928
+	 *                                                          or 'Registration's
3929
+	 * @param string                      $original_query_param what it originally was (eg
3930
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3931
+	 *                                                          matches $query_param
3932
+	 * @throws EE_Error
3933
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3934
+	 */
3935
+	private function _extract_related_model_info_from_query_param(
3936
+		$query_param,
3937
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3938
+		$query_param_type,
3939
+		$original_query_param = null
3940
+	) {
3941
+		if ($original_query_param === null) {
3942
+			$original_query_param = $query_param;
3943
+		}
3944
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3945
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3946
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3947
+		$allow_fields = in_array(
3948
+			$query_param_type,
3949
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3950
+			true
3951
+		);
3952
+		// check to see if we have a field on this model
3953
+		$this_model_fields = $this->field_settings(true);
3954
+		if (array_key_exists($query_param, $this_model_fields)) {
3955
+			if ($allow_fields) {
3956
+				return;
3957
+			}
3958
+			throw new EE_Error(
3959
+				sprintf(
3960
+					__(
3961
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3962
+						"event_espresso"
3963
+					),
3964
+					$query_param,
3965
+					get_class($this),
3966
+					$query_param_type,
3967
+					$original_query_param
3968
+				)
3969
+			);
3970
+		}
3971
+		// check if this is a special logic query param
3972
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3973
+			if ($allow_logic_query_params) {
3974
+				return;
3975
+			}
3976
+			throw new EE_Error(
3977
+				sprintf(
3978
+					__(
3979
+						'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',
3980
+						'event_espresso'
3981
+					),
3982
+					implode('", "', $this->_logic_query_param_keys),
3983
+					$query_param,
3984
+					get_class($this),
3985
+					'<br />',
3986
+					"\t"
3987
+					. ' $passed_in_query_info = <pre>'
3988
+					. print_r($passed_in_query_info, true)
3989
+					. '</pre>'
3990
+					. "\n\t"
3991
+					. ' $query_param_type = '
3992
+					. $query_param_type
3993
+					. "\n\t"
3994
+					. ' $original_query_param = '
3995
+					. $original_query_param
3996
+				)
3997
+			);
3998
+		}
3999
+		// check if it's a custom selection
4000
+		if ($this->_custom_selections instanceof CustomSelects
4001
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4002
+		) {
4003
+			return;
4004
+		}
4005
+		// check if has a model name at the beginning
4006
+		// and
4007
+		// check if it's a field on a related model
4008
+		if ($this->extractJoinModelFromQueryParams(
4009
+			$passed_in_query_info,
4010
+			$query_param,
4011
+			$original_query_param,
4012
+			$query_param_type
4013
+		)) {
4014
+			return;
4015
+		}
4016
+
4017
+		// ok so $query_param didn't start with a model name
4018
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4019
+		// it's wack, that's what it is
4020
+		throw new EE_Error(
4021
+			sprintf(
4022
+				esc_html__(
4023
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4024
+					"event_espresso"
4025
+				),
4026
+				$query_param,
4027
+				get_class($this),
4028
+				$query_param_type,
4029
+				$original_query_param
4030
+			)
4031
+		);
4032
+	}
4033
+
4034
+
4035
+	/**
4036
+	 * Extracts any possible join model information from the provided possible_join_string.
4037
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4038
+	 * parts that should be added to the query.
4039
+	 *
4040
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4041
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4042
+	 * @param null|string                 $original_query_param
4043
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4044
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4045
+	 * @return bool  returns true if a join was added and false if not.
4046
+	 * @throws EE_Error
4047
+	 */
4048
+	private function extractJoinModelFromQueryParams(
4049
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4050
+		$possible_join_string,
4051
+		$original_query_param,
4052
+		$query_parameter_type
4053
+	) {
4054
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4055
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4056
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4057
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4058
+				if ($possible_join_string === '') {
4059
+					// nothing left to $query_param
4060
+					// we should actually end in a field name, not a model like this!
4061
+					throw new EE_Error(
4062
+						sprintf(
4063
+							esc_html__(
4064
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4065
+								"event_espresso"
4066
+							),
4067
+							$possible_join_string,
4068
+							$query_parameter_type,
4069
+							get_class($this),
4070
+							$valid_related_model_name
4071
+						)
4072
+					);
4073
+				}
4074
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4075
+				$related_model_obj->_extract_related_model_info_from_query_param(
4076
+					$possible_join_string,
4077
+					$query_info_carrier,
4078
+					$query_parameter_type,
4079
+					$original_query_param
4080
+				);
4081
+				return true;
4082
+			}
4083
+			if ($possible_join_string === $valid_related_model_name) {
4084
+				$this->_add_join_to_model(
4085
+					$valid_related_model_name,
4086
+					$query_info_carrier,
4087
+					$original_query_param
4088
+				);
4089
+				return true;
4090
+			}
4091
+		}
4092
+		return false;
4093
+	}
4094
+
4095
+
4096
+	/**
4097
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4098
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4099
+	 * @throws EE_Error
4100
+	 */
4101
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4102
+	{
4103
+		if ($this->_custom_selections instanceof CustomSelects
4104
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4105
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4106
+			)
4107
+		) {
4108
+			$original_selects = $this->_custom_selections->originalSelects();
4109
+			foreach ($original_selects as $alias => $select_configuration) {
4110
+				$this->extractJoinModelFromQueryParams(
4111
+					$query_info_carrier,
4112
+					$select_configuration[0],
4113
+					$select_configuration[0],
4114
+					'custom_selects'
4115
+				);
4116
+			}
4117
+		}
4118
+	}
4119
+
4120
+
4121
+
4122
+	/**
4123
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4124
+	 * and store it on $passed_in_query_info
4125
+	 *
4126
+	 * @param string                      $model_name
4127
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4128
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4129
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4130
+	 *                                                          and are adding a join to 'Payment' with the original
4131
+	 *                                                          query param key
4132
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4133
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4134
+	 *                                                          Payment wants to add default query params so that it
4135
+	 *                                                          will know what models to prepend onto its default query
4136
+	 *                                                          params or in case it wants to rename tables (in case
4137
+	 *                                                          there are multiple joins to the same table)
4138
+	 * @return void
4139
+	 * @throws EE_Error
4140
+	 */
4141
+	private function _add_join_to_model(
4142
+		$model_name,
4143
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4144
+		$original_query_param
4145
+	) {
4146
+		$relation_obj = $this->related_settings_for($model_name);
4147
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4148
+		// check if the relation is HABTM, because then we're essentially doing two joins
4149
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4150
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4151
+			$join_model_obj = $relation_obj->get_join_model();
4152
+			// replace the model specified with the join model for this relation chain, whi
4153
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4154
+				$model_name,
4155
+				$join_model_obj->get_this_model_name(),
4156
+				$model_relation_chain
4157
+			);
4158
+			$passed_in_query_info->merge(
4159
+				new EE_Model_Query_Info_Carrier(
4160
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4161
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4162
+				)
4163
+			);
4164
+		}
4165
+		// now just join to the other table pointed to by the relation object, and add its data types
4166
+		$passed_in_query_info->merge(
4167
+			new EE_Model_Query_Info_Carrier(
4168
+				array($model_relation_chain => $model_name),
4169
+				$relation_obj->get_join_statement($model_relation_chain)
4170
+			)
4171
+		);
4172
+	}
4173
+
4174
+
4175
+
4176
+	/**
4177
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4178
+	 *
4179
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4180
+	 * @return string of SQL
4181
+	 * @throws EE_Error
4182
+	 */
4183
+	private function _construct_where_clause($where_params)
4184
+	{
4185
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4186
+		if ($SQL) {
4187
+			return " WHERE " . $SQL;
4188
+		}
4189
+		return '';
4190
+	}
4191
+
4192
+
4193
+
4194
+	/**
4195
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4196
+	 * and should be passed HAVING parameters, not WHERE parameters
4197
+	 *
4198
+	 * @param array $having_params
4199
+	 * @return string
4200
+	 * @throws EE_Error
4201
+	 */
4202
+	private function _construct_having_clause($having_params)
4203
+	{
4204
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4205
+		if ($SQL) {
4206
+			return " HAVING " . $SQL;
4207
+		}
4208
+		return '';
4209
+	}
4210
+
4211
+
4212
+	/**
4213
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4214
+	 * Event_Meta.meta_value = 'foo'))"
4215
+	 *
4216
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4217
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4218
+	 * @throws EE_Error
4219
+	 * @return string of SQL
4220
+	 */
4221
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4222
+	{
4223
+		$where_clauses = array();
4224
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4225
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4226
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4227
+				switch ($query_param) {
4228
+					case 'not':
4229
+					case 'NOT':
4230
+						$where_clauses[] = "! ("
4231
+										   . $this->_construct_condition_clause_recursive(
4232
+											   $op_and_value_or_sub_condition,
4233
+											   $glue
4234
+										   )
4235
+										   . ")";
4236
+						break;
4237
+					case 'and':
4238
+					case 'AND':
4239
+						$where_clauses[] = " ("
4240
+										   . $this->_construct_condition_clause_recursive(
4241
+											   $op_and_value_or_sub_condition,
4242
+											   ' AND '
4243
+										   )
4244
+										   . ")";
4245
+						break;
4246
+					case 'or':
4247
+					case 'OR':
4248
+						$where_clauses[] = " ("
4249
+										   . $this->_construct_condition_clause_recursive(
4250
+											   $op_and_value_or_sub_condition,
4251
+											   ' OR '
4252
+										   )
4253
+										   . ")";
4254
+						break;
4255
+				}
4256
+			} else {
4257
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4258
+				// if it's not a normal field, maybe it's a custom selection?
4259
+				if (! $field_obj) {
4260
+					if ($this->_custom_selections instanceof CustomSelects) {
4261
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4262
+					} else {
4263
+						throw new EE_Error(sprintf(__(
4264
+							"%s is neither a valid model field name, nor a custom selection",
4265
+							"event_espresso"
4266
+						), $query_param));
4267
+					}
4268
+				}
4269
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4270
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4271
+			}
4272
+		}
4273
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4274
+	}
4275
+
4276
+
4277
+
4278
+	/**
4279
+	 * Takes the input parameter and extract the table name (alias) and column name
4280
+	 *
4281
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4282
+	 * @throws EE_Error
4283
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4284
+	 */
4285
+	private function _deduce_column_name_from_query_param($query_param)
4286
+	{
4287
+		$field = $this->_deduce_field_from_query_param($query_param);
4288
+		if ($field) {
4289
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4290
+				$field->get_model_name(),
4291
+				$query_param
4292
+			);
4293
+			return $table_alias_prefix . $field->get_qualified_column();
4294
+		}
4295
+		if ($this->_custom_selections instanceof CustomSelects
4296
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4297
+		) {
4298
+			// maybe it's custom selection item?
4299
+			// if so, just use it as the "column name"
4300
+			return $query_param;
4301
+		}
4302
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4303
+			? implode(',', $this->_custom_selections->columnAliases())
4304
+			: '';
4305
+		throw new EE_Error(
4306
+			sprintf(
4307
+				__(
4308
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4309
+					"event_espresso"
4310
+				),
4311
+				$query_param,
4312
+				$custom_select_aliases
4313
+			)
4314
+		);
4315
+	}
4316
+
4317
+
4318
+
4319
+	/**
4320
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4321
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4322
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4323
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4324
+	 *
4325
+	 * @param string $condition_query_param_key
4326
+	 * @return string
4327
+	 */
4328
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4329
+	{
4330
+		$pos_of_star = strpos($condition_query_param_key, '*');
4331
+		if ($pos_of_star === false) {
4332
+			return $condition_query_param_key;
4333
+		}
4334
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4335
+		return $condition_query_param_sans_star;
4336
+	}
4337
+
4338
+
4339
+
4340
+	/**
4341
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4342
+	 *
4343
+	 * @param                            mixed      array | string    $op_and_value
4344
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4345
+	 * @throws EE_Error
4346
+	 * @return string
4347
+	 */
4348
+	private function _construct_op_and_value($op_and_value, $field_obj)
4349
+	{
4350
+		if (is_array($op_and_value)) {
4351
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4352
+			if (! $operator) {
4353
+				$php_array_like_string = array();
4354
+				foreach ($op_and_value as $key => $value) {
4355
+					$php_array_like_string[] = "$key=>$value";
4356
+				}
4357
+				throw new EE_Error(
4358
+					sprintf(
4359
+						__(
4360
+							"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))",
4361
+							"event_espresso"
4362
+						),
4363
+						implode(",", $php_array_like_string)
4364
+					)
4365
+				);
4366
+			}
4367
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4368
+		} else {
4369
+			$operator = '=';
4370
+			$value = $op_and_value;
4371
+		}
4372
+		// check to see if the value is actually another field
4373
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4374
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4375
+		}
4376
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4377
+			// in this case, the value should be an array, or at least a comma-separated list
4378
+			// it will need to handle a little differently
4379
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4380
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4381
+			return $operator . SP . $cleaned_value;
4382
+		}
4383
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4384
+			// the value should be an array with count of two.
4385
+			if (count($value) !== 2) {
4386
+				throw new EE_Error(
4387
+					sprintf(
4388
+						__(
4389
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4390
+							'event_espresso'
4391
+						),
4392
+						"BETWEEN"
4393
+					)
4394
+				);
4395
+			}
4396
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4397
+			return $operator . SP . $cleaned_value;
4398
+		}
4399
+		if (in_array($operator, $this->valid_null_style_operators())) {
4400
+			if ($value !== null) {
4401
+				throw new EE_Error(
4402
+					sprintf(
4403
+						__(
4404
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4405
+							"event_espresso"
4406
+						),
4407
+						$value,
4408
+						$operator
4409
+					)
4410
+				);
4411
+			}
4412
+			return $operator;
4413
+		}
4414
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4415
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4416
+			// remove other junk. So just treat it as a string.
4417
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4418
+		}
4419
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4421
+		}
4422
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4423
+			throw new EE_Error(
4424
+				sprintf(
4425
+					__(
4426
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4427
+						'event_espresso'
4428
+					),
4429
+					$operator,
4430
+					$operator
4431
+				)
4432
+			);
4433
+		}
4434
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4435
+			throw new EE_Error(
4436
+				sprintf(
4437
+					__(
4438
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4439
+						'event_espresso'
4440
+					),
4441
+					$operator,
4442
+					$operator
4443
+				)
4444
+			);
4445
+		}
4446
+		throw new EE_Error(
4447
+			sprintf(
4448
+				__(
4449
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4450
+					"event_espresso"
4451
+				),
4452
+				http_build_query($op_and_value)
4453
+			)
4454
+		);
4455
+	}
4456
+
4457
+
4458
+
4459
+	/**
4460
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4461
+	 *
4462
+	 * @param array                      $values
4463
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4464
+	 *                                              '%s'
4465
+	 * @return string
4466
+	 * @throws EE_Error
4467
+	 */
4468
+	public function _construct_between_value($values, $field_obj)
4469
+	{
4470
+		$cleaned_values = array();
4471
+		foreach ($values as $value) {
4472
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4473
+		}
4474
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4475
+	}
4476
+
4477
+
4478
+
4479
+	/**
4480
+	 * Takes an array or a comma-separated list of $values and cleans them
4481
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4482
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4483
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4484
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4485
+	 *
4486
+	 * @param mixed                      $values    array or comma-separated string
4487
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4488
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4489
+	 * @throws EE_Error
4490
+	 */
4491
+	public function _construct_in_value($values, $field_obj)
4492
+	{
4493
+		// check if the value is a CSV list
4494
+		if (is_string($values)) {
4495
+			// in which case, turn it into an array
4496
+			$values = explode(",", $values);
4497
+		}
4498
+		$cleaned_values = array();
4499
+		foreach ($values as $value) {
4500
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4501
+		}
4502
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4503
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4504
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4505
+		if (empty($cleaned_values)) {
4506
+			$all_fields = $this->field_settings();
4507
+			$a_field = array_shift($all_fields);
4508
+			$main_table = $this->_get_main_table();
4509
+			$cleaned_values[] = "SELECT "
4510
+								. $a_field->get_table_column()
4511
+								. " FROM "
4512
+								. $main_table->get_table_name()
4513
+								. " WHERE FALSE";
4514
+		}
4515
+		return "(" . implode(",", $cleaned_values) . ")";
4516
+	}
4517
+
4518
+
4519
+
4520
+	/**
4521
+	 * @param mixed                      $value
4522
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4523
+	 * @throws EE_Error
4524
+	 * @return false|null|string
4525
+	 */
4526
+	private function _wpdb_prepare_using_field($value, $field_obj)
4527
+	{
4528
+		/** @type WPDB $wpdb */
4529
+		global $wpdb;
4530
+		if ($field_obj instanceof EE_Model_Field_Base) {
4531
+			return $wpdb->prepare(
4532
+				$field_obj->get_wpdb_data_type(),
4533
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4534
+			);
4535
+		} //$field_obj should really just be a data type
4536
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4537
+			throw new EE_Error(
4538
+				sprintf(
4539
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4540
+					$field_obj,
4541
+					implode(",", $this->_valid_wpdb_data_types)
4542
+				)
4543
+			);
4544
+		}
4545
+		return $wpdb->prepare($field_obj, $value);
4546
+	}
4547
+
4548
+
4549
+
4550
+	/**
4551
+	 * Takes the input parameter and finds the model field that it indicates.
4552
+	 *
4553
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4554
+	 * @throws EE_Error
4555
+	 * @return EE_Model_Field_Base
4556
+	 */
4557
+	protected function _deduce_field_from_query_param($query_param_name)
4558
+	{
4559
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4560
+		// which will help us find the database table and column
4561
+		$query_param_parts = explode(".", $query_param_name);
4562
+		if (empty($query_param_parts)) {
4563
+			throw new EE_Error(sprintf(__(
4564
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4565
+				'event_espresso'
4566
+			), $query_param_name));
4567
+		}
4568
+		$number_of_parts = count($query_param_parts);
4569
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4570
+		if ($number_of_parts === 1) {
4571
+			$field_name = $last_query_param_part;
4572
+			$model_obj = $this;
4573
+		} else {// $number_of_parts >= 2
4574
+			// the last part is the column name, and there are only 2parts. therefore...
4575
+			$field_name = $last_query_param_part;
4576
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4577
+		}
4578
+		try {
4579
+			return $model_obj->field_settings_for($field_name);
4580
+		} catch (EE_Error $e) {
4581
+			return null;
4582
+		}
4583
+	}
4584
+
4585
+
4586
+
4587
+	/**
4588
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4589
+	 * alias and column which corresponds to it
4590
+	 *
4591
+	 * @param string $field_name
4592
+	 * @throws EE_Error
4593
+	 * @return string
4594
+	 */
4595
+	public function _get_qualified_column_for_field($field_name)
4596
+	{
4597
+		$all_fields = $this->field_settings();
4598
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4599
+		if ($field) {
4600
+			return $field->get_qualified_column();
4601
+		}
4602
+		throw new EE_Error(
4603
+			sprintf(
4604
+				__(
4605
+					"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.",
4606
+					'event_espresso'
4607
+				),
4608
+				$field_name,
4609
+				get_class($this)
4610
+			)
4611
+		);
4612
+	}
4613
+
4614
+
4615
+
4616
+	/**
4617
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4618
+	 * Example usage:
4619
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4620
+	 *      array(),
4621
+	 *      ARRAY_A,
4622
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4623
+	 *  );
4624
+	 * is equivalent to
4625
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4626
+	 * and
4627
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4628
+	 *      array(
4629
+	 *          array(
4630
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4631
+	 *          ),
4632
+	 *          ARRAY_A,
4633
+	 *          implode(
4634
+	 *              ', ',
4635
+	 *              array_merge(
4636
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4637
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4638
+	 *              )
4639
+	 *          )
4640
+	 *      )
4641
+	 *  );
4642
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4643
+	 *
4644
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4645
+	 *                                            and the one whose fields you are selecting for example: when querying
4646
+	 *                                            tickets model and selecting fields from the tickets model you would
4647
+	 *                                            leave this parameter empty, because no models are needed to join
4648
+	 *                                            between the queried model and the selected one. Likewise when
4649
+	 *                                            querying the datetime model and selecting fields from the tickets
4650
+	 *                                            model, it would also be left empty, because there is a direct
4651
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4652
+	 *                                            them together. However, when querying from the event model and
4653
+	 *                                            selecting fields from the ticket model, you should provide the string
4654
+	 *                                            'Datetime', indicating that the event model must first join to the
4655
+	 *                                            datetime model in order to find its relation to ticket model.
4656
+	 *                                            Also, when querying from the venue model and selecting fields from
4657
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4658
+	 *                                            indicating you need to join the venue model to the event model,
4659
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4660
+	 *                                            This string is used to deduce the prefix that gets added onto the
4661
+	 *                                            models' tables qualified columns
4662
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4663
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4664
+	 *                                            qualified column names
4665
+	 * @return array|string
4666
+	 */
4667
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4668
+	{
4669
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4670
+		$qualified_columns = array();
4671
+		foreach ($this->field_settings() as $field_name => $field) {
4672
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4673
+		}
4674
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4675
+	}
4676
+
4677
+
4678
+
4679
+	/**
4680
+	 * constructs the select use on special limit joins
4681
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4682
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4683
+	 * (as that is typically where the limits would be set).
4684
+	 *
4685
+	 * @param  string       $table_alias The table the select is being built for
4686
+	 * @param  mixed|string $limit       The limit for this select
4687
+	 * @return string                The final select join element for the query.
4688
+	 */
4689
+	public function _construct_limit_join_select($table_alias, $limit)
4690
+	{
4691
+		$SQL = '';
4692
+		foreach ($this->_tables as $table_obj) {
4693
+			if ($table_obj instanceof EE_Primary_Table) {
4694
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4695
+					? $table_obj->get_select_join_limit($limit)
4696
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4697
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4698
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4699
+					? $table_obj->get_select_join_limit_join($limit)
4700
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4701
+			}
4702
+		}
4703
+		return $SQL;
4704
+	}
4705
+
4706
+
4707
+
4708
+	/**
4709
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4710
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4711
+	 *
4712
+	 * @return string SQL
4713
+	 * @throws EE_Error
4714
+	 */
4715
+	public function _construct_internal_join()
4716
+	{
4717
+		$SQL = $this->_get_main_table()->get_table_sql();
4718
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4719
+		return $SQL;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Constructs the SQL for joining all the tables on this model.
4726
+	 * Normally $alias should be the primary table's alias, but in cases where
4727
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4728
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4729
+	 * alias, this will construct SQL like:
4730
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4731
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4732
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4733
+	 *
4734
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4735
+	 * @return string
4736
+	 */
4737
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4738
+	{
4739
+		$SQL = '';
4740
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4741
+		foreach ($this->_tables as $table_obj) {
4742
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4743
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4744
+					// so we're joining to this table, meaning the table is already in
4745
+					// the FROM statement, BUT the primary table isn't. So we want
4746
+					// to add the inverse join sql
4747
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4748
+				} else {
4749
+					// just add a regular JOIN to this table from the primary table
4750
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4751
+				}
4752
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4753
+		}
4754
+		return $SQL;
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4761
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4762
+	 * their data type (eg, '%s', '%d', etc)
4763
+	 *
4764
+	 * @return array
4765
+	 */
4766
+	public function _get_data_types()
4767
+	{
4768
+		$data_types = array();
4769
+		foreach ($this->field_settings() as $field_obj) {
4770
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4771
+			/** @var $field_obj EE_Model_Field_Base */
4772
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4773
+		}
4774
+		return $data_types;
4775
+	}
4776
+
4777
+
4778
+
4779
+	/**
4780
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4781
+	 *
4782
+	 * @param string $model_name
4783
+	 * @throws EE_Error
4784
+	 * @return EEM_Base
4785
+	 */
4786
+	public function get_related_model_obj($model_name)
4787
+	{
4788
+		$model_classname = "EEM_" . $model_name;
4789
+		if (! class_exists($model_classname)) {
4790
+			throw new EE_Error(sprintf(__(
4791
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4792
+				'event_espresso'
4793
+			), $model_name, $model_classname));
4794
+		}
4795
+		return call_user_func($model_classname . "::instance");
4796
+	}
4797
+
4798
+
4799
+
4800
+	/**
4801
+	 * Returns the array of EE_ModelRelations for this model.
4802
+	 *
4803
+	 * @return EE_Model_Relation_Base[]
4804
+	 */
4805
+	public function relation_settings()
4806
+	{
4807
+		return $this->_model_relations;
4808
+	}
4809
+
4810
+
4811
+
4812
+	/**
4813
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4814
+	 * because without THOSE models, this model probably doesn't have much purpose.
4815
+	 * (Eg, without an event, datetimes have little purpose.)
4816
+	 *
4817
+	 * @return EE_Belongs_To_Relation[]
4818
+	 */
4819
+	public function belongs_to_relations()
4820
+	{
4821
+		$belongs_to_relations = array();
4822
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4823
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4824
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4825
+			}
4826
+		}
4827
+		return $belongs_to_relations;
4828
+	}
4829
+
4830
+
4831
+
4832
+	/**
4833
+	 * Returns the specified EE_Model_Relation, or throws an exception
4834
+	 *
4835
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4836
+	 * @throws EE_Error
4837
+	 * @return EE_Model_Relation_Base
4838
+	 */
4839
+	public function related_settings_for($relation_name)
4840
+	{
4841
+		$relatedModels = $this->relation_settings();
4842
+		if (! array_key_exists($relation_name, $relatedModels)) {
4843
+			throw new EE_Error(
4844
+				sprintf(
4845
+					__(
4846
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4847
+						'event_espresso'
4848
+					),
4849
+					$relation_name,
4850
+					$this->_get_class_name(),
4851
+					implode(', ', array_keys($relatedModels))
4852
+				)
4853
+			);
4854
+		}
4855
+		return $relatedModels[ $relation_name ];
4856
+	}
4857
+
4858
+
4859
+
4860
+	/**
4861
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4862
+	 * fields
4863
+	 *
4864
+	 * @param string $fieldName
4865
+	 * @param boolean $include_db_only_fields
4866
+	 * @throws EE_Error
4867
+	 * @return EE_Model_Field_Base
4868
+	 */
4869
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4870
+	{
4871
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4872
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4873
+			throw new EE_Error(sprintf(
4874
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4875
+				$fieldName,
4876
+				get_class($this)
4877
+			));
4878
+		}
4879
+		return $fieldSettings[ $fieldName ];
4880
+	}
4881
+
4882
+
4883
+
4884
+	/**
4885
+	 * Checks if this field exists on this model
4886
+	 *
4887
+	 * @param string $fieldName a key in the model's _field_settings array
4888
+	 * @return boolean
4889
+	 */
4890
+	public function has_field($fieldName)
4891
+	{
4892
+		$fieldSettings = $this->field_settings(true);
4893
+		if (isset($fieldSettings[ $fieldName ])) {
4894
+			return true;
4895
+		}
4896
+		return false;
4897
+	}
4898
+
4899
+
4900
+
4901
+	/**
4902
+	 * Returns whether or not this model has a relation to the specified model
4903
+	 *
4904
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4905
+	 * @return boolean
4906
+	 */
4907
+	public function has_relation($relation_name)
4908
+	{
4909
+		$relations = $this->relation_settings();
4910
+		if (isset($relations[ $relation_name ])) {
4911
+			return true;
4912
+		}
4913
+		return false;
4914
+	}
4915
+
4916
+
4917
+
4918
+	/**
4919
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4920
+	 * Eg, on EE_Answer that would be ANS_ID field object
4921
+	 *
4922
+	 * @param $field_obj
4923
+	 * @return boolean
4924
+	 */
4925
+	public function is_primary_key_field($field_obj)
4926
+	{
4927
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4928
+	}
4929
+
4930
+
4931
+
4932
+	/**
4933
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
+	 * Eg, on EE_Answer that would be ANS_ID field object
4935
+	 *
4936
+	 * @return EE_Model_Field_Base
4937
+	 * @throws EE_Error
4938
+	 */
4939
+	public function get_primary_key_field()
4940
+	{
4941
+		if ($this->_primary_key_field === null) {
4942
+			foreach ($this->field_settings(true) as $field_obj) {
4943
+				if ($this->is_primary_key_field($field_obj)) {
4944
+					$this->_primary_key_field = $field_obj;
4945
+					break;
4946
+				}
4947
+			}
4948
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4949
+				throw new EE_Error(sprintf(
4950
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4951
+					get_class($this)
4952
+				));
4953
+			}
4954
+		}
4955
+		return $this->_primary_key_field;
4956
+	}
4957
+
4958
+
4959
+
4960
+	/**
4961
+	 * Returns whether or not not there is a primary key on this model.
4962
+	 * Internally does some caching.
4963
+	 *
4964
+	 * @return boolean
4965
+	 */
4966
+	public function has_primary_key_field()
4967
+	{
4968
+		if ($this->_has_primary_key_field === null) {
4969
+			try {
4970
+				$this->get_primary_key_field();
4971
+				$this->_has_primary_key_field = true;
4972
+			} catch (EE_Error $e) {
4973
+				$this->_has_primary_key_field = false;
4974
+			}
4975
+		}
4976
+		return $this->_has_primary_key_field;
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * Finds the first field of type $field_class_name.
4983
+	 *
4984
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4985
+	 *                                 EE_Foreign_Key_Field, etc
4986
+	 * @return EE_Model_Field_Base or null if none is found
4987
+	 */
4988
+	public function get_a_field_of_type($field_class_name)
4989
+	{
4990
+		foreach ($this->field_settings() as $field) {
4991
+			if ($field instanceof $field_class_name) {
4992
+				return $field;
4993
+			}
4994
+		}
4995
+		return null;
4996
+	}
4997
+
4998
+
4999
+
5000
+	/**
5001
+	 * Gets a foreign key field pointing to model.
5002
+	 *
5003
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5004
+	 * @return EE_Foreign_Key_Field_Base
5005
+	 * @throws EE_Error
5006
+	 */
5007
+	public function get_foreign_key_to($model_name)
5008
+	{
5009
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5010
+			foreach ($this->field_settings() as $field) {
5011
+				if ($field instanceof EE_Foreign_Key_Field_Base
5012
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5013
+				) {
5014
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5015
+					break;
5016
+				}
5017
+			}
5018
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5019
+				throw new EE_Error(sprintf(__(
5020
+					"There is no foreign key field pointing to model %s on model %s",
5021
+					'event_espresso'
5022
+				), $model_name, get_class($this)));
5023
+			}
5024
+		}
5025
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5026
+	}
5027
+
5028
+
5029
+
5030
+	/**
5031
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5032
+	 *
5033
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5034
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5035
+	 *                            Either one works
5036
+	 * @return string
5037
+	 */
5038
+	public function get_table_for_alias($table_alias)
5039
+	{
5040
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5041
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5042
+	}
5043
+
5044
+
5045
+
5046
+	/**
5047
+	 * Returns a flat array of all field son this model, instead of organizing them
5048
+	 * by table_alias as they are in the constructor.
5049
+	 *
5050
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5051
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5052
+	 */
5053
+	public function field_settings($include_db_only_fields = false)
5054
+	{
5055
+		if ($include_db_only_fields) {
5056
+			if ($this->_cached_fields === null) {
5057
+				$this->_cached_fields = array();
5058
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5059
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5060
+						$this->_cached_fields[ $field_name ] = $field_obj;
5061
+					}
5062
+				}
5063
+			}
5064
+			return $this->_cached_fields;
5065
+		}
5066
+		if ($this->_cached_fields_non_db_only === null) {
5067
+			$this->_cached_fields_non_db_only = array();
5068
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5069
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5070
+					/** @var $field_obj EE_Model_Field_Base */
5071
+					if (! $field_obj->is_db_only_field()) {
5072
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5073
+					}
5074
+				}
5075
+			}
5076
+		}
5077
+		return $this->_cached_fields_non_db_only;
5078
+	}
5079
+
5080
+
5081
+
5082
+	/**
5083
+	 *        cycle though array of attendees and create objects out of each item
5084
+	 *
5085
+	 * @access        private
5086
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5087
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5088
+	 *                           numerically indexed)
5089
+	 * @throws EE_Error
5090
+	 */
5091
+	protected function _create_objects($rows = array())
5092
+	{
5093
+		$array_of_objects = array();
5094
+		if (empty($rows)) {
5095
+			return array();
5096
+		}
5097
+		$count_if_model_has_no_primary_key = 0;
5098
+		$has_primary_key = $this->has_primary_key_field();
5099
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5100
+		foreach ((array) $rows as $row) {
5101
+			if (empty($row)) {
5102
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5103
+				return array();
5104
+			}
5105
+			// check if we've already set this object in the results array,
5106
+			// in which case there's no need to process it further (again)
5107
+			if ($has_primary_key) {
5108
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5109
+					$row,
5110
+					$primary_key_field->get_qualified_column(),
5111
+					$primary_key_field->get_table_column()
5112
+				);
5113
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5114
+					continue;
5115
+				}
5116
+			}
5117
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5118
+			if (! $classInstance) {
5119
+				throw new EE_Error(
5120
+					sprintf(
5121
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5122
+						$this->get_this_model_name(),
5123
+						http_build_query($row)
5124
+					)
5125
+				);
5126
+			}
5127
+			// set the timezone on the instantiated objects
5128
+			$classInstance->set_timezone($this->_timezone);
5129
+			// make sure if there is any timezone setting present that we set the timezone for the object
5130
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5131
+			$array_of_objects[ $key ] = $classInstance;
5132
+			// also, for all the relations of type BelongsTo, see if we can cache
5133
+			// those related models
5134
+			// (we could do this for other relations too, but if there are conditions
5135
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5136
+			// so it requires a little more thought than just caching them immediately...)
5137
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5138
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5139
+					// check if this model's INFO is present. If so, cache it on the model
5140
+					$other_model = $relation_obj->get_other_model();
5141
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5142
+					// if we managed to make a model object from the results, cache it on the main model object
5143
+					if ($other_model_obj_maybe) {
5144
+						// set timezone on these other model objects if they are present
5145
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5146
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5147
+					}
5148
+				}
5149
+			}
5150
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5151
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5152
+			// the field in the CustomSelects object
5153
+			if ($this->_custom_selections instanceof CustomSelects) {
5154
+				$classInstance->setCustomSelectsValues(
5155
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5156
+				);
5157
+			}
5158
+		}
5159
+		return $array_of_objects;
5160
+	}
5161
+
5162
+
5163
+	/**
5164
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5165
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5166
+	 *
5167
+	 * @param array $db_results_row
5168
+	 * @return array
5169
+	 */
5170
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5171
+	{
5172
+		$results = array();
5173
+		if ($this->_custom_selections instanceof CustomSelects) {
5174
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5175
+				if (isset($db_results_row[ $alias ])) {
5176
+					$results[ $alias ] = $this->convertValueToDataType(
5177
+						$db_results_row[ $alias ],
5178
+						$this->_custom_selections->getDataTypeForAlias($alias)
5179
+					);
5180
+				}
5181
+			}
5182
+		}
5183
+		return $results;
5184
+	}
5185
+
5186
+
5187
+	/**
5188
+	 * This will set the value for the given alias
5189
+	 * @param string $value
5190
+	 * @param string $datatype (one of %d, %s, %f)
5191
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5192
+	 */
5193
+	protected function convertValueToDataType($value, $datatype)
5194
+	{
5195
+		switch ($datatype) {
5196
+			case '%f':
5197
+				return (float) $value;
5198
+			case '%d':
5199
+				return (int) $value;
5200
+			default:
5201
+				return (string) $value;
5202
+		}
5203
+	}
5204
+
5205
+
5206
+	/**
5207
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5208
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5209
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5210
+	 * object (as set in the model_field!).
5211
+	 *
5212
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5213
+	 */
5214
+	public function create_default_object()
5215
+	{
5216
+		$this_model_fields_and_values = array();
5217
+		// setup the row using default values;
5218
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5219
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5220
+		}
5221
+		$className = $this->_get_class_name();
5222
+		$classInstance = EE_Registry::instance()
5223
+									->load_class($className, array($this_model_fields_and_values), false, false);
5224
+		return $classInstance;
5225
+	}
5226
+
5227
+
5228
+
5229
+	/**
5230
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5231
+	 *                             or an stdClass where each property is the name of a column,
5232
+	 * @return EE_Base_Class
5233
+	 * @throws EE_Error
5234
+	 */
5235
+	public function instantiate_class_from_array_or_object($cols_n_values)
5236
+	{
5237
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5238
+			$cols_n_values = get_object_vars($cols_n_values);
5239
+		}
5240
+		$primary_key = null;
5241
+		// make sure the array only has keys that are fields/columns on this model
5242
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5243
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5245
+		}
5246
+		$className = $this->_get_class_name();
5247
+		// check we actually found results that we can use to build our model object
5248
+		// if not, return null
5249
+		if ($this->has_primary_key_field()) {
5250
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5251
+				return null;
5252
+			}
5253
+		} elseif ($this->unique_indexes()) {
5254
+			$first_column = reset($this_model_fields_n_values);
5255
+			if (empty($first_column)) {
5256
+				return null;
5257
+			}
5258
+		}
5259
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5260
+		if ($primary_key) {
5261
+			$classInstance = $this->get_from_entity_map($primary_key);
5262
+			if (! $classInstance) {
5263
+				$classInstance = EE_Registry::instance()
5264
+											->load_class(
5265
+												$className,
5266
+												array($this_model_fields_n_values, $this->_timezone),
5267
+												true,
5268
+												false
5269
+											);
5270
+				// add this new object to the entity map
5271
+				$classInstance = $this->add_to_entity_map($classInstance);
5272
+			}
5273
+		} else {
5274
+			$classInstance = EE_Registry::instance()
5275
+										->load_class(
5276
+											$className,
5277
+											array($this_model_fields_n_values, $this->_timezone),
5278
+											true,
5279
+											false
5280
+										);
5281
+		}
5282
+		return $classInstance;
5283
+	}
5284
+
5285
+
5286
+
5287
+	/**
5288
+	 * Gets the model object from the  entity map if it exists
5289
+	 *
5290
+	 * @param int|string $id the ID of the model object
5291
+	 * @return EE_Base_Class
5292
+	 */
5293
+	public function get_from_entity_map($id)
5294
+	{
5295
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5296
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5297
+	}
5298
+
5299
+
5300
+
5301
+	/**
5302
+	 * add_to_entity_map
5303
+	 * Adds the object to the model's entity mappings
5304
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5305
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5306
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5307
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5308
+	 *        then this method should be called immediately after the update query
5309
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5310
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5311
+	 *
5312
+	 * @param    EE_Base_Class $object
5313
+	 * @throws EE_Error
5314
+	 * @return \EE_Base_Class
5315
+	 */
5316
+	public function add_to_entity_map(EE_Base_Class $object)
5317
+	{
5318
+		$className = $this->_get_class_name();
5319
+		if (! $object instanceof $className) {
5320
+			throw new EE_Error(sprintf(
5321
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5322
+				is_object($object) ? get_class($object) : $object,
5323
+				$className
5324
+			));
5325
+		}
5326
+		/** @var $object EE_Base_Class */
5327
+		if (! $object->ID()) {
5328
+			throw new EE_Error(sprintf(__(
5329
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5330
+				"event_espresso"
5331
+			), get_class($this)));
5332
+		}
5333
+		// double check it's not already there
5334
+		$classInstance = $this->get_from_entity_map($object->ID());
5335
+		if ($classInstance) {
5336
+			return $classInstance;
5337
+		}
5338
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5339
+		return $object;
5340
+	}
5341
+
5342
+
5343
+
5344
+	/**
5345
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5346
+	 * if no identifier is provided, then the entire entity map is emptied
5347
+	 *
5348
+	 * @param int|string $id the ID of the model object
5349
+	 * @return boolean
5350
+	 */
5351
+	public function clear_entity_map($id = null)
5352
+	{
5353
+		if (empty($id)) {
5354
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5355
+			return true;
5356
+		}
5357
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5358
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5359
+			return true;
5360
+		}
5361
+		return false;
5362
+	}
5363
+
5364
+
5365
+
5366
+	/**
5367
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5368
+	 * Given an array where keys are column (or column alias) names and values,
5369
+	 * returns an array of their corresponding field names and database values
5370
+	 *
5371
+	 * @param array $cols_n_values
5372
+	 * @return array
5373
+	 */
5374
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5375
+	{
5376
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5377
+	}
5378
+
5379
+
5380
+
5381
+	/**
5382
+	 * _deduce_fields_n_values_from_cols_n_values
5383
+	 * Given an array where keys are column (or column alias) names and values,
5384
+	 * returns an array of their corresponding field names and database values
5385
+	 *
5386
+	 * @param string $cols_n_values
5387
+	 * @return array
5388
+	 */
5389
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
+	{
5391
+		$this_model_fields_n_values = array();
5392
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5393
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5394
+				$cols_n_values,
5395
+				$table_obj->get_fully_qualified_pk_column(),
5396
+				$table_obj->get_pk_column()
5397
+			);
5398
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5399
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5400
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5401
+					if (! $field_obj->is_db_only_field()) {
5402
+						// prepare field as if its coming from db
5403
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5404
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5405
+					}
5406
+				}
5407
+			} else {
5408
+				// the table's rows existed. Use their values
5409
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5410
+					if (! $field_obj->is_db_only_field()) {
5411
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5412
+							$cols_n_values,
5413
+							$field_obj->get_qualified_column(),
5414
+							$field_obj->get_table_column()
5415
+						);
5416
+					}
5417
+				}
5418
+			}
5419
+		}
5420
+		return $this_model_fields_n_values;
5421
+	}
5422
+
5423
+
5424
+	/**
5425
+	 * @param $cols_n_values
5426
+	 * @param $qualified_column
5427
+	 * @param $regular_column
5428
+	 * @return null
5429
+	 * @throws EE_Error
5430
+	 * @throws ReflectionException
5431
+	 */
5432
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5433
+	{
5434
+		$value = null;
5435
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5436
+		// does the field on the model relate to this column retrieved from the db?
5437
+		// or is it a db-only field? (not relating to the model)
5438
+		if (isset($cols_n_values[ $qualified_column ])) {
5439
+			$value = $cols_n_values[ $qualified_column ];
5440
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5441
+			$value = $cols_n_values[ $regular_column ];
5442
+		} elseif (! empty($this->foreign_key_aliases)) {
5443
+			// no PK?  ok check if there is a foreign key alias set for this table
5444
+			// then check if that alias exists in the incoming data
5445
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5446
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5447
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5448
+					$value = $cols_n_values[ $FK_alias ];
5449
+					list($pk_class) = explode('.', $PK_column);
5450
+					$pk_model_name = "EEM_{$pk_class}";
5451
+					/** @var EEM_Base $pk_model */
5452
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5453
+					if ($pk_model instanceof EEM_Base) {
5454
+						// make sure object is pulled from db and added to entity map
5455
+						$pk_model->get_one_by_ID($value);
5456
+					}
5457
+					break;
5458
+				}
5459
+			}
5460
+		}
5461
+		return $value;
5462
+	}
5463
+
5464
+
5465
+
5466
+	/**
5467
+	 * refresh_entity_map_from_db
5468
+	 * Makes sure the model object in the entity map at $id assumes the values
5469
+	 * of the database (opposite of EE_base_Class::save())
5470
+	 *
5471
+	 * @param int|string $id
5472
+	 * @return EE_Base_Class
5473
+	 * @throws EE_Error
5474
+	 */
5475
+	public function refresh_entity_map_from_db($id)
5476
+	{
5477
+		$obj_in_map = $this->get_from_entity_map($id);
5478
+		if ($obj_in_map) {
5479
+			$wpdb_results = $this->_get_all_wpdb_results(
5480
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5481
+			);
5482
+			if ($wpdb_results && is_array($wpdb_results)) {
5483
+				$one_row = reset($wpdb_results);
5484
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5485
+					$obj_in_map->set_from_db($field_name, $db_value);
5486
+				}
5487
+				// clear the cache of related model objects
5488
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5489
+					$obj_in_map->clear_cache($relation_name, null, true);
5490
+				}
5491
+			}
5492
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5493
+			return $obj_in_map;
5494
+		}
5495
+		return $this->get_one_by_ID($id);
5496
+	}
5497
+
5498
+
5499
+
5500
+	/**
5501
+	 * refresh_entity_map_with
5502
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5503
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5504
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5505
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5506
+	 *
5507
+	 * @param int|string    $id
5508
+	 * @param EE_Base_Class $replacing_model_obj
5509
+	 * @return \EE_Base_Class
5510
+	 * @throws EE_Error
5511
+	 */
5512
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5513
+	{
5514
+		$obj_in_map = $this->get_from_entity_map($id);
5515
+		if ($obj_in_map) {
5516
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5517
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5518
+					$obj_in_map->set($field_name, $value);
5519
+				}
5520
+				// make the model object in the entity map's cache match the $replacing_model_obj
5521
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5522
+					$obj_in_map->clear_cache($relation_name, null, true);
5523
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5524
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5525
+					}
5526
+				}
5527
+			}
5528
+			return $obj_in_map;
5529
+		}
5530
+		$this->add_to_entity_map($replacing_model_obj);
5531
+		return $replacing_model_obj;
5532
+	}
5533
+
5534
+
5535
+
5536
+	/**
5537
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5538
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5539
+	 * require_once($this->_getClassName().".class.php");
5540
+	 *
5541
+	 * @return string
5542
+	 */
5543
+	private function _get_class_name()
5544
+	{
5545
+		return "EE_" . $this->get_this_model_name();
5546
+	}
5547
+
5548
+
5549
+
5550
+	/**
5551
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5552
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5553
+	 * it would be 'Events'.
5554
+	 *
5555
+	 * @param int $quantity
5556
+	 * @return string
5557
+	 */
5558
+	public function item_name($quantity = 1)
5559
+	{
5560
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5561
+	}
5562
+
5563
+
5564
+
5565
+	/**
5566
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5567
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5568
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5569
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5570
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5571
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5572
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5573
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5574
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5575
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5576
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5577
+	 *        return $previousReturnValue.$returnString;
5578
+	 * }
5579
+	 * require('EEM_Answer.model.php');
5580
+	 * $answer=EEM_Answer::instance();
5581
+	 * echo $answer->my_callback('monkeys',100);
5582
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5583
+	 *
5584
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5585
+	 * @param array  $args       array of original arguments passed to the function
5586
+	 * @throws EE_Error
5587
+	 * @return mixed whatever the plugin which calls add_filter decides
5588
+	 */
5589
+	public function __call($methodName, $args)
5590
+	{
5591
+		$className = get_class($this);
5592
+		$tagName = "FHEE__{$className}__{$methodName}";
5593
+		if (! has_filter($tagName)) {
5594
+			throw new EE_Error(
5595
+				sprintf(
5596
+					__(
5597
+						'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 );',
5598
+						'event_espresso'
5599
+					),
5600
+					$methodName,
5601
+					$className,
5602
+					$tagName,
5603
+					'<br />'
5604
+				)
5605
+			);
5606
+		}
5607
+		return apply_filters($tagName, null, $this, $args);
5608
+	}
5609
+
5610
+
5611
+
5612
+	/**
5613
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5614
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5615
+	 *
5616
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5617
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5618
+	 *                                                       the object's class name
5619
+	 *                                                       or object's ID
5620
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5621
+	 *                                                       exists in the database. If it does not, we add it
5622
+	 * @throws EE_Error
5623
+	 * @return EE_Base_Class
5624
+	 */
5625
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5626
+	{
5627
+		$className = $this->_get_class_name();
5628
+		if ($base_class_obj_or_id instanceof $className) {
5629
+			$model_object = $base_class_obj_or_id;
5630
+		} else {
5631
+			$primary_key_field = $this->get_primary_key_field();
5632
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5633
+				&& (
5634
+					is_int($base_class_obj_or_id)
5635
+					|| is_string($base_class_obj_or_id)
5636
+				)
5637
+			) {
5638
+				// assume it's an ID.
5639
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5640
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5641
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5642
+				&& is_string($base_class_obj_or_id)
5643
+			) {
5644
+				// assume its a string representation of the object
5645
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5646
+			} else {
5647
+				throw new EE_Error(
5648
+					sprintf(
5649
+						__(
5650
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5651
+							'event_espresso'
5652
+						),
5653
+						$base_class_obj_or_id,
5654
+						$this->_get_class_name(),
5655
+						print_r($base_class_obj_or_id, true)
5656
+					)
5657
+				);
5658
+			}
5659
+		}
5660
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5661
+			$model_object->save();
5662
+		}
5663
+		return $model_object;
5664
+	}
5665
+
5666
+
5667
+
5668
+	/**
5669
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5670
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5671
+	 * returns it ID.
5672
+	 *
5673
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5674
+	 * @return int|string depending on the type of this model object's ID
5675
+	 * @throws EE_Error
5676
+	 */
5677
+	public function ensure_is_ID($base_class_obj_or_id)
5678
+	{
5679
+		$className = $this->_get_class_name();
5680
+		if ($base_class_obj_or_id instanceof $className) {
5681
+			/** @var $base_class_obj_or_id EE_Base_Class */
5682
+			$id = $base_class_obj_or_id->ID();
5683
+		} elseif (is_int($base_class_obj_or_id)) {
5684
+			// assume it's an ID
5685
+			$id = $base_class_obj_or_id;
5686
+		} elseif (is_string($base_class_obj_or_id)) {
5687
+			// assume its a string representation of the object
5688
+			$id = $base_class_obj_or_id;
5689
+		} else {
5690
+			throw new EE_Error(sprintf(
5691
+				__(
5692
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5693
+					'event_espresso'
5694
+				),
5695
+				$base_class_obj_or_id,
5696
+				$this->_get_class_name(),
5697
+				print_r($base_class_obj_or_id, true)
5698
+			));
5699
+		}
5700
+		return $id;
5701
+	}
5702
+
5703
+
5704
+
5705
+	/**
5706
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5707
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5708
+	 * been sanitized and converted into the appropriate domain.
5709
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5710
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5711
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5712
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5713
+	 * $EVT = EEM_Event::instance(); $old_setting =
5714
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5715
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5716
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5717
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5718
+	 *
5719
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5720
+	 * @return void
5721
+	 */
5722
+	public function assume_values_already_prepared_by_model_object(
5723
+		$values_already_prepared = self::not_prepared_by_model_object
5724
+	) {
5725
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5726
+	}
5727
+
5728
+
5729
+
5730
+	/**
5731
+	 * Read comments for assume_values_already_prepared_by_model_object()
5732
+	 *
5733
+	 * @return int
5734
+	 */
5735
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5736
+	{
5737
+		return $this->_values_already_prepared_by_model_object;
5738
+	}
5739
+
5740
+
5741
+
5742
+	/**
5743
+	 * Gets all the indexes on this model
5744
+	 *
5745
+	 * @return EE_Index[]
5746
+	 */
5747
+	public function indexes()
5748
+	{
5749
+		return $this->_indexes;
5750
+	}
5751
+
5752
+
5753
+
5754
+	/**
5755
+	 * Gets all the Unique Indexes on this model
5756
+	 *
5757
+	 * @return EE_Unique_Index[]
5758
+	 */
5759
+	public function unique_indexes()
5760
+	{
5761
+		$unique_indexes = array();
5762
+		foreach ($this->_indexes as $name => $index) {
5763
+			if ($index instanceof EE_Unique_Index) {
5764
+				$unique_indexes [ $name ] = $index;
5765
+			}
5766
+		}
5767
+		return $unique_indexes;
5768
+	}
5769
+
5770
+
5771
+
5772
+	/**
5773
+	 * Gets all the fields which, when combined, make the primary key.
5774
+	 * This is usually just an array with 1 element (the primary key), but in cases
5775
+	 * where there is no primary key, it's a combination of fields as defined
5776
+	 * on a primary index
5777
+	 *
5778
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5779
+	 * @throws EE_Error
5780
+	 */
5781
+	public function get_combined_primary_key_fields()
5782
+	{
5783
+		foreach ($this->indexes() as $index) {
5784
+			if ($index instanceof EE_Primary_Key_Index) {
5785
+				return $index->fields();
5786
+			}
5787
+		}
5788
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5789
+	}
5790
+
5791
+
5792
+
5793
+	/**
5794
+	 * Used to build a primary key string (when the model has no primary key),
5795
+	 * which can be used a unique string to identify this model object.
5796
+	 *
5797
+	 * @param array $fields_n_values keys are field names, values are their values.
5798
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5799
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5800
+	 *                               before passing it to this function (that will convert it from columns-n-values
5801
+	 *                               to field-names-n-values).
5802
+	 * @return string
5803
+	 * @throws EE_Error
5804
+	 */
5805
+	public function get_index_primary_key_string($fields_n_values)
5806
+	{
5807
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5808
+			$fields_n_values,
5809
+			$this->get_combined_primary_key_fields()
5810
+		);
5811
+		return http_build_query($cols_n_values_for_primary_key_index);
5812
+	}
5813
+
5814
+
5815
+
5816
+	/**
5817
+	 * Gets the field values from the primary key string
5818
+	 *
5819
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5820
+	 * @param string $index_primary_key_string
5821
+	 * @return null|array
5822
+	 * @throws EE_Error
5823
+	 */
5824
+	public function parse_index_primary_key_string($index_primary_key_string)
5825
+	{
5826
+		$key_fields = $this->get_combined_primary_key_fields();
5827
+		// check all of them are in the $id
5828
+		$key_vals_in_combined_pk = array();
5829
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5830
+		foreach ($key_fields as $key_field_name => $field_obj) {
5831
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5832
+				return null;
5833
+			}
5834
+		}
5835
+		return $key_vals_in_combined_pk;
5836
+	}
5837
+
5838
+
5839
+
5840
+	/**
5841
+	 * verifies that an array of key-value pairs for model fields has a key
5842
+	 * for each field comprising the primary key index
5843
+	 *
5844
+	 * @param array $key_vals
5845
+	 * @return boolean
5846
+	 * @throws EE_Error
5847
+	 */
5848
+	public function has_all_combined_primary_key_fields($key_vals)
5849
+	{
5850
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5851
+		foreach ($keys_it_should_have as $key) {
5852
+			if (! isset($key_vals[ $key ])) {
5853
+				return false;
5854
+			}
5855
+		}
5856
+		return true;
5857
+	}
5858
+
5859
+
5860
+
5861
+	/**
5862
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5863
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5864
+	 *
5865
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5866
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5867
+	 * @throws EE_Error
5868
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5869
+	 *                                                              indexed)
5870
+	 */
5871
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5872
+	{
5873
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5874
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5875
+		} elseif (is_array($model_object_or_attributes_array)) {
5876
+			$attributes_array = $model_object_or_attributes_array;
5877
+		} else {
5878
+			throw new EE_Error(sprintf(__(
5879
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5880
+				"event_espresso"
5881
+			), $model_object_or_attributes_array));
5882
+		}
5883
+		// even copies obviously won't have the same ID, so remove the primary key
5884
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5885
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5886
+			unset($attributes_array[ $this->primary_key_name() ]);
5887
+		}
5888
+		if (isset($query_params[0])) {
5889
+			$query_params[0] = array_merge($attributes_array, $query_params);
5890
+		} else {
5891
+			$query_params[0] = $attributes_array;
5892
+		}
5893
+		return $this->get_all($query_params);
5894
+	}
5895
+
5896
+
5897
+
5898
+	/**
5899
+	 * Gets the first copy we find. See get_all_copies for more details
5900
+	 *
5901
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5902
+	 * @param array $query_params
5903
+	 * @return EE_Base_Class
5904
+	 * @throws EE_Error
5905
+	 */
5906
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5907
+	{
5908
+		if (! is_array($query_params)) {
5909
+			EE_Error::doing_it_wrong(
5910
+				'EEM_Base::get_one_copy',
5911
+				sprintf(
5912
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5913
+					gettype($query_params)
5914
+				),
5915
+				'4.6.0'
5916
+			);
5917
+			$query_params = array();
5918
+		}
5919
+		$query_params['limit'] = 1;
5920
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5921
+		if (is_array($copies)) {
5922
+			return array_shift($copies);
5923
+		}
5924
+		return null;
5925
+	}
5926
+
5927
+
5928
+
5929
+	/**
5930
+	 * Updates the item with the specified id. Ignores default query parameters because
5931
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5932
+	 *
5933
+	 * @param array      $fields_n_values keys are field names, values are their new values
5934
+	 * @param int|string $id              the value of the primary key to update
5935
+	 * @return int number of rows updated
5936
+	 * @throws EE_Error
5937
+	 */
5938
+	public function update_by_ID($fields_n_values, $id)
5939
+	{
5940
+		$query_params = array(
5941
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5942
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5943
+		);
5944
+		return $this->update($fields_n_values, $query_params);
5945
+	}
5946
+
5947
+
5948
+
5949
+	/**
5950
+	 * Changes an operator which was supplied to the models into one usable in SQL
5951
+	 *
5952
+	 * @param string $operator_supplied
5953
+	 * @return string an operator which can be used in SQL
5954
+	 * @throws EE_Error
5955
+	 */
5956
+	private function _prepare_operator_for_sql($operator_supplied)
5957
+	{
5958
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5959
+			: null;
5960
+		if ($sql_operator) {
5961
+			return $sql_operator;
5962
+		}
5963
+		throw new EE_Error(
5964
+			sprintf(
5965
+				__(
5966
+					"The operator '%s' is not in the list of valid operators: %s",
5967
+					"event_espresso"
5968
+				),
5969
+				$operator_supplied,
5970
+				implode(",", array_keys($this->_valid_operators))
5971
+			)
5972
+		);
5973
+	}
5974
+
5975
+
5976
+
5977
+	/**
5978
+	 * Gets the valid operators
5979
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5980
+	 */
5981
+	public function valid_operators()
5982
+	{
5983
+		return $this->_valid_operators;
5984
+	}
5985
+
5986
+
5987
+
5988
+	/**
5989
+	 * Gets the between-style operators (take 2 arguments).
5990
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5991
+	 */
5992
+	public function valid_between_style_operators()
5993
+	{
5994
+		return array_intersect(
5995
+			$this->valid_operators(),
5996
+			$this->_between_style_operators
5997
+		);
5998
+	}
5999
+
6000
+	/**
6001
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6002
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6003
+	 */
6004
+	public function valid_like_style_operators()
6005
+	{
6006
+		return array_intersect(
6007
+			$this->valid_operators(),
6008
+			$this->_like_style_operators
6009
+		);
6010
+	}
6011
+
6012
+	/**
6013
+	 * Gets the "in"-style operators
6014
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6015
+	 */
6016
+	public function valid_in_style_operators()
6017
+	{
6018
+		return array_intersect(
6019
+			$this->valid_operators(),
6020
+			$this->_in_style_operators
6021
+		);
6022
+	}
6023
+
6024
+	/**
6025
+	 * Gets the "null"-style operators (accept no arguments)
6026
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6027
+	 */
6028
+	public function valid_null_style_operators()
6029
+	{
6030
+		return array_intersect(
6031
+			$this->valid_operators(),
6032
+			$this->_null_style_operators
6033
+		);
6034
+	}
6035
+
6036
+	/**
6037
+	 * Gets an array where keys are the primary keys and values are their 'names'
6038
+	 * (as determined by the model object's name() function, which is often overridden)
6039
+	 *
6040
+	 * @param array $query_params like get_all's
6041
+	 * @return string[]
6042
+	 * @throws EE_Error
6043
+	 */
6044
+	public function get_all_names($query_params = array())
6045
+	{
6046
+		$objs = $this->get_all($query_params);
6047
+		$names = array();
6048
+		foreach ($objs as $obj) {
6049
+			$names[ $obj->ID() ] = $obj->name();
6050
+		}
6051
+		return $names;
6052
+	}
6053
+
6054
+
6055
+
6056
+	/**
6057
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6058
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6059
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6060
+	 * array_keys() on $model_objects.
6061
+	 *
6062
+	 * @param \EE_Base_Class[] $model_objects
6063
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6064
+	 *                                               in the returned array
6065
+	 * @return array
6066
+	 * @throws EE_Error
6067
+	 */
6068
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6069
+	{
6070
+		if (! $this->has_primary_key_field()) {
6071
+			if (WP_DEBUG) {
6072
+				EE_Error::add_error(
6073
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6074
+					__FILE__,
6075
+					__FUNCTION__,
6076
+					__LINE__
6077
+				);
6078
+			}
6079
+		}
6080
+		$IDs = array();
6081
+		foreach ($model_objects as $model_object) {
6082
+			$id = $model_object->ID();
6083
+			if (! $id) {
6084
+				if ($filter_out_empty_ids) {
6085
+					continue;
6086
+				}
6087
+				if (WP_DEBUG) {
6088
+					EE_Error::add_error(
6089
+						__(
6090
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6091
+							'event_espresso'
6092
+						),
6093
+						__FILE__,
6094
+						__FUNCTION__,
6095
+						__LINE__
6096
+					);
6097
+				}
6098
+			}
6099
+			$IDs[] = $id;
6100
+		}
6101
+		return $IDs;
6102
+	}
6103
+
6104
+
6105
+
6106
+	/**
6107
+	 * Returns the string used in capabilities relating to this model. If there
6108
+	 * are no capabilities that relate to this model returns false
6109
+	 *
6110
+	 * @return string|false
6111
+	 */
6112
+	public function cap_slug()
6113
+	{
6114
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6115
+	}
6116
+
6117
+
6118
+
6119
+	/**
6120
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6121
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6122
+	 * only returns the cap restrictions array in that context (ie, the array
6123
+	 * at that key)
6124
+	 *
6125
+	 * @param string $context
6126
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6127
+	 * @throws EE_Error
6128
+	 */
6129
+	public function cap_restrictions($context = EEM_Base::caps_read)
6130
+	{
6131
+		EEM_Base::verify_is_valid_cap_context($context);
6132
+		// check if we ought to run the restriction generator first
6133
+		if (isset($this->_cap_restriction_generators[ $context ])
6134
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6135
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6136
+		) {
6137
+			$this->_cap_restrictions[ $context ] = array_merge(
6138
+				$this->_cap_restrictions[ $context ],
6139
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6140
+			);
6141
+		}
6142
+		// and make sure we've finalized the construction of each restriction
6143
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6144
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6145
+				$where_conditions_obj->_finalize_construct($this);
6146
+			}
6147
+		}
6148
+		return $this->_cap_restrictions[ $context ];
6149
+	}
6150
+
6151
+
6152
+
6153
+	/**
6154
+	 * Indicating whether or not this model thinks its a wp core model
6155
+	 *
6156
+	 * @return boolean
6157
+	 */
6158
+	public function is_wp_core_model()
6159
+	{
6160
+		return $this->_wp_core_model;
6161
+	}
6162
+
6163
+
6164
+
6165
+	/**
6166
+	 * Gets all the caps that are missing which impose a restriction on
6167
+	 * queries made in this context
6168
+	 *
6169
+	 * @param string $context one of EEM_Base::caps_ constants
6170
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6171
+	 * @throws EE_Error
6172
+	 */
6173
+	public function caps_missing($context = EEM_Base::caps_read)
6174
+	{
6175
+		$missing_caps = array();
6176
+		$cap_restrictions = $this->cap_restrictions($context);
6177
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6178
+			if (! EE_Capabilities::instance()
6179
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6180
+			) {
6181
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6182
+			}
6183
+		}
6184
+		return $missing_caps;
6185
+	}
6186
+
6187
+
6188
+
6189
+	/**
6190
+	 * Gets the mapping from capability contexts to action strings used in capability names
6191
+	 *
6192
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6193
+	 * one of 'read', 'edit', or 'delete'
6194
+	 */
6195
+	public function cap_contexts_to_cap_action_map()
6196
+	{
6197
+		return apply_filters(
6198
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6199
+			$this->_cap_contexts_to_cap_action_map,
6200
+			$this
6201
+		);
6202
+	}
6203
+
6204
+
6205
+
6206
+	/**
6207
+	 * Gets the action string for the specified capability context
6208
+	 *
6209
+	 * @param string $context
6210
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6211
+	 * @throws EE_Error
6212
+	 */
6213
+	public function cap_action_for_context($context)
6214
+	{
6215
+		$mapping = $this->cap_contexts_to_cap_action_map();
6216
+		if (isset($mapping[ $context ])) {
6217
+			return $mapping[ $context ];
6218
+		}
6219
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6220
+			return $action;
6221
+		}
6222
+		throw new EE_Error(
6223
+			sprintf(
6224
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6225
+				$context,
6226
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6227
+			)
6228
+		);
6229
+	}
6230
+
6231
+
6232
+
6233
+	/**
6234
+	 * Returns all the capability contexts which are valid when querying models
6235
+	 *
6236
+	 * @return array
6237
+	 */
6238
+	public static function valid_cap_contexts()
6239
+	{
6240
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6241
+			self::caps_read,
6242
+			self::caps_read_admin,
6243
+			self::caps_edit,
6244
+			self::caps_delete,
6245
+		));
6246
+	}
6247
+
6248
+
6249
+
6250
+	/**
6251
+	 * Returns all valid options for 'default_where_conditions'
6252
+	 *
6253
+	 * @return array
6254
+	 */
6255
+	public static function valid_default_where_conditions()
6256
+	{
6257
+		return array(
6258
+			EEM_Base::default_where_conditions_all,
6259
+			EEM_Base::default_where_conditions_this_only,
6260
+			EEM_Base::default_where_conditions_others_only,
6261
+			EEM_Base::default_where_conditions_minimum_all,
6262
+			EEM_Base::default_where_conditions_minimum_others,
6263
+			EEM_Base::default_where_conditions_none
6264
+		);
6265
+	}
6266
+
6267
+	// public static function default_where_conditions_full
6268
+	/**
6269
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6270
+	 *
6271
+	 * @param string $context
6272
+	 * @return bool
6273
+	 * @throws EE_Error
6274
+	 */
6275
+	public static function verify_is_valid_cap_context($context)
6276
+	{
6277
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6278
+		if (in_array($context, $valid_cap_contexts)) {
6279
+			return true;
6280
+		}
6281
+		throw new EE_Error(
6282
+			sprintf(
6283
+				__(
6284
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6285
+					'event_espresso'
6286
+				),
6287
+				$context,
6288
+				'EEM_Base',
6289
+				implode(',', $valid_cap_contexts)
6290
+			)
6291
+		);
6292
+	}
6293
+
6294
+
6295
+
6296
+	/**
6297
+	 * Clears all the models field caches. This is only useful when a sub-class
6298
+	 * might have added a field or something and these caches might be invalidated
6299
+	 */
6300
+	protected function _invalidate_field_caches()
6301
+	{
6302
+		$this->_cache_foreign_key_to_fields = array();
6303
+		$this->_cached_fields = null;
6304
+		$this->_cached_fields_non_db_only = null;
6305
+	}
6306
+
6307
+
6308
+
6309
+	/**
6310
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6311
+	 * (eg "and", "or", "not").
6312
+	 *
6313
+	 * @return array
6314
+	 */
6315
+	public function logic_query_param_keys()
6316
+	{
6317
+		return $this->_logic_query_param_keys;
6318
+	}
6319
+
6320
+
6321
+
6322
+	/**
6323
+	 * Determines whether or not the where query param array key is for a logic query param.
6324
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6325
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6326
+	 *
6327
+	 * @param $query_param_key
6328
+	 * @return bool
6329
+	 */
6330
+	public function is_logic_query_param_key($query_param_key)
6331
+	{
6332
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6333
+			if ($query_param_key === $logic_query_param_key
6334
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6335
+			) {
6336
+				return true;
6337
+			}
6338
+		}
6339
+		return false;
6340
+	}
6341
+
6342
+	/**
6343
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6344
+	 * @since 4.9.74.p
6345
+	 * @return boolean
6346
+	 */
6347
+	public function hasPassword()
6348
+	{
6349
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6350
+		if ($this->has_password_field === null) {
6351
+			$password_field = $this->getPasswordField();
6352
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6353
+		}
6354
+		return $this->has_password_field;
6355
+	}
6356
+
6357
+	/**
6358
+	 * Returns the password field on this model, if there is one
6359
+	 * @since 4.9.74.p
6360
+	 * @return EE_Password_Field|null
6361
+	 */
6362
+	public function getPasswordField()
6363
+	{
6364
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6365
+		// there's no need to search for it. If we don't know yet, then find out
6366
+		if ($this->has_password_field === null && $this->password_field === null) {
6367
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6368
+		}
6369
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6370
+		return $this->password_field;
6371
+	}
6372
+
6373
+
6374
+	/**
6375
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6376
+	 * @since 4.9.74.p
6377
+	 * @return EE_Model_Field_Base[]
6378
+	 * @throws EE_Error
6379
+	 */
6380
+	public function getPasswordProtectedFields()
6381
+	{
6382
+		$password_field = $this->getPasswordField();
6383
+		$fields = array();
6384
+		if ($password_field instanceof EE_Password_Field) {
6385
+			$field_names = $password_field->protectedFields();
6386
+			foreach ($field_names as $field_name) {
6387
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6388
+			}
6389
+		}
6390
+		return $fields;
6391
+	}
6392
+
6393
+
6394
+	/**
6395
+	 * Checks if the current user can perform the requested action on this model
6396
+	 * @since 4.9.74.p
6397
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6398
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6399
+	 * @return bool
6400
+	 * @throws EE_Error
6401
+	 * @throws InvalidArgumentException
6402
+	 * @throws InvalidDataTypeException
6403
+	 * @throws InvalidInterfaceException
6404
+	 * @throws ReflectionException
6405
+	 * @throws UnexpectedEntityException
6406
+	 */
6407
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6408
+	{
6409
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6410
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6411
+		}
6412
+		if (!is_array($model_obj_or_fields_n_values)) {
6413
+			throw new UnexpectedEntityException(
6414
+				$model_obj_or_fields_n_values,
6415
+				'EE_Base_Class',
6416
+				sprintf(
6417
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6418
+					__FUNCTION__
6419
+				)
6420
+			);
6421
+		}
6422
+		return $this->exists(
6423
+			$this->alter_query_params_to_restrict_by_ID(
6424
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6425
+				array(
6426
+					'default_where_conditions' => 'none',
6427
+					'caps'                     => $cap_to_check,
6428
+				)
6429
+			)
6430
+		);
6431
+	}
6432
+
6433
+	/**
6434
+	 * Returns the query param where conditions key to the password affecting this model.
6435
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6436
+	 * @since 4.9.74.p
6437
+	 * @return null|string
6438
+	 * @throws EE_Error
6439
+	 * @throws InvalidArgumentException
6440
+	 * @throws InvalidDataTypeException
6441
+	 * @throws InvalidInterfaceException
6442
+	 * @throws ModelConfigurationException
6443
+	 * @throws ReflectionException
6444
+	 */
6445
+	public function modelChainAndPassword()
6446
+	{
6447
+		if ($this->model_chain_to_password === null) {
6448
+			throw new ModelConfigurationException(
6449
+				$this,
6450
+				esc_html_x(
6451
+				// @codingStandardsIgnoreStart
6452
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6453
+					// @codingStandardsIgnoreEnd
6454
+					'1: model name',
6455
+					'event_espresso'
6456
+				)
6457
+			);
6458
+		}
6459
+		if ($this->model_chain_to_password === '') {
6460
+			$model_with_password = $this;
6461
+		} else {
6462
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6463
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6464
+			} else {
6465
+				$last_model_in_chain = $this->model_chain_to_password;
6466
+			}
6467
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6468
+		}
6469
+
6470
+		$password_field = $model_with_password->getPasswordField();
6471
+		if ($password_field instanceof EE_Password_Field) {
6472
+			$password_field_name = $password_field->get_name();
6473
+		} else {
6474
+			throw new ModelConfigurationException(
6475
+				$this,
6476
+				sprintf(
6477
+					esc_html_x(
6478
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6479
+						'1: model name, 2: special string',
6480
+						'event_espresso'
6481
+					),
6482
+					$model_with_password->get_this_model_name(),
6483
+					$this->model_chain_to_password
6484
+				)
6485
+			);
6486
+		}
6487
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6488
+	}
6489
+
6490
+	/**
6491
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6492
+	 * or if this model itself has a password affecting access to some of its other fields.
6493
+	 * @since 4.9.74.p
6494
+	 * @return boolean
6495
+	 */
6496
+	public function restrictedByRelatedModelPassword()
6497
+	{
6498
+		return $this->model_chain_to_password !== null;
6499
+	}
6500 6500
 }
Please login to merge, or discard this patch.
Spacing   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     protected function __construct($timezone = null)
555 555
     {
556 556
         // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
557
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
558 558
             throw new EE_Error(
559 559
                 sprintf(
560 560
                     __(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @var EE_Table_Base[] $_tables
579 579
          */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
580
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
581 581
         foreach ($this->_tables as $table_alias => $table_obj) {
582 582
             /** @var $table_obj EE_Table_Base */
583 583
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
          *
593 593
          * @param EE_Model_Field_Base[] $_fields
594 594
          */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
595
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
596 596
         $this->_invalidate_field_caches();
597 597
         foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
598
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
599 599
                 throw new EE_Error(sprintf(__(
600 600
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601 601
                     'event_espresso'
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
          * @param EE_Model_Relation_Base[] $_model_relations
627 627
          */
628 628
         $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
629
+            'FHEE__'.get_class($this).'__construct__model_relations',
630 630
             $this->_model_relations
631 631
         );
632 632
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
         }
640 640
         $this->set_timezone($timezone);
641 641
         // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
642
+        if ( ! $this->_default_where_conditions_strategy) {
643 643
             // nothing was set during child constructor, so set default
644 644
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645 645
         }
646 646
         $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
647
+        if ( ! $this->_minimum_where_conditions_strategy) {
648 648
             // nothing was set during child constructor, so set default
649 649
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650 650
         }
@@ -657,8 +657,8 @@  discard block
 block discarded – undo
657 657
         // initialize the standard cap restriction generators if none were specified by the child constructor
658 658
         if ($this->_cap_restriction_generators !== false) {
659 659
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
660
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
661
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
662 662
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663 663
                         new EE_Restriction_Generator_Protected(),
664 664
                         $cap_context,
@@ -670,10 +670,10 @@  discard block
 block discarded – undo
670 670
         // if there are cap restriction generators, use them to make the default cap restrictions
671 671
         if ($this->_cap_restriction_generators !== false) {
672 672
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
673
+                if ( ! $generator_object) {
674 674
                     continue;
675 675
                 }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
676
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
677 677
                     throw new EE_Error(
678 678
                         sprintf(
679 679
                             __(
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
                     );
687 687
                 }
688 688
                 $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
689
+                if ( ! $generator_object->construction_finalized()) {
690 690
                     $generator_object->_construct_finalize($this, $action);
691 691
                 }
692 692
             }
693 693
         }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
694
+        do_action('AHEE__'.get_class($this).'__construct__end');
695 695
     }
696 696
 
697 697
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     public static function instance($timezone = null)
739 739
     {
740 740
         // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
741
+        if ( ! static::$_instance instanceof static) {
742 742
             // instantiate Espresso_model
743 743
             static::$_instance = new static(
744 744
                 $timezone,
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach ($r->getDefaultProperties() as $property => $value) {
778 778
                 // don't set instance to null like it was originally,
779 779
                 // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
780
+                if ( ! isset($static_properties[$property])) {
781 781
                     static::$_instance->{$property} = $value;
782 782
                 }
783 783
             }
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
      */
802 802
     private static function getLoader()
803 803
     {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
804
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
805 805
             EEM_Base::$loader = LoaderFactory::getLoader();
806 806
         }
807 807
         return EEM_Base::$loader;
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
      */
822 822
     public function status_array($translated = false)
823 823
     {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
824
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
825 825
             return array();
826 826
         }
827 827
         $model_name = $this->get_this_model_name();
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830 830
         $status_array = array();
831 831
         foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
832
+            $status_array[$status->ID()] = $status->get('STS_code');
833 833
         }
834 834
         return $translated
835 835
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
     {
890 890
         $wp_user_field_name = $this->wp_user_field_name();
891 891
         if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
892
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
893 893
         }
894 894
         return $query_params;
895 895
     }
@@ -907,17 +907,17 @@  discard block
 block discarded – undo
907 907
     public function wp_user_field_name()
908 908
     {
909 909
         try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
910
+            if ( ! empty($this->_model_chain_to_wp_user)) {
911 911
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912 912
                 $last_model_name = end($models_to_follow_to_wp_users);
913 913
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
914
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
915 915
             } else {
916 916
                 $model_with_fk_to_wp_users = $this;
917 917
                 $model_chain_to_wp_user = '';
918 918
             }
919 919
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
920
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
921 921
         } catch (EE_Error $e) {
922 922
             return false;
923 923
         }
@@ -994,11 +994,11 @@  discard block
 block discarded – undo
994 994
         if ($this->_custom_selections instanceof CustomSelects) {
995 995
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996 996
             $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
997
+                ? ', '.$custom_expressions
998 998
                 : $custom_expressions;
999 999
         }
1000 1000
 
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1001
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1002 1002
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003 1003
     }
1004 1004
 
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
      */
1016 1016
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017 1017
     {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1018
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019 1019
             return null;
1020 1020
         }
1021 1021
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
         if (is_array($columns_to_select)) {
1065 1065
             $select_sql_array = array();
1066 1066
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1067
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068 1068
                     throw new EE_Error(
1069 1069
                         sprintf(
1070 1070
                             __(
@@ -1076,7 +1076,7 @@  discard block
 block discarded – undo
1076 1076
                         )
1077 1077
                     );
1078 1078
                 }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1079
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080 1080
                     throw new EE_Error(
1081 1081
                         sprintf(
1082 1082
                             esc_html__(
@@ -1155,12 +1155,12 @@  discard block
 block discarded – undo
1155 1155
      */
1156 1156
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157 1157
     {
1158
-        if (! isset($query_params[0])) {
1158
+        if ( ! isset($query_params[0])) {
1159 1159
             $query_params[0] = array();
1160 1160
         }
1161 1161
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1162 1162
         if ($conditions_from_id === null) {
1163
-            $query_params[0][ $this->primary_key_name() ] = $id;
1163
+            $query_params[0][$this->primary_key_name()] = $id;
1164 1164
         } else {
1165 1165
             // no primary key, so the $id must be from the get_index_primary_key_string()
1166 1166
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
      */
1181 1181
     public function get_one($query_params = array())
1182 1182
     {
1183
-        if (! is_array($query_params)) {
1183
+        if ( ! is_array($query_params)) {
1184 1184
             EE_Error::doing_it_wrong(
1185 1185
                 'EEM_Base::get_one',
1186 1186
                 sprintf(
@@ -1378,7 +1378,7 @@  discard block
 block discarded – undo
1378 1378
                 return array();
1379 1379
             }
1380 1380
         }
1381
-        if (! is_array($query_params)) {
1381
+        if ( ! is_array($query_params)) {
1382 1382
             EE_Error::doing_it_wrong(
1383 1383
                 'EEM_Base::_get_consecutive',
1384 1384
                 sprintf(
@@ -1390,7 +1390,7 @@  discard block
 block discarded – undo
1390 1390
             $query_params = array();
1391 1391
         }
1392 1392
         // let's add the where query param for consecutive look up.
1393
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1393
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1394 1394
         $query_params['limit'] = $limit;
1395 1395
         // set direction
1396 1396
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
     {
1472 1472
         $field_settings = $this->field_settings_for($field_name);
1473 1473
         // if not a valid EE_Datetime_Field then throw error
1474
-        if (! $field_settings instanceof EE_Datetime_Field) {
1474
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1475 1475
             throw new EE_Error(sprintf(__(
1476 1476
                 '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.',
1477 1477
                 'event_espresso'
@@ -1620,7 +1620,7 @@  discard block
 block discarded – undo
1620 1620
      */
1621 1621
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622 1622
     {
1623
-        if (! is_array($query_params)) {
1623
+        if ( ! is_array($query_params)) {
1624 1624
             EE_Error::doing_it_wrong(
1625 1625
                 'EEM_Base::update',
1626 1626
                 sprintf(
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
             $wpdb_result = (array) $wpdb_result;
1669 1669
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670 1670
             if ($this->has_primary_key_field()) {
1671
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1671
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1672 1672
             } else {
1673 1673
                 // 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)
1674 1674
                 $main_table_pk_value = null;
@@ -1682,8 +1682,8 @@  discard block
 block discarded – undo
1682 1682
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683 1683
                     // if there is no private key for this table on the results, it means there's no entry
1684 1684
                     // in this table, right? so insert a row in the current table, using any fields available
1685
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
-                           && $wpdb_result[ $this_table_pk_column ])
1685
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
+                           && $wpdb_result[$this_table_pk_column])
1687 1687
                     ) {
1688 1688
                         $success = $this->_insert_into_specific_table(
1689 1689
                             $table_obj,
@@ -1691,7 +1691,7 @@  discard block
 block discarded – undo
1691 1691
                             $main_table_pk_value
1692 1692
                         );
1693 1693
                         // if we died here, report the error
1694
-                        if (! $success) {
1694
+                        if ( ! $success) {
1695 1695
                             return false;
1696 1696
                         }
1697 1697
                     }
@@ -1719,10 +1719,10 @@  discard block
 block discarded – undo
1719 1719
                 $model_objs_affected_ids = array();
1720 1720
                 foreach ($models_affected_key_columns as $row) {
1721 1721
                     $combined_index_key = $this->get_index_primary_key_string($row);
1722
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1722
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1723 1723
                 }
1724 1724
             }
1725
-            if (! $model_objs_affected_ids) {
1725
+            if ( ! $model_objs_affected_ids) {
1726 1726
                 // wait wait wait- if nothing was affected let's stop here
1727 1727
                 return 0;
1728 1728
             }
@@ -1749,7 +1749,7 @@  discard block
 block discarded – undo
1749 1749
                . $model_query_info->get_full_join_sql()
1750 1750
                . " SET "
1751 1751
                . $this->_construct_update_sql($fields_n_values)
1752
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1752
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753 1753
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754 1754
         /**
1755 1755
          * Action called after a model update call has been made.
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
          * @param int      $rows_affected
1761 1761
          */
1762 1762
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
-        return $rows_affected;// how many supposedly got updated
1763
+        return $rows_affected; // how many supposedly got updated
1764 1764
     }
1765 1765
 
1766 1766
 
@@ -1788,7 +1788,7 @@  discard block
 block discarded – undo
1788 1788
         }
1789 1789
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1790 1790
         $select_expressions = $field->get_qualified_column();
1791
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1791
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1792 1792
         return $this->_do_wpdb_query('get_col', array($SQL));
1793 1793
     }
1794 1794
 
@@ -1806,7 +1806,7 @@  discard block
 block discarded – undo
1806 1806
     {
1807 1807
         $query_params['limit'] = 1;
1808 1808
         $col = $this->get_col($query_params, $field_to_select);
1809
-        if (! empty($col)) {
1809
+        if ( ! empty($col)) {
1810 1810
             return reset($col);
1811 1811
         }
1812 1812
         return null;
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838 1838
             $value_sql = $prepared_value === null ? 'NULL'
1839 1839
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1840
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1841 1841
         }
1842 1842
         return implode(",", $cols_n_values);
1843 1843
     }
@@ -1980,12 +1980,12 @@  discard block
 block discarded – undo
1980 1980
         // there was no error with the delete query.
1981 1981
         if ($this->has_primary_key_field()
1982 1982
             && $rows_deleted !== false
1983
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1983
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1984 1984
         ) {
1985
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1985
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1986 1986
             foreach ($ids_for_removal as $id) {
1987
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1987
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1988
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1989 1989
                 }
1990 1990
             }
1991 1991
 
@@ -2020,7 +2020,7 @@  discard block
 block discarded – undo
2020 2020
          * @param int      $rows_deleted
2021 2021
          */
2022 2022
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
-        return $rows_deleted;// how many supposedly got deleted
2023
+        return $rows_deleted; // how many supposedly got deleted
2024 2024
     }
2025 2025
 
2026 2026
 
@@ -2113,15 +2113,15 @@  discard block
 block discarded – undo
2113 2113
                 // make sure there's no related entities blocking its deletion (if we're checking)
2114 2114
                 if ($allow_blocking
2115 2115
                     && $this->delete_is_blocked_by_related_models(
2116
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2116
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2117 2117
                     )
2118 2118
                 ) {
2119 2119
                     continue;
2120 2120
                 }
2121 2121
                 // primary table deletes
2122
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2122
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2123
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2124
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2125 2125
                 }
2126 2126
             }
2127 2127
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2130,8 +2130,8 @@  discard block
 block discarded – undo
2130 2130
                 $ids_to_delete_indexed_by_column_for_row = array();
2131 2131
                 foreach ($fields as $cpk_field) {
2132 2132
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2133
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2133
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2134
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2135 2135
                     }
2136 2136
                 }
2137 2137
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2171,7 +2171,7 @@  discard block
 block discarded – undo
2171 2171
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172 2172
                 // make sure we have unique $ids
2173 2173
                 $ids = array_unique($ids);
2174
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2174
+                $query[] = $column.' IN('.implode(',', $ids).')';
2175 2175
             }
2176 2176
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2177 2177
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2179,7 +2179,7 @@  discard block
 block discarded – undo
2179 2179
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2180 2180
                 $values_for_each_combined_primary_key_for_a_row = array();
2181 2181
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2182
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2182
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2183 2183
                 }
2184 2184
                 $ways_to_identify_a_row[] = '('
2185 2185
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2251,8 +2251,8 @@  discard block
 block discarded – undo
2251 2251
                 $column_to_count = '*';
2252 2252
             }
2253 2253
         }
2254
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2255
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2254
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2255
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2256 2256
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2257 2257
     }
2258 2258
 
@@ -2275,7 +2275,7 @@  discard block
 block discarded – undo
2275 2275
             $field_obj = $this->get_primary_key_field();
2276 2276
         }
2277 2277
         $column_to_count = $field_obj->get_qualified_column();
2278
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2278
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2279 2279
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2280 2280
         $data_type = $field_obj->get_wpdb_data_type();
2281 2281
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2302,7 +2302,7 @@  discard block
 block discarded – undo
2302 2302
         // if we're in maintenance mode level 2, DON'T run any queries
2303 2303
         // because level 2 indicates the database needs updating and
2304 2304
         // is probably out of sync with the code
2305
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2305
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2306 2306
             throw new EE_Error(sprintf(__(
2307 2307
                 "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.",
2308 2308
                 "event_espresso"
@@ -2310,7 +2310,7 @@  discard block
 block discarded – undo
2310 2310
         }
2311 2311
         /** @type WPDB $wpdb */
2312 2312
         global $wpdb;
2313
-        if (! method_exists($wpdb, $wpdb_method)) {
2313
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2314 2314
             throw new EE_Error(sprintf(__(
2315 2315
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2316 2316
                 'event_espresso'
@@ -2324,7 +2324,7 @@  discard block
 block discarded – undo
2324 2324
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2325 2325
         if (WP_DEBUG) {
2326 2326
             $wpdb->show_errors($old_show_errors_value);
2327
-            if (! empty($wpdb->last_error)) {
2327
+            if ( ! empty($wpdb->last_error)) {
2328 2328
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2329 2329
             }
2330 2330
             if ($result === false) {
@@ -2389,7 +2389,7 @@  discard block
 block discarded – undo
2389 2389
                     return $result;
2390 2390
                     break;
2391 2391
             }
2392
-            if (! empty($error_message)) {
2392
+            if ( ! empty($error_message)) {
2393 2393
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2394 2394
                 trigger_error($error_message);
2395 2395
             }
@@ -2469,11 +2469,11 @@  discard block
 block discarded – undo
2469 2469
      */
2470 2470
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2471 2471
     {
2472
-        return " FROM " . $model_query_info->get_full_join_sql() .
2473
-               $model_query_info->get_where_sql() .
2474
-               $model_query_info->get_group_by_sql() .
2475
-               $model_query_info->get_having_sql() .
2476
-               $model_query_info->get_order_by_sql() .
2472
+        return " FROM ".$model_query_info->get_full_join_sql().
2473
+               $model_query_info->get_where_sql().
2474
+               $model_query_info->get_group_by_sql().
2475
+               $model_query_info->get_having_sql().
2476
+               $model_query_info->get_order_by_sql().
2477 2477
                $model_query_info->get_limit_sql();
2478 2478
     }
2479 2479
 
@@ -2669,12 +2669,12 @@  discard block
 block discarded – undo
2669 2669
         $related_model = $this->get_related_model_obj($model_name);
2670 2670
         // we're just going to use the query params on the related model's normal get_all query,
2671 2671
         // except add a condition to say to match the current mod
2672
-        if (! isset($query_params['default_where_conditions'])) {
2672
+        if ( ! isset($query_params['default_where_conditions'])) {
2673 2673
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2674 2674
         }
2675 2675
         $this_model_name = $this->get_this_model_name();
2676 2676
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2677
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2677
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2678 2678
         return $related_model->count($query_params, $field_to_count, $distinct);
2679 2679
     }
2680 2680
 
@@ -2694,7 +2694,7 @@  discard block
 block discarded – undo
2694 2694
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2695 2695
     {
2696 2696
         $related_model = $this->get_related_model_obj($model_name);
2697
-        if (! is_array($query_params)) {
2697
+        if ( ! is_array($query_params)) {
2698 2698
             EE_Error::doing_it_wrong(
2699 2699
                 'EEM_Base::sum_related',
2700 2700
                 sprintf(
@@ -2707,12 +2707,12 @@  discard block
 block discarded – undo
2707 2707
         }
2708 2708
         // we're just going to use the query params on the related model's normal get_all query,
2709 2709
         // except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2710
+        if ( ! isset($query_params['default_where_conditions'])) {
2711 2711
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712 2712
         }
2713 2713
         $this_model_name = $this->get_this_model_name();
2714 2714
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2715
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2716 2716
         return $related_model->sum($query_params, $field_to_sum);
2717 2717
     }
2718 2718
 
@@ -2765,7 +2765,7 @@  discard block
 block discarded – undo
2765 2765
                 $field_with_model_name = $field;
2766 2766
             }
2767 2767
         }
2768
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2768
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2769 2769
             throw new EE_Error(sprintf(
2770 2770
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2771 2771
                 $this->get_this_model_name()
@@ -2901,13 +2901,13 @@  discard block
 block discarded – undo
2901 2901
                 || $this->get_primary_key_field()
2902 2902
                    instanceof
2903 2903
                    EE_Primary_Key_String_Field)
2904
-            && isset($fields_n_values[ $this->primary_key_name() ])
2904
+            && isset($fields_n_values[$this->primary_key_name()])
2905 2905
         ) {
2906
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2906
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2907 2907
         }
2908 2908
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2909 2909
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2910
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2910
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2911 2911
         }
2912 2912
         // if there is nothing to base this search on, then we shouldn't find anything
2913 2913
         if (empty($query_params)) {
@@ -2985,15 +2985,15 @@  discard block
 block discarded – undo
2985 2985
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2986 2986
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2987 2987
             if ($prepared_value !== null) {
2988
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2988
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2989 2989
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2990 2990
             }
2991 2991
         }
2992 2992
         if ($table instanceof EE_Secondary_Table && $new_id) {
2993 2993
             // its not the main table, so we should have already saved the main table's PK which we just inserted
2994 2994
             // so add the fk to the main table as a column
2995
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2996
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2995
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2996
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
2997 2997
         }
2998 2998
         // insert the new entry
2999 2999
         $result = $this->_do_wpdb_query(
@@ -3010,7 +3010,7 @@  discard block
 block discarded – undo
3010 3010
             }
3011 3011
             // it's not an auto-increment primary key, so
3012 3012
             // it must have been supplied
3013
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3013
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3014 3014
         }
3015 3015
         // we can't return a  primary key because there is none. instead return
3016 3016
         // a unique string indicating this model
@@ -3032,16 +3032,16 @@  discard block
 block discarded – undo
3032 3032
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3033 3033
     {
3034 3034
         // if this field doesn't allow nullable, don't allow it
3035
-        if (! $field_obj->is_nullable()
3035
+        if ( ! $field_obj->is_nullable()
3036 3036
             && (
3037
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3038
-                || $fields_n_values[ $field_obj->get_name() ] === null
3037
+                ! isset($fields_n_values[$field_obj->get_name()])
3038
+                || $fields_n_values[$field_obj->get_name()] === null
3039 3039
             )
3040 3040
         ) {
3041
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3041
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3042 3042
         }
3043
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3044
-            ? $fields_n_values[ $field_obj->get_name() ]
3043
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3044
+            ? $fields_n_values[$field_obj->get_name()]
3045 3045
             : null;
3046 3046
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3047 3047
     }
@@ -3142,7 +3142,7 @@  discard block
 block discarded – undo
3142 3142
      */
3143 3143
     public function get_table_obj_by_alias($table_alias = '')
3144 3144
     {
3145
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3145
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3146 3146
     }
3147 3147
 
3148 3148
 
@@ -3157,7 +3157,7 @@  discard block
 block discarded – undo
3157 3157
         $other_tables = array();
3158 3158
         foreach ($this->_tables as $table_alias => $table) {
3159 3159
             if ($table instanceof EE_Secondary_Table) {
3160
-                $other_tables[ $table_alias ] = $table;
3160
+                $other_tables[$table_alias] = $table;
3161 3161
             }
3162 3162
         }
3163 3163
         return $other_tables;
@@ -3173,7 +3173,7 @@  discard block
 block discarded – undo
3173 3173
      */
3174 3174
     public function _get_fields_for_table($table_alias)
3175 3175
     {
3176
-        return $this->_fields[ $table_alias ];
3176
+        return $this->_fields[$table_alias];
3177 3177
     }
3178 3178
 
3179 3179
 
@@ -3202,7 +3202,7 @@  discard block
 block discarded – undo
3202 3202
                     $query_info_carrier,
3203 3203
                     'group_by'
3204 3204
                 );
3205
-            } elseif (! empty($query_params['group_by'])) {
3205
+            } elseif ( ! empty($query_params['group_by'])) {
3206 3206
                 $this->_extract_related_model_info_from_query_param(
3207 3207
                     $query_params['group_by'],
3208 3208
                     $query_info_carrier,
@@ -3224,7 +3224,7 @@  discard block
 block discarded – undo
3224 3224
                     $query_info_carrier,
3225 3225
                     'order_by'
3226 3226
                 );
3227
-            } elseif (! empty($query_params['order_by'])) {
3227
+            } elseif ( ! empty($query_params['order_by'])) {
3228 3228
                 $this->_extract_related_model_info_from_query_param(
3229 3229
                     $query_params['order_by'],
3230 3230
                     $query_info_carrier,
@@ -3259,7 +3259,7 @@  discard block
 block discarded – undo
3259 3259
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3260 3260
         $query_param_type
3261 3261
     ) {
3262
-        if (! empty($sub_query_params)) {
3262
+        if ( ! empty($sub_query_params)) {
3263 3263
             $sub_query_params = (array) $sub_query_params;
3264 3264
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3265 3265
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3274,7 +3274,7 @@  discard block
 block discarded – undo
3274 3274
                 // of array('Registration.TXN_ID'=>23)
3275 3275
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3276 3276
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3277
-                    if (! is_array($possibly_array_of_params)) {
3277
+                    if ( ! is_array($possibly_array_of_params)) {
3278 3278
                         throw new EE_Error(sprintf(
3279 3279
                             __(
3280 3280
                                 "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'))",
@@ -3297,7 +3297,7 @@  discard block
 block discarded – undo
3297 3297
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3298 3298
                     // indicating that $possible_array_of_params[1] is actually a field name,
3299 3299
                     // from which we should extract query parameters!
3300
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3300
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3301 3301
                         throw new EE_Error(sprintf(__(
3302 3302
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303 3303
                             "event_espresso"
@@ -3331,8 +3331,8 @@  discard block
 block discarded – undo
3331 3331
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3332 3332
         $query_param_type
3333 3333
     ) {
3334
-        if (! empty($sub_query_params)) {
3335
-            if (! is_array($sub_query_params)) {
3334
+        if ( ! empty($sub_query_params)) {
3335
+            if ( ! is_array($sub_query_params)) {
3336 3336
                 throw new EE_Error(sprintf(
3337 3337
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3338 3338
                     $sub_query_params
@@ -3366,7 +3366,7 @@  discard block
 block discarded – undo
3366 3366
      */
3367 3367
     public function _create_model_query_info_carrier($query_params)
3368 3368
     {
3369
-        if (! is_array($query_params)) {
3369
+        if ( ! is_array($query_params)) {
3370 3370
             EE_Error::doing_it_wrong(
3371 3371
                 'EEM_Base::_create_model_query_info_carrier',
3372 3372
                 sprintf(
@@ -3399,7 +3399,7 @@  discard block
 block discarded – undo
3399 3399
             // only include if related to a cpt where no password has been set
3400 3400
             $query_params[0]['OR*nopassword'] = array(
3401 3401
                 $where_param_key_for_password => '',
3402
-                $where_param_key_for_password . '*' => array('IS_NULL')
3402
+                $where_param_key_for_password.'*' => array('IS_NULL')
3403 3403
             );
3404 3404
         }
3405 3405
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3452,7 +3452,7 @@  discard block
 block discarded – undo
3452 3452
         // set limit
3453 3453
         if (array_key_exists('limit', $query_params)) {
3454 3454
             if (is_array($query_params['limit'])) {
3455
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3455
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3456 3456
                     $e = sprintf(
3457 3457
                         __(
3458 3458
                             "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)",
@@ -3460,12 +3460,12 @@  discard block
 block discarded – undo
3460 3460
                         ),
3461 3461
                         http_build_query($query_params['limit'])
3462 3462
                     );
3463
-                    throw new EE_Error($e . "|" . $e);
3463
+                    throw new EE_Error($e."|".$e);
3464 3464
                 }
3465 3465
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3466
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3467
-            } elseif (! empty($query_params['limit'])) {
3468
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3466
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3467
+            } elseif ( ! empty($query_params['limit'])) {
3468
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3469 3469
             }
3470 3470
         }
3471 3471
         // set order by
@@ -3497,10 +3497,10 @@  discard block
 block discarded – undo
3497 3497
                 $order_array = array();
3498 3498
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3499 3499
                     $order = $this->_extract_order($order);
3500
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3500
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3501 3501
                 }
3502
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3503
-            } elseif (! empty($query_params['order_by'])) {
3502
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3503
+            } elseif ( ! empty($query_params['order_by'])) {
3504 3504
                 $this->_extract_related_model_info_from_query_param(
3505 3505
                     $query_params['order_by'],
3506 3506
                     $query_object,
@@ -3511,18 +3511,18 @@  discard block
 block discarded – undo
3511 3511
                     ? $this->_extract_order($query_params['order'])
3512 3512
                     : 'DESC';
3513 3513
                 $query_object->set_order_by_sql(
3514
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3514
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3515 3515
                 );
3516 3516
             }
3517 3517
         }
3518 3518
         // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3519
-        if (! array_key_exists('order_by', $query_params)
3519
+        if ( ! array_key_exists('order_by', $query_params)
3520 3520
             && array_key_exists('order', $query_params)
3521 3521
             && ! empty($query_params['order'])
3522 3522
         ) {
3523 3523
             $pk_field = $this->get_primary_key_field();
3524 3524
             $order = $this->_extract_order($query_params['order']);
3525
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3525
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3526 3526
         }
3527 3527
         // set group by
3528 3528
         if (array_key_exists('group_by', $query_params)) {
@@ -3532,10 +3532,10 @@  discard block
 block discarded – undo
3532 3532
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3533 3533
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3534 3534
                 }
3535
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3536
-            } elseif (! empty($query_params['group_by'])) {
3535
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3536
+            } elseif ( ! empty($query_params['group_by'])) {
3537 3537
                 $query_object->set_group_by_sql(
3538
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3538
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3539 3539
                 );
3540 3540
             }
3541 3541
         }
@@ -3545,7 +3545,7 @@  discard block
 block discarded – undo
3545 3545
         }
3546 3546
         // now, just verify they didn't pass anything wack
3547 3547
         foreach ($query_params as $query_key => $query_value) {
3548
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3548
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3549 3549
                 throw new EE_Error(
3550 3550
                     sprintf(
3551 3551
                         __(
@@ -3653,7 +3653,7 @@  discard block
 block discarded – undo
3653 3653
         $where_query_params = array()
3654 3654
     ) {
3655 3655
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3656
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3656
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3657 3657
             throw new EE_Error(sprintf(
3658 3658
                 __(
3659 3659
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3785,19 +3785,19 @@  discard block
 block discarded – undo
3785 3785
     ) {
3786 3786
         $null_friendly_where_conditions = array();
3787 3787
         $none_overridden = true;
3788
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3788
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3789 3789
         foreach ($default_where_conditions as $key => $val) {
3790
-            if (isset($provided_where_conditions[ $key ])) {
3790
+            if (isset($provided_where_conditions[$key])) {
3791 3791
                 $none_overridden = false;
3792 3792
             } else {
3793
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3793
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3794 3794
             }
3795 3795
         }
3796 3796
         if ($none_overridden && $default_where_conditions) {
3797 3797
             if ($model->has_primary_key_field()) {
3798
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3798
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3799 3799
                                                                                 . "."
3800
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3800
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3801 3801
             }/*else{
3802 3802
                 //@todo NO PK, use other defaults
3803 3803
             }*/
@@ -3903,7 +3903,7 @@  discard block
 block discarded – undo
3903 3903
             foreach ($tables as $table_obj) {
3904 3904
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3905 3905
                                        . $table_obj->get_fully_qualified_pk_column();
3906
-                if (! in_array($qualified_pk_column, $selects)) {
3906
+                if ( ! in_array($qualified_pk_column, $selects)) {
3907 3907
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3908 3908
                 }
3909 3909
             }
@@ -4052,9 +4052,9 @@  discard block
 block discarded – undo
4052 4052
         $query_parameter_type
4053 4053
     ) {
4054 4054
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4055
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4055
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4056 4056
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4057
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4057
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4058 4058
                 if ($possible_join_string === '') {
4059 4059
                     // nothing left to $query_param
4060 4060
                     // we should actually end in a field name, not a model like this!
@@ -4184,7 +4184,7 @@  discard block
 block discarded – undo
4184 4184
     {
4185 4185
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4186 4186
         if ($SQL) {
4187
-            return " WHERE " . $SQL;
4187
+            return " WHERE ".$SQL;
4188 4188
         }
4189 4189
         return '';
4190 4190
     }
@@ -4203,7 +4203,7 @@  discard block
 block discarded – undo
4203 4203
     {
4204 4204
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4205 4205
         if ($SQL) {
4206
-            return " HAVING " . $SQL;
4206
+            return " HAVING ".$SQL;
4207 4207
         }
4208 4208
         return '';
4209 4209
     }
@@ -4222,7 +4222,7 @@  discard block
 block discarded – undo
4222 4222
     {
4223 4223
         $where_clauses = array();
4224 4224
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4225
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4225
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4226 4226
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4227 4227
                 switch ($query_param) {
4228 4228
                     case 'not':
@@ -4256,7 +4256,7 @@  discard block
 block discarded – undo
4256 4256
             } else {
4257 4257
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4258 4258
                 // if it's not a normal field, maybe it's a custom selection?
4259
-                if (! $field_obj) {
4259
+                if ( ! $field_obj) {
4260 4260
                     if ($this->_custom_selections instanceof CustomSelects) {
4261 4261
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4262 4262
                     } else {
@@ -4267,7 +4267,7 @@  discard block
 block discarded – undo
4267 4267
                     }
4268 4268
                 }
4269 4269
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4270
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4270
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4271 4271
             }
4272 4272
         }
4273 4273
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4290,7 +4290,7 @@  discard block
 block discarded – undo
4290 4290
                 $field->get_model_name(),
4291 4291
                 $query_param
4292 4292
             );
4293
-            return $table_alias_prefix . $field->get_qualified_column();
4293
+            return $table_alias_prefix.$field->get_qualified_column();
4294 4294
         }
4295 4295
         if ($this->_custom_selections instanceof CustomSelects
4296 4296
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4349,7 +4349,7 @@  discard block
 block discarded – undo
4349 4349
     {
4350 4350
         if (is_array($op_and_value)) {
4351 4351
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4352
-            if (! $operator) {
4352
+            if ( ! $operator) {
4353 4353
                 $php_array_like_string = array();
4354 4354
                 foreach ($op_and_value as $key => $value) {
4355 4355
                     $php_array_like_string[] = "$key=>$value";
@@ -4371,14 +4371,14 @@  discard block
 block discarded – undo
4371 4371
         }
4372 4372
         // check to see if the value is actually another field
4373 4373
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4374
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4374
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4375 4375
         }
4376 4376
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4377 4377
             // in this case, the value should be an array, or at least a comma-separated list
4378 4378
             // it will need to handle a little differently
4379 4379
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4380 4380
             // note: $cleaned_value has already been run through $wpdb->prepare()
4381
-            return $operator . SP . $cleaned_value;
4381
+            return $operator.SP.$cleaned_value;
4382 4382
         }
4383 4383
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4384 4384
             // the value should be an array with count of two.
@@ -4394,7 +4394,7 @@  discard block
 block discarded – undo
4394 4394
                 );
4395 4395
             }
4396 4396
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4397
-            return $operator . SP . $cleaned_value;
4397
+            return $operator.SP.$cleaned_value;
4398 4398
         }
4399 4399
         if (in_array($operator, $this->valid_null_style_operators())) {
4400 4400
             if ($value !== null) {
@@ -4414,10 +4414,10 @@  discard block
 block discarded – undo
4414 4414
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4415 4415
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4416 4416
             // remove other junk. So just treat it as a string.
4417
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4417
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4418 4418
         }
4419
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4419
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4421 4421
         }
4422 4422
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4423 4423
             throw new EE_Error(
@@ -4431,7 +4431,7 @@  discard block
 block discarded – undo
4431 4431
                 )
4432 4432
             );
4433 4433
         }
4434
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4434
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4435 4435
             throw new EE_Error(
4436 4436
                 sprintf(
4437 4437
                     __(
@@ -4471,7 +4471,7 @@  discard block
 block discarded – undo
4471 4471
         foreach ($values as $value) {
4472 4472
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4473 4473
         }
4474
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4474
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4475 4475
     }
4476 4476
 
4477 4477
 
@@ -4512,7 +4512,7 @@  discard block
 block discarded – undo
4512 4512
                                 . $main_table->get_table_name()
4513 4513
                                 . " WHERE FALSE";
4514 4514
         }
4515
-        return "(" . implode(",", $cleaned_values) . ")";
4515
+        return "(".implode(",", $cleaned_values).")";
4516 4516
     }
4517 4517
 
4518 4518
 
@@ -4533,7 +4533,7 @@  discard block
 block discarded – undo
4533 4533
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4534 4534
             );
4535 4535
         } //$field_obj should really just be a data type
4536
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4536
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4537 4537
             throw new EE_Error(
4538 4538
                 sprintf(
4539 4539
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4566,14 +4566,14 @@  discard block
 block discarded – undo
4566 4566
             ), $query_param_name));
4567 4567
         }
4568 4568
         $number_of_parts = count($query_param_parts);
4569
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4569
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4570 4570
         if ($number_of_parts === 1) {
4571 4571
             $field_name = $last_query_param_part;
4572 4572
             $model_obj = $this;
4573 4573
         } else {// $number_of_parts >= 2
4574 4574
             // the last part is the column name, and there are only 2parts. therefore...
4575 4575
             $field_name = $last_query_param_part;
4576
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4576
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4577 4577
         }
4578 4578
         try {
4579 4579
             return $model_obj->field_settings_for($field_name);
@@ -4595,7 +4595,7 @@  discard block
 block discarded – undo
4595 4595
     public function _get_qualified_column_for_field($field_name)
4596 4596
     {
4597 4597
         $all_fields = $this->field_settings();
4598
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4598
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4599 4599
         if ($field) {
4600 4600
             return $field->get_qualified_column();
4601 4601
         }
@@ -4666,10 +4666,10 @@  discard block
 block discarded – undo
4666 4666
      */
4667 4667
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4668 4668
     {
4669
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4669
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4670 4670
         $qualified_columns = array();
4671 4671
         foreach ($this->field_settings() as $field_name => $field) {
4672
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4672
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4673 4673
         }
4674 4674
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4675 4675
     }
@@ -4693,11 +4693,11 @@  discard block
 block discarded – undo
4693 4693
             if ($table_obj instanceof EE_Primary_Table) {
4694 4694
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4695 4695
                     ? $table_obj->get_select_join_limit($limit)
4696
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4696
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4697 4697
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4698 4698
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4699 4699
                     ? $table_obj->get_select_join_limit_join($limit)
4700
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4700
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4701 4701
             }
4702 4702
         }
4703 4703
         return $SQL;
@@ -4769,7 +4769,7 @@  discard block
 block discarded – undo
4769 4769
         foreach ($this->field_settings() as $field_obj) {
4770 4770
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4771 4771
             /** @var $field_obj EE_Model_Field_Base */
4772
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4772
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4773 4773
         }
4774 4774
         return $data_types;
4775 4775
     }
@@ -4785,14 +4785,14 @@  discard block
 block discarded – undo
4785 4785
      */
4786 4786
     public function get_related_model_obj($model_name)
4787 4787
     {
4788
-        $model_classname = "EEM_" . $model_name;
4789
-        if (! class_exists($model_classname)) {
4788
+        $model_classname = "EEM_".$model_name;
4789
+        if ( ! class_exists($model_classname)) {
4790 4790
             throw new EE_Error(sprintf(__(
4791 4791
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4792 4792
                 'event_espresso'
4793 4793
             ), $model_name, $model_classname));
4794 4794
         }
4795
-        return call_user_func($model_classname . "::instance");
4795
+        return call_user_func($model_classname."::instance");
4796 4796
     }
4797 4797
 
4798 4798
 
@@ -4821,7 +4821,7 @@  discard block
 block discarded – undo
4821 4821
         $belongs_to_relations = array();
4822 4822
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4823 4823
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4824
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4824
+                $belongs_to_relations[$model_name] = $relation_obj;
4825 4825
             }
4826 4826
         }
4827 4827
         return $belongs_to_relations;
@@ -4839,7 +4839,7 @@  discard block
 block discarded – undo
4839 4839
     public function related_settings_for($relation_name)
4840 4840
     {
4841 4841
         $relatedModels = $this->relation_settings();
4842
-        if (! array_key_exists($relation_name, $relatedModels)) {
4842
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4843 4843
             throw new EE_Error(
4844 4844
                 sprintf(
4845 4845
                     __(
@@ -4852,7 +4852,7 @@  discard block
 block discarded – undo
4852 4852
                 )
4853 4853
             );
4854 4854
         }
4855
-        return $relatedModels[ $relation_name ];
4855
+        return $relatedModels[$relation_name];
4856 4856
     }
4857 4857
 
4858 4858
 
@@ -4869,14 +4869,14 @@  discard block
 block discarded – undo
4869 4869
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4870 4870
     {
4871 4871
         $fieldSettings = $this->field_settings($include_db_only_fields);
4872
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4872
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4873 4873
             throw new EE_Error(sprintf(
4874 4874
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4875 4875
                 $fieldName,
4876 4876
                 get_class($this)
4877 4877
             ));
4878 4878
         }
4879
-        return $fieldSettings[ $fieldName ];
4879
+        return $fieldSettings[$fieldName];
4880 4880
     }
4881 4881
 
4882 4882
 
@@ -4890,7 +4890,7 @@  discard block
 block discarded – undo
4890 4890
     public function has_field($fieldName)
4891 4891
     {
4892 4892
         $fieldSettings = $this->field_settings(true);
4893
-        if (isset($fieldSettings[ $fieldName ])) {
4893
+        if (isset($fieldSettings[$fieldName])) {
4894 4894
             return true;
4895 4895
         }
4896 4896
         return false;
@@ -4907,7 +4907,7 @@  discard block
 block discarded – undo
4907 4907
     public function has_relation($relation_name)
4908 4908
     {
4909 4909
         $relations = $this->relation_settings();
4910
-        if (isset($relations[ $relation_name ])) {
4910
+        if (isset($relations[$relation_name])) {
4911 4911
             return true;
4912 4912
         }
4913 4913
         return false;
@@ -4945,7 +4945,7 @@  discard block
 block discarded – undo
4945 4945
                     break;
4946 4946
                 }
4947 4947
             }
4948
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4948
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4949 4949
                 throw new EE_Error(sprintf(
4950 4950
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
4951 4951
                     get_class($this)
@@ -5006,23 +5006,23 @@  discard block
 block discarded – undo
5006 5006
      */
5007 5007
     public function get_foreign_key_to($model_name)
5008 5008
     {
5009
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5009
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5010 5010
             foreach ($this->field_settings() as $field) {
5011 5011
                 if ($field instanceof EE_Foreign_Key_Field_Base
5012 5012
                     && in_array($model_name, $field->get_model_names_pointed_to())
5013 5013
                 ) {
5014
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5014
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5015 5015
                     break;
5016 5016
                 }
5017 5017
             }
5018
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5018
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5019 5019
                 throw new EE_Error(sprintf(__(
5020 5020
                     "There is no foreign key field pointing to model %s on model %s",
5021 5021
                     'event_espresso'
5022 5022
                 ), $model_name, get_class($this)));
5023 5023
             }
5024 5024
         }
5025
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5025
+        return $this->_cache_foreign_key_to_fields[$model_name];
5026 5026
     }
5027 5027
 
5028 5028
 
@@ -5038,7 +5038,7 @@  discard block
 block discarded – undo
5038 5038
     public function get_table_for_alias($table_alias)
5039 5039
     {
5040 5040
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5041
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5041
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5042 5042
     }
5043 5043
 
5044 5044
 
@@ -5057,7 +5057,7 @@  discard block
 block discarded – undo
5057 5057
                 $this->_cached_fields = array();
5058 5058
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5059 5059
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5060
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5060
+                        $this->_cached_fields[$field_name] = $field_obj;
5061 5061
                     }
5062 5062
                 }
5063 5063
             }
@@ -5068,8 +5068,8 @@  discard block
 block discarded – undo
5068 5068
             foreach ($this->_fields as $fields_corresponding_to_table) {
5069 5069
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5070 5070
                     /** @var $field_obj EE_Model_Field_Base */
5071
-                    if (! $field_obj->is_db_only_field()) {
5072
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5071
+                    if ( ! $field_obj->is_db_only_field()) {
5072
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5073 5073
                     }
5074 5074
                 }
5075 5075
             }
@@ -5110,12 +5110,12 @@  discard block
 block discarded – undo
5110 5110
                     $primary_key_field->get_qualified_column(),
5111 5111
                     $primary_key_field->get_table_column()
5112 5112
                 );
5113
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5113
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5114 5114
                     continue;
5115 5115
                 }
5116 5116
             }
5117 5117
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5118
-            if (! $classInstance) {
5118
+            if ( ! $classInstance) {
5119 5119
                 throw new EE_Error(
5120 5120
                     sprintf(
5121 5121
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5128,7 +5128,7 @@  discard block
 block discarded – undo
5128 5128
             $classInstance->set_timezone($this->_timezone);
5129 5129
             // make sure if there is any timezone setting present that we set the timezone for the object
5130 5130
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5131
-            $array_of_objects[ $key ] = $classInstance;
5131
+            $array_of_objects[$key] = $classInstance;
5132 5132
             // also, for all the relations of type BelongsTo, see if we can cache
5133 5133
             // those related models
5134 5134
             // (we could do this for other relations too, but if there are conditions
@@ -5172,9 +5172,9 @@  discard block
 block discarded – undo
5172 5172
         $results = array();
5173 5173
         if ($this->_custom_selections instanceof CustomSelects) {
5174 5174
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5175
-                if (isset($db_results_row[ $alias ])) {
5176
-                    $results[ $alias ] = $this->convertValueToDataType(
5177
-                        $db_results_row[ $alias ],
5175
+                if (isset($db_results_row[$alias])) {
5176
+                    $results[$alias] = $this->convertValueToDataType(
5177
+                        $db_results_row[$alias],
5178 5178
                         $this->_custom_selections->getDataTypeForAlias($alias)
5179 5179
                     );
5180 5180
                 }
@@ -5216,7 +5216,7 @@  discard block
 block discarded – undo
5216 5216
         $this_model_fields_and_values = array();
5217 5217
         // setup the row using default values;
5218 5218
         foreach ($this->field_settings() as $field_name => $field_obj) {
5219
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5219
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5220 5220
         }
5221 5221
         $className = $this->_get_class_name();
5222 5222
         $classInstance = EE_Registry::instance()
@@ -5234,20 +5234,20 @@  discard block
 block discarded – undo
5234 5234
      */
5235 5235
     public function instantiate_class_from_array_or_object($cols_n_values)
5236 5236
     {
5237
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5237
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5238 5238
             $cols_n_values = get_object_vars($cols_n_values);
5239 5239
         }
5240 5240
         $primary_key = null;
5241 5241
         // make sure the array only has keys that are fields/columns on this model
5242 5242
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5243
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5243
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5244
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5245 5245
         }
5246 5246
         $className = $this->_get_class_name();
5247 5247
         // check we actually found results that we can use to build our model object
5248 5248
         // if not, return null
5249 5249
         if ($this->has_primary_key_field()) {
5250
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5250
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5251 5251
                 return null;
5252 5252
             }
5253 5253
         } elseif ($this->unique_indexes()) {
@@ -5259,7 +5259,7 @@  discard block
 block discarded – undo
5259 5259
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5260 5260
         if ($primary_key) {
5261 5261
             $classInstance = $this->get_from_entity_map($primary_key);
5262
-            if (! $classInstance) {
5262
+            if ( ! $classInstance) {
5263 5263
                 $classInstance = EE_Registry::instance()
5264 5264
                                             ->load_class(
5265 5265
                                                 $className,
@@ -5292,8 +5292,8 @@  discard block
 block discarded – undo
5292 5292
      */
5293 5293
     public function get_from_entity_map($id)
5294 5294
     {
5295
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5296
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5295
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5296
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5297 5297
     }
5298 5298
 
5299 5299
 
@@ -5316,7 +5316,7 @@  discard block
 block discarded – undo
5316 5316
     public function add_to_entity_map(EE_Base_Class $object)
5317 5317
     {
5318 5318
         $className = $this->_get_class_name();
5319
-        if (! $object instanceof $className) {
5319
+        if ( ! $object instanceof $className) {
5320 5320
             throw new EE_Error(sprintf(
5321 5321
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5322 5322
                 is_object($object) ? get_class($object) : $object,
@@ -5324,7 +5324,7 @@  discard block
 block discarded – undo
5324 5324
             ));
5325 5325
         }
5326 5326
         /** @var $object EE_Base_Class */
5327
-        if (! $object->ID()) {
5327
+        if ( ! $object->ID()) {
5328 5328
             throw new EE_Error(sprintf(__(
5329 5329
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5330 5330
                 "event_espresso"
@@ -5335,7 +5335,7 @@  discard block
 block discarded – undo
5335 5335
         if ($classInstance) {
5336 5336
             return $classInstance;
5337 5337
         }
5338
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5338
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5339 5339
         return $object;
5340 5340
     }
5341 5341
 
@@ -5351,11 +5351,11 @@  discard block
 block discarded – undo
5351 5351
     public function clear_entity_map($id = null)
5352 5352
     {
5353 5353
         if (empty($id)) {
5354
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5354
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5355 5355
             return true;
5356 5356
         }
5357
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5358
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5357
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5358
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5359 5359
             return true;
5360 5360
         }
5361 5361
         return false;
@@ -5398,17 +5398,17 @@  discard block
 block discarded – undo
5398 5398
             // there is a primary key on this table and its not set. Use defaults for all its columns
5399 5399
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5400 5400
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5401
-                    if (! $field_obj->is_db_only_field()) {
5401
+                    if ( ! $field_obj->is_db_only_field()) {
5402 5402
                         // prepare field as if its coming from db
5403 5403
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5404
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5404
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5405 5405
                     }
5406 5406
                 }
5407 5407
             } else {
5408 5408
                 // the table's rows existed. Use their values
5409 5409
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5410
-                    if (! $field_obj->is_db_only_field()) {
5411
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5410
+                    if ( ! $field_obj->is_db_only_field()) {
5411
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5412 5412
                             $cols_n_values,
5413 5413
                             $field_obj->get_qualified_column(),
5414 5414
                             $field_obj->get_table_column()
@@ -5435,17 +5435,17 @@  discard block
 block discarded – undo
5435 5435
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5436 5436
         // does the field on the model relate to this column retrieved from the db?
5437 5437
         // or is it a db-only field? (not relating to the model)
5438
-        if (isset($cols_n_values[ $qualified_column ])) {
5439
-            $value = $cols_n_values[ $qualified_column ];
5440
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5441
-            $value = $cols_n_values[ $regular_column ];
5442
-        } elseif (! empty($this->foreign_key_aliases)) {
5438
+        if (isset($cols_n_values[$qualified_column])) {
5439
+            $value = $cols_n_values[$qualified_column];
5440
+        } elseif (isset($cols_n_values[$regular_column])) {
5441
+            $value = $cols_n_values[$regular_column];
5442
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5443 5443
             // no PK?  ok check if there is a foreign key alias set for this table
5444 5444
             // then check if that alias exists in the incoming data
5445 5445
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5446 5446
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5447
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5448
-                    $value = $cols_n_values[ $FK_alias ];
5447
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5448
+                    $value = $cols_n_values[$FK_alias];
5449 5449
                     list($pk_class) = explode('.', $PK_column);
5450 5450
                     $pk_model_name = "EEM_{$pk_class}";
5451 5451
                     /** @var EEM_Base $pk_model */
@@ -5489,7 +5489,7 @@  discard block
 block discarded – undo
5489 5489
                     $obj_in_map->clear_cache($relation_name, null, true);
5490 5490
                 }
5491 5491
             }
5492
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5492
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5493 5493
             return $obj_in_map;
5494 5494
         }
5495 5495
         return $this->get_one_by_ID($id);
@@ -5542,7 +5542,7 @@  discard block
 block discarded – undo
5542 5542
      */
5543 5543
     private function _get_class_name()
5544 5544
     {
5545
-        return "EE_" . $this->get_this_model_name();
5545
+        return "EE_".$this->get_this_model_name();
5546 5546
     }
5547 5547
 
5548 5548
 
@@ -5590,7 +5590,7 @@  discard block
 block discarded – undo
5590 5590
     {
5591 5591
         $className = get_class($this);
5592 5592
         $tagName = "FHEE__{$className}__{$methodName}";
5593
-        if (! has_filter($tagName)) {
5593
+        if ( ! has_filter($tagName)) {
5594 5594
             throw new EE_Error(
5595 5595
                 sprintf(
5596 5596
                     __(
@@ -5761,7 +5761,7 @@  discard block
 block discarded – undo
5761 5761
         $unique_indexes = array();
5762 5762
         foreach ($this->_indexes as $name => $index) {
5763 5763
             if ($index instanceof EE_Unique_Index) {
5764
-                $unique_indexes [ $name ] = $index;
5764
+                $unique_indexes [$name] = $index;
5765 5765
             }
5766 5766
         }
5767 5767
         return $unique_indexes;
@@ -5828,7 +5828,7 @@  discard block
 block discarded – undo
5828 5828
         $key_vals_in_combined_pk = array();
5829 5829
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5830 5830
         foreach ($key_fields as $key_field_name => $field_obj) {
5831
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5831
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5832 5832
                 return null;
5833 5833
             }
5834 5834
         }
@@ -5849,7 +5849,7 @@  discard block
 block discarded – undo
5849 5849
     {
5850 5850
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5851 5851
         foreach ($keys_it_should_have as $key) {
5852
-            if (! isset($key_vals[ $key ])) {
5852
+            if ( ! isset($key_vals[$key])) {
5853 5853
                 return false;
5854 5854
             }
5855 5855
         }
@@ -5882,8 +5882,8 @@  discard block
 block discarded – undo
5882 5882
         }
5883 5883
         // even copies obviously won't have the same ID, so remove the primary key
5884 5884
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5885
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5886
-            unset($attributes_array[ $this->primary_key_name() ]);
5885
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5886
+            unset($attributes_array[$this->primary_key_name()]);
5887 5887
         }
5888 5888
         if (isset($query_params[0])) {
5889 5889
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5905,7 +5905,7 @@  discard block
 block discarded – undo
5905 5905
      */
5906 5906
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5907 5907
     {
5908
-        if (! is_array($query_params)) {
5908
+        if ( ! is_array($query_params)) {
5909 5909
             EE_Error::doing_it_wrong(
5910 5910
                 'EEM_Base::get_one_copy',
5911 5911
                 sprintf(
@@ -5955,7 +5955,7 @@  discard block
 block discarded – undo
5955 5955
      */
5956 5956
     private function _prepare_operator_for_sql($operator_supplied)
5957 5957
     {
5958
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5958
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5959 5959
             : null;
5960 5960
         if ($sql_operator) {
5961 5961
             return $sql_operator;
@@ -6046,7 +6046,7 @@  discard block
 block discarded – undo
6046 6046
         $objs = $this->get_all($query_params);
6047 6047
         $names = array();
6048 6048
         foreach ($objs as $obj) {
6049
-            $names[ $obj->ID() ] = $obj->name();
6049
+            $names[$obj->ID()] = $obj->name();
6050 6050
         }
6051 6051
         return $names;
6052 6052
     }
@@ -6067,7 +6067,7 @@  discard block
 block discarded – undo
6067 6067
      */
6068 6068
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6069 6069
     {
6070
-        if (! $this->has_primary_key_field()) {
6070
+        if ( ! $this->has_primary_key_field()) {
6071 6071
             if (WP_DEBUG) {
6072 6072
                 EE_Error::add_error(
6073 6073
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6080,7 +6080,7 @@  discard block
 block discarded – undo
6080 6080
         $IDs = array();
6081 6081
         foreach ($model_objects as $model_object) {
6082 6082
             $id = $model_object->ID();
6083
-            if (! $id) {
6083
+            if ( ! $id) {
6084 6084
                 if ($filter_out_empty_ids) {
6085 6085
                     continue;
6086 6086
                 }
@@ -6130,22 +6130,22 @@  discard block
 block discarded – undo
6130 6130
     {
6131 6131
         EEM_Base::verify_is_valid_cap_context($context);
6132 6132
         // check if we ought to run the restriction generator first
6133
-        if (isset($this->_cap_restriction_generators[ $context ])
6134
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6135
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6133
+        if (isset($this->_cap_restriction_generators[$context])
6134
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6135
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6136 6136
         ) {
6137
-            $this->_cap_restrictions[ $context ] = array_merge(
6138
-                $this->_cap_restrictions[ $context ],
6139
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6137
+            $this->_cap_restrictions[$context] = array_merge(
6138
+                $this->_cap_restrictions[$context],
6139
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6140 6140
             );
6141 6141
         }
6142 6142
         // and make sure we've finalized the construction of each restriction
6143
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6143
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6144 6144
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6145 6145
                 $where_conditions_obj->_finalize_construct($this);
6146 6146
             }
6147 6147
         }
6148
-        return $this->_cap_restrictions[ $context ];
6148
+        return $this->_cap_restrictions[$context];
6149 6149
     }
6150 6150
 
6151 6151
 
@@ -6175,10 +6175,10 @@  discard block
 block discarded – undo
6175 6175
         $missing_caps = array();
6176 6176
         $cap_restrictions = $this->cap_restrictions($context);
6177 6177
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6178
-            if (! EE_Capabilities::instance()
6179
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6178
+            if ( ! EE_Capabilities::instance()
6179
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6180 6180
             ) {
6181
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6181
+                $missing_caps[$cap] = $restriction_if_no_cap;
6182 6182
             }
6183 6183
         }
6184 6184
         return $missing_caps;
@@ -6213,8 +6213,8 @@  discard block
 block discarded – undo
6213 6213
     public function cap_action_for_context($context)
6214 6214
     {
6215 6215
         $mapping = $this->cap_contexts_to_cap_action_map();
6216
-        if (isset($mapping[ $context ])) {
6217
-            return $mapping[ $context ];
6216
+        if (isset($mapping[$context])) {
6217
+            return $mapping[$context];
6218 6218
         }
6219 6219
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6220 6220
             return $action;
@@ -6331,7 +6331,7 @@  discard block
 block discarded – undo
6331 6331
     {
6332 6332
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6333 6333
             if ($query_param_key === $logic_query_param_key
6334
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6334
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6335 6335
             ) {
6336 6336
                 return true;
6337 6337
             }
@@ -6384,7 +6384,7 @@  discard block
 block discarded – undo
6384 6384
         if ($password_field instanceof EE_Password_Field) {
6385 6385
             $field_names = $password_field->protectedFields();
6386 6386
             foreach ($field_names as $field_name) {
6387
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6387
+                $fields[$field_name] = $this->field_settings_for($field_name);
6388 6388
             }
6389 6389
         }
6390 6390
         return $fields;
@@ -6409,7 +6409,7 @@  discard block
 block discarded – undo
6409 6409
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6410 6410
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6411 6411
         }
6412
-        if (!is_array($model_obj_or_fields_n_values)) {
6412
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6413 6413
             throw new UnexpectedEntityException(
6414 6414
                 $model_obj_or_fields_n_values,
6415 6415
                 'EE_Base_Class',
@@ -6484,7 +6484,7 @@  discard block
 block discarded – undo
6484 6484
                 )
6485 6485
             );
6486 6486
         }
6487
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6487
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6488 6488
     }
6489 6489
 
6490 6490
     /**
Please login to merge, or discard this patch.