Completed
Branch models-cleanup/main (de94a1)
by
unknown
14:03 queued 11:37
created
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6562 added lines, -6562 removed lines patch added patch discarded remove patch
@@ -37,6568 +37,6568 @@
 block discarded – undo
37 37
 abstract class EEM_Base extends EE_Base implements ResettableInterface
38 38
 {
39 39
 
40
-    /**
41
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
-     */
43
-    const caps_read       = 'read';
44
-
45
-    const caps_read_admin = 'read_admin';
46
-
47
-    const caps_edit       = 'edit';
48
-
49
-    const caps_delete     = 'delete';
50
-
51
-
52
-    /**
53
-     * constant used to show EEM_Base has not yet verified the db on this http request
54
-     */
55
-    const db_verified_none = 0;
56
-
57
-    /**
58
-     * constant used to show EEM_Base has verified the EE core db on this http request,
59
-     * but not the addons' dbs
60
-     */
61
-    const db_verified_core = 1;
62
-
63
-    /**
64
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
-     * the EE core db too)
66
-     */
67
-    const db_verified_addons = 2;
68
-
69
-    /**
70
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
-     *        registrations for non-trashed tickets for non-trashed datetimes)
73
-     */
74
-    const default_where_conditions_all = 'all';
75
-
76
-    /**
77
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
-     *        models which share tables with other models, this can return data for the wrong model.
82
-     */
83
-    const default_where_conditions_this_only = 'this_model_only';
84
-
85
-    /**
86
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
-     */
90
-    const default_where_conditions_others_only = 'other_models_only';
91
-
92
-    /**
93
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
96
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
-     *        (regardless of whether those events and venues are trashed)
98
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
-     *        events.
100
-     */
101
-    const default_where_conditions_minimum_all = 'minimum';
102
-
103
-    /**
104
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
-     *        not)
108
-     */
109
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
-
111
-    /**
112
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
-     *        it's possible it will return table entries for other models. You should use
115
-     *        EEM_Base::default_where_conditions_minimum_all instead.
116
-     */
117
-    const default_where_conditions_none = 'none';
118
-
119
-    /**
120
-     * when $_values_already_prepared_by_model_object equals this, we assume
121
-     * the data is just like form input that needs to have the model fields'
122
-     * prepare_for_set and prepare_for_use_in_db called on it
123
-     */
124
-    const not_prepared_by_model_object = 0;
125
-
126
-    /**
127
-     * when $_values_already_prepared_by_model_object equals this, we
128
-     * assume this value is coming from a model object and doesn't need to have
129
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
130
-     */
131
-    const prepared_by_model_object = 1;
132
-
133
-    /**
134
-     * when $_values_already_prepared_by_model_object equals this, we assume
135
-     * the values are already to be used in the database (ie no processing is done
136
-     * on them by the model's fields)
137
-     */
138
-    const prepared_for_use_in_db = 2;
139
-
140
-    /**
141
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
-     * They almost always WILL NOT, but it's not necessarily a requirement.
144
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
-     *
146
-     * @var boolean
147
-     */
148
-    private $_values_already_prepared_by_model_object = 0;
149
-
150
-
151
-    /**
152
-     * @var string
153
-     */
154
-    protected $singular_item = 'Item';
155
-
156
-    /**
157
-     * @var string
158
-     */
159
-    protected $plural_item = 'Items';
160
-
161
-    /**
162
-     * array of EE_Table objects for defining which tables comprise this model.
163
-     *
164
-     * @type EE_Table_Base[] $_tables
165
-     */
166
-    protected $_tables;
167
-
168
-    /**
169
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
-     *
173
-     * @var EE_Model_Field_Base[][] $_fields
174
-     */
175
-    protected $_fields;
176
-
177
-    /**
178
-     * array of different kinds of relations
179
-     *
180
-     * @var EE_Model_Relation_Base[] $_model_relations
181
-     */
182
-    protected $_model_relations;
183
-
184
-    /**
185
-     * @var EE_Index[] $_indexes
186
-     */
187
-    protected $_indexes = [];
188
-
189
-    /**
190
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
191
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
-     * by setting the same columns as used in these queries in the query yourself.
193
-     *
194
-     * @var EE_Default_Where_Conditions
195
-     */
196
-    protected $_default_where_conditions_strategy;
197
-
198
-    /**
199
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
-     * This is particularly useful when you want something between 'none' and 'default'
201
-     *
202
-     * @var EE_Default_Where_Conditions
203
-     */
204
-    protected $_minimum_where_conditions_strategy;
205
-
206
-    /**
207
-     * String describing how to find the "owner" of this model's objects.
208
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
-     * But when there isn't, this indicates which related model, or transiently-related model,
210
-     * has the foreign key to the wp_users table.
211
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
-     * related to events, and events have a foreign key to wp_users.
213
-     * On EEM_Transaction, this would be 'Transaction.Event'
214
-     *
215
-     * @var string
216
-     */
217
-    protected $_model_chain_to_wp_user = '';
218
-
219
-    /**
220
-     * String describing how to find the model with a password controlling access to this model. This property has the
221
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
-     * This value is the path of models to follow to arrive at the model with the password field.
223
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
-     * model with a password that should affect reading this on the front-end.
225
-     * Eg this is an empty string for the Event model because it has a password.
226
-     * This is null for the Registration model, because its event's password has no bearing on whether
227
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
-     * should hide tickets for datetimes for events that have a password set.
230
-     *
231
-     * @var string |null
232
-     */
233
-    protected $model_chain_to_password = null;
234
-
235
-    /**
236
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
-     * don't need it (particularly CPT models)
238
-     *
239
-     * @var bool
240
-     */
241
-    protected $_ignore_where_strategy = false;
242
-
243
-    /**
244
-     * String used in caps relating to this model. Eg, if the caps relating to this
245
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
-     *
247
-     * @var string. If null it hasn't been initialized yet. If false then we
248
-     * have indicated capabilities don't apply to this
249
-     */
250
-    protected $_caps_slug = null;
251
-
252
-    /**
253
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
-     * and next-level keys are capability names, and values are a
255
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
-     * they specify which context to use (ie, frontend, backend, edit or delete)
257
-     * and then each capability in the corresponding sub-array that they're missing
258
-     * adds the where conditions onto the query.
259
-     *
260
-     * @var array
261
-     */
262
-    protected $_cap_restrictions = [
263
-        self::caps_read       => [],
264
-        self::caps_read_admin => [],
265
-        self::caps_edit       => [],
266
-        self::caps_delete     => [],
267
-    ];
268
-
269
-    /**
270
-     * Array defining which cap restriction generators to use to create default
271
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
272
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
-     * automatically set this to false (not just null).
275
-     *
276
-     * @var EE_Restriction_Generator_Base[]
277
-     */
278
-    protected $_cap_restriction_generators = [];
279
-
280
-    /**
281
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
-     * maps to 'read' because when looking for relevant permissions we're going to use
284
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
285
-     *
286
-     * @var array
287
-     */
288
-    protected $_cap_contexts_to_cap_action_map = [
289
-        self::caps_read       => 'read',
290
-        self::caps_read_admin => 'read',
291
-        self::caps_edit       => 'edit',
292
-        self::caps_delete     => 'delete',
293
-    ];
294
-
295
-    /**
296
-     * Timezone
297
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
-     * EE_Datetime_Field data type will have access to it.
301
-     *
302
-     * @var string
303
-     */
304
-    protected $_timezone;
305
-
306
-
307
-    /**
308
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
-     * multisite.
310
-     *
311
-     * @var int
312
-     */
313
-    protected static $_model_query_blog_id;
314
-
315
-    /**
316
-     * A copy of _fields, except the array keys are the model names pointed to by
317
-     * the field
318
-     *
319
-     * @var EE_Model_Field_Base[]
320
-     */
321
-    private $_cache_foreign_key_to_fields = [];
322
-
323
-    /**
324
-     * Cached list of all the fields on the model, indexed by their name
325
-     *
326
-     * @var EE_Model_Field_Base[]
327
-     */
328
-    private $_cached_fields = null;
329
-
330
-    /**
331
-     * Cached list of all the fields on the model, except those that are
332
-     * marked as only pertinent to the database
333
-     *
334
-     * @var EE_Model_Field_Base[]
335
-     */
336
-    private $_cached_fields_non_db_only = null;
337
-
338
-    /**
339
-     * A cached reference to the primary key for quick lookup
340
-     *
341
-     * @var EE_Model_Field_Base
342
-     */
343
-    private $_primary_key_field = null;
344
-
345
-    /**
346
-     * Flag indicating whether this model has a primary key or not
347
-     *
348
-     * @var boolean
349
-     */
350
-    protected $_has_primary_key_field = null;
351
-
352
-    /**
353
-     * array in the format:  [ FK alias => full PK ]
354
-     * where keys are local column name aliases for foreign keys
355
-     * and values are the fully qualified column name for the primary key they represent
356
-     *  ex:
357
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
-     *
359
-     * @var array $foreign_key_aliases
360
-     */
361
-    protected $foreign_key_aliases = [];
362
-
363
-    /**
364
-     * Whether or not this model is based off a table in WP core only (CPTs should set
365
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
-     * This should be true for models that deal with data that should exist independent of EE.
367
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
369
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
371
-     *
372
-     * @var boolean
373
-     */
374
-    protected $_wp_core_model = false;
375
-
376
-    /**
377
-     * @var bool stores whether this model has a password field or not.
378
-     * null until initialized by hasPasswordField()
379
-     */
380
-    protected $has_password_field;
381
-
382
-    /**
383
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
-     */
385
-    protected $password_field;
386
-
387
-    /**
388
-     *    List of valid operators that can be used for querying.
389
-     * The keys are all operators we'll accept, the values are the real SQL
390
-     * operators used
391
-     *
392
-     * @var array
393
-     */
394
-    protected $_valid_operators = [
395
-        '='           => '=',
396
-        '<='          => '<=',
397
-        '<'           => '<',
398
-        '>='          => '>=',
399
-        '>'           => '>',
400
-        '!='          => '!=',
401
-        'LIKE'        => 'LIKE',
402
-        'like'        => 'LIKE',
403
-        'NOT_LIKE'    => 'NOT LIKE',
404
-        'not_like'    => 'NOT LIKE',
405
-        'NOT LIKE'    => 'NOT LIKE',
406
-        'not like'    => 'NOT LIKE',
407
-        'IN'          => 'IN',
408
-        'in'          => 'IN',
409
-        'NOT_IN'      => 'NOT IN',
410
-        'not_in'      => 'NOT IN',
411
-        'NOT IN'      => 'NOT IN',
412
-        'not in'      => 'NOT IN',
413
-        'between'     => 'BETWEEN',
414
-        'BETWEEN'     => 'BETWEEN',
415
-        'IS_NOT_NULL' => 'IS NOT NULL',
416
-        'is_not_null' => 'IS NOT NULL',
417
-        'IS NOT NULL' => 'IS NOT NULL',
418
-        'is not null' => 'IS NOT NULL',
419
-        'IS_NULL'     => 'IS NULL',
420
-        'is_null'     => 'IS NULL',
421
-        'IS NULL'     => 'IS NULL',
422
-        'is null'     => 'IS NULL',
423
-        'REGEXP'      => 'REGEXP',
424
-        'regexp'      => 'REGEXP',
425
-        'NOT_REGEXP'  => 'NOT REGEXP',
426
-        'not_regexp'  => 'NOT REGEXP',
427
-        'NOT REGEXP'  => 'NOT REGEXP',
428
-        'not regexp'  => 'NOT REGEXP',
429
-    ];
430
-
431
-    /**
432
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
-     *
434
-     * @var array
435
-     */
436
-    protected $_in_style_operators = ['IN', 'NOT IN'];
437
-
438
-    /**
439
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
-     * '12-31-2012'"
441
-     *
442
-     * @var array
443
-     */
444
-    protected $_between_style_operators = ['BETWEEN'];
445
-
446
-    /**
447
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
-
453
-    /**
454
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
-     * on a join table.
456
-     *
457
-     * @var array
458
-     */
459
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
-
461
-    /**
462
-     * Allowed values for $query_params['order'] for ordering in queries
463
-     *
464
-     * @var array
465
-     */
466
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
-
468
-    /**
469
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
471
-     *
472
-     * @var array
473
-     */
474
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
-
476
-    /**
477
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
479
-     *
480
-     * @var array
481
-     */
482
-    private $_allowed_query_params = [
483
-        0,
484
-        'limit',
485
-        'order_by',
486
-        'group_by',
487
-        'having',
488
-        'force_join',
489
-        'order',
490
-        'on_join_limit',
491
-        'default_where_conditions',
492
-        'caps',
493
-        'extra_selects',
494
-        'exclude_protected',
495
-    ];
496
-
497
-    /**
498
-     * All the data types that can be used in $wpdb->prepare statements.
499
-     *
500
-     * @var array
501
-     */
502
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
-
504
-    /**
505
-     * @var EE_Registry $EE
506
-     */
507
-    protected $EE = null;
508
-
509
-
510
-    /**
511
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
-     *
513
-     * @var int
514
-     */
515
-    protected $_show_next_x_db_queries = 0;
516
-
517
-    /**
518
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
-     * WHERE, GROUP_BY, etc.
521
-     *
522
-     * @var CustomSelects
523
-     */
524
-    protected $_custom_selections = [];
525
-
526
-    /**
527
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
-     * caches every model object we've fetched from the DB on this request
529
-     *
530
-     * @var array
531
-     */
532
-    protected $_entity_map;
533
-
534
-    /**
535
-     * @var LoaderInterface $loader
536
-     */
537
-    private static $loader;
538
-
539
-    /**
540
-     * indicates whether an EEM_Base child has already re-verified the DB
541
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
542
-     * looking like EEM_Base::db_verified_*
543
-     *
544
-     * @var int - 0 = none, 1 = core, 2 = addons
545
-     */
546
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
547
-
548
-
549
-    /**
550
-     * About all child constructors:
551
-     * they should define the _tables, _fields and _model_relations arrays.
552
-     * Should ALWAYS be called after child constructor.
553
-     * In order to make the child constructors to be as simple as possible, this parent constructor
554
-     * finalizes constructing all the object's attributes.
555
-     * Generally, rather than requiring a child to code
556
-     * $this->_tables = array(
557
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
-     *        ...);
559
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
-     * each EE_Table has a function to set the table's alias after the constructor, using
561
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
-     * do something similar.
563
-     *
564
-     * @param string $timezone
565
-     * @throws EE_Error
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blog id for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                /** @var $table_obj EE_Secondary_Table */
599
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
-            }
601
-        }
602
-        /**
603
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
-         * EE_Register_Model_Extension
605
-         *
606
-         * @param EE_Model_Field_Base[] $_fields
607
-         */
608
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
-        $this->_invalidate_field_caches();
610
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
612
-                throw new EE_Error(
613
-                    sprintf(
614
-                        esc_html__(
615
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
-                            'event_espresso'
617
-                        ),
618
-                        $table_alias,
619
-                        implode(",", $this->_fields)
620
-                    )
621
-                );
622
-            }
623
-            foreach ($fields_for_table as $field_name => $field_obj) {
624
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
-                // primary key field base has a slightly different _construct_finalize
626
-                /** @var $field_obj EE_Model_Field_Base */
627
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
-            }
629
-        }
630
-        // everything is related to Extra_Meta
631
-        if (get_class($this) !== 'EEM_Extra_Meta') {
632
-            // make extra meta related to everything, but don't block deleting things just
633
-            // because they have related extra meta info. For now just orphan those extra meta
634
-            // in the future we should automatically delete them
635
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
-        }
637
-        // and change logs
638
-        if (get_class($this) !== 'EEM_Change_Log') {
639
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
-        }
641
-        /**
642
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
-         * EE_Register_Model_Extension
644
-         *
645
-         * @param EE_Model_Relation_Base[] $_model_relations
646
-         */
647
-        $this->_model_relations = (array)apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
649
-            $this->_model_relations
650
-        );
651
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
652
-            /** @var $relation_obj EE_Model_Relation_Base */
653
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
-        }
655
-        foreach ($this->_indexes as $index_name => $index_obj) {
656
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
-        }
658
-        $this->set_timezone($timezone);
659
-        // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
661
-            // nothing was set during child constructor, so set default
662
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
-        }
664
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
666
-            // nothing was set during child constructor, so set default
667
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
-        }
669
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
671
-        // to indicate to NOT set it, set it to the logical default
672
-        if ($this->_caps_slug === null) {
673
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
-        }
675
-        // initialize the standard cap restriction generators if none were specified by the child constructor
676
-        if (! empty($this->_cap_restriction_generators)) {
677
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
-                        new EE_Restriction_Generator_Protected(),
682
-                        $cap_context,
683
-                        $this
684
-                    );
685
-                }
686
-            }
687
-        // }
688
-        // if ($this->_cap_restriction_generators !== false) {
689
-        // if there are cap restriction generators, use them to make the default cap restrictions
690
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
692
-                    continue;
693
-                }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
-                    throw new EE_Error(
696
-                        sprintf(
697
-                            esc_html__(
698
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
699
-                                'event_espresso'
700
-                            ),
701
-                            $context,
702
-                            $this->get_this_model_name()
703
-                        )
704
-                    );
705
-                }
706
-                $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
708
-                    $generator_object->_construct_finalize($this, $action);
709
-                }
710
-            }
711
-        }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
713
-    }
714
-
715
-
716
-    /**
717
-     * Used to set the $_model_query_blog_id static property.
718
-     *
719
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
-     *                      value for get_current_blog_id() will be used.
721
-     */
722
-    public static function set_model_query_blog_id($blog_id = 0)
723
-    {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
725
-    }
726
-
727
-
728
-    /**
729
-     * Returns whatever is set as the internal $model_query_blog_id.
730
-     *
731
-     * @return int
732
-     */
733
-    public static function get_model_query_blog_id()
734
-    {
735
-        return EEM_Base::$_model_query_blog_id;
736
-    }
737
-
738
-
739
-    /**
740
-     * This function is a singleton method used to instantiate the Espresso_model object
741
-     *
742
-     * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
-     *                                (and any incoming timezone data that gets saved).
744
-     *                                Note this just sends the timezone info to the date time model field objects.
745
-     *                                Default is NULL
746
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
-     * @return static (as in the concrete child class)
748
-     * @throws EE_Error
749
-     * @throws InvalidArgumentException
750
-     * @throws InvalidDataTypeException
751
-     * @throws InvalidInterfaceException
752
-     */
753
-    public static function instance($timezone = '')
754
-    {
755
-        // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
757
-            // instantiate Espresso_model
758
-            static::$_instance = new static(
759
-                $timezone,
760
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
-            );
762
-        }
763
-        // Espresso model object
764
-        return static::$_instance;
765
-    }
766
-
767
-
768
-    /**
769
-     * resets the model and returns it
770
-     *
771
-     * @param string $timezone
772
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
-     * all its properties reset; if it wasn't instantiated, returns null)
774
-     * @throws EE_Error
775
-     * @throws ReflectionException
776
-     * @throws InvalidArgumentException
777
-     * @throws InvalidDataTypeException
778
-     * @throws InvalidInterfaceException
779
-     */
780
-    public static function reset($timezone = '')
781
-    {
782
-        if (static::$_instance instanceof EEM_Base) {
783
-            // let's try to NOT swap out the current instance for a new one
784
-            // because if someone has a reference to it, we can't remove their reference
785
-            // so it's best to keep using the same reference, but change the original object
786
-            // reset all its properties to their original values as defined in the class
787
-            $r                 = new ReflectionClass(get_class(static::$_instance));
788
-            $static_properties = $r->getStaticProperties();
789
-            foreach ($r->getDefaultProperties() as $property => $value) {
790
-                // don't set instance to null like it was originally,
791
-                // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
793
-                    static::$_instance->{$property} = $value;
794
-                }
795
-            }
796
-            EEH_DTT_Helper::resetDefaultTimezoneString();
797
-            // and then directly call its constructor again, like we would if we were creating a new one
798
-            static::$_instance->__construct(
799
-                $timezone,
800
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
-            );
802
-            return static::instance();
803
-        }
804
-        return null;
805
-    }
806
-
807
-
808
-    /**
809
-     * @return LoaderInterface
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     */
814
-    private static function getLoader()
815
-    {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
817
-            EEM_Base::$loader = LoaderFactory::getLoader();
818
-        }
819
-        return EEM_Base::$loader;
820
-    }
821
-
822
-
823
-    /**
824
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
-     *
826
-     * @param boolean $translated return localized strings or JUST the array.
827
-     * @return array
828
-     * @throws EE_Error
829
-     * @throws InvalidArgumentException
830
-     * @throws InvalidDataTypeException
831
-     * @throws InvalidInterfaceException
832
-     * @throws ReflectionException
833
-     */
834
-    public function status_array($translated = false)
835
-    {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
837
-            return [];
838
-        }
839
-        $model_name   = $this->get_this_model_name();
840
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
-        $statuses      = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
-        $status_array = [];
843
-        foreach ($statuses as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
845
-        }
846
-        return $translated
847
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
-            : $status_array;
849
-    }
850
-
851
-
852
-    /**
853
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
-     *
855
-     * @param array $query_params             see github link below for more info
856
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
-     *                                        EEM_Transaction::instance()->get_all( array( array(
861
-     *                                        'OR'=>array(
862
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
-     *                                        )
865
-     *                                        ),
866
-     *                                        'limit'=>10,
867
-     *                                        'group_by'=>'TXN_ID'
868
-     *                                        ));
869
-     *                                        get all the answers to the question titled "shirt size" for event with id
870
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
-     *                                        'Question.QST_display_text'=>'shirt size',
872
-     *                                        'Registration.Event.EVT_ID'=>12
873
-     *                                        ),
874
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
875
-     *                                        ));
876
-     * @throws EE_Error
877
-     * @throws ReflectionException
878
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
-     *                                        or if you have the development copy of EE you can view this at the path:
880
-     *                                        /docs/G--Model-System/model-query-params.md
881
-     */
882
-    public function get_all($query_params = [])
883
-    {
884
-        if (
885
-            isset($query_params['limit'])
886
-            && ! isset($query_params['group_by'])
887
-        ) {
888
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
-        }
890
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
-    }
892
-
893
-
894
-    /**
895
-     * Modifies the query parameters so we only get back model objects
896
-     * that "belong" to the current user
897
-     *
898
-     * @param array $query_params see github link below for more info
899
-     * @return array
900
-     * @throws ReflectionException
901
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     */
903
-    public function alter_query_params_to_only_include_mine($query_params = [])
904
-    {
905
-        $wp_user_field_name = $this->wp_user_field_name();
906
-        if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
-        }
909
-        return $query_params;
910
-    }
911
-
912
-
913
-    /**
914
-     * Returns the name of the field's name that points to the WP_User table
915
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
-     * foreign key to the WP_User table)
917
-     *
918
-     * @return string|boolean string on success, boolean false when there is no
919
-     * foreign key to the WP_User table
920
-     * @throws ReflectionException
921
-     */
922
-    public function wp_user_field_name()
923
-    {
924
-        try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
926
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
-                $last_model_name              = end($models_to_follow_to_wp_users);
928
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
-            } else {
931
-                $model_with_fk_to_wp_users = $this;
932
-                $model_chain_to_wp_user    = '';
933
-            }
934
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
936
-        } catch (EE_Error $e) {
937
-            return false;
938
-        }
939
-    }
940
-
941
-
942
-    /**
943
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
944
-     * (or transiently-related model) has a foreign key to the wp_users table;
945
-     * useful for finding if model objects of this type are 'owned' by the current user.
946
-     * This is an empty string when the foreign key is on this model and when it isn't,
947
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
948
-     * (or transiently-related model)
949
-     *
950
-     * @return string
951
-     */
952
-    public function model_chain_to_wp_user()
953
-    {
954
-        return $this->_model_chain_to_wp_user;
955
-    }
956
-
957
-
958
-    /**
959
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
-     * like how registrations don't have a foreign key to wp_users, but the
961
-     * events they are for are), or is unrelated to wp users.
962
-     * generally available
963
-     *
964
-     * @return boolean
965
-     */
966
-    public function is_owned()
967
-    {
968
-        if ($this->model_chain_to_wp_user()) {
969
-            return true;
970
-        }
971
-        try {
972
-            $this->get_foreign_key_to('WP_User');
973
-            return true;
974
-        } catch (EE_Error $e) {
975
-            return false;
976
-        }
977
-    }
978
-
979
-
980
-    /**
981
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
-     * the model)
984
-     *
985
-     * @param array  $query_params
986
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
-     *                                  fields on the model, and the models we joined to in the query. However, you can
989
-     *                                  override this and set the select to "*", or a specific column name, like
990
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
-     *                                  the aliases used to refer to this selection, and values are to be
993
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws ReflectionException
999
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
-     */
1001
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
-    {
1003
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
-        $select_expressions       = $columns_to_select === null
1006
-            ? $this->_construct_default_select_sql($model_query_info)
1007
-            : '';
1008
-        if ($this->_custom_selections instanceof CustomSelects) {
1009
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
-            $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1012
-                : $custom_expressions;
1013
-        }
1014
-
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
-     * method of including extra select information.
1024
-     *
1025
-     * @param array             $query_params
1026
-     * @param null|array|string $columns_to_select
1027
-     * @return null|CustomSelects
1028
-     * @throws InvalidArgumentException
1029
-     */
1030
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
-    {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
-            return null;
1034
-        }
1035
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
-        return new CustomSelects($selects);
1038
-    }
1039
-
1040
-
1041
-    /**
1042
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1043
-     * but you can use the model query params to more easily
1044
-     * take care of joins, field preparation etc.
1045
-     *
1046
-     * @param array  $query_params
1047
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1050
-     *                                  override this and set the select to "*", or a specific column name, like
1051
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
-     *                                  the aliases used to refer to this selection, and values are to be
1054
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
-     * @throws EE_Error
1058
-     * @throws ReflectionException
1059
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
-     */
1061
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
-    {
1063
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * For creating a custom select statement
1069
-     *
1070
-     * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
-     *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
-     *                                        selection SQL, and 1=>is the datatype
1073
-     * @return string
1074
-     * @throws EE_Error
1075
-     */
1076
-    private function _construct_select_from_input($columns_to_select)
1077
-    {
1078
-        if (is_array($columns_to_select)) {
1079
-            $select_sql_array = [];
1080
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype,
1089
-                            $alias
1090
-                        )
1091
-                    );
1092
-                }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
-                    throw new EE_Error(
1095
-                        sprintf(
1096
-                            esc_html__(
1097
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
-                                'event_espresso'
1099
-                            ),
1100
-                            $selection_and_datatype[1],
1101
-                            $selection_and_datatype[0],
1102
-                            $alias,
1103
-                            implode(', ', $this->_valid_wpdb_data_types)
1104
-                        )
1105
-                    );
1106
-                }
1107
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
-            }
1109
-            $columns_to_select_string = implode(', ', $select_sql_array);
1110
-        } else {
1111
-            $columns_to_select_string = $columns_to_select;
1112
-        }
1113
-        return $columns_to_select_string;
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
-     *
1120
-     * @return string
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function primary_key_name()
1124
-    {
1125
-        return $this->get_primary_key_field()->get_name();
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
-     * If there is no primary key on this model, $id is treated as primary key string
1132
-     *
1133
-     * @param mixed $id int or string, depending on the type of the model's primary key
1134
-     * @return EE_Base_Class
1135
-     * @throws EE_Error
1136
-     * @throws ReflectionException
1137
-     */
1138
-    public function get_one_by_ID($id)
1139
-    {
1140
-        if ($this->get_from_entity_map($id)) {
1141
-            return $this->get_from_entity_map($id);
1142
-        }
1143
-        $model_object = $this->get_one(
1144
-            $this->alter_query_params_to_restrict_by_ID(
1145
-                $id,
1146
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
-            )
1148
-        );
1149
-        $className = $this->_get_class_name();
1150
-        if ($model_object instanceof $className) {
1151
-            // make sure valid objects get added to the entity map
1152
-            // so that the next call to this method doesn't trigger another trip to the db
1153
-            $this->add_to_entity_map($model_object);
1154
-        }
1155
-        return $model_object;
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * Alters query parameters to only get items with this ID are returned.
1161
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1162
-     * or could just be a simple primary key ID
1163
-     *
1164
-     * @param int   $id
1165
-     * @param array $query_params see github link below for more info
1166
-     * @return array of normal query params,
1167
-     * @throws EE_Error
1168
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1169
-     */
1170
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1171
-    {
1172
-        if (! isset($query_params[0])) {
1173
-            $query_params[0] = [];
1174
-        }
1175
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1176
-        if ($conditions_from_id === null) {
1177
-            $query_params[0][ $this->primary_key_name() ] = $id;
1178
-        } else {
1179
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1180
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1181
-        }
1182
-        return $query_params;
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1188
-     * array. If no item is found, null is returned.
1189
-     *
1190
-     * @param array $query_params like EEM_Base's $query_params variable.
1191
-     * @return EE_Base_Class|null
1192
-     * @throws EE_Error
1193
-     * @throws ReflectionException
1194
-     */
1195
-    public function get_one(array $query_params = [])
1196
-    {
1197
-        if (! is_array($query_params)) {
1198
-            EE_Error::doing_it_wrong(
1199
-                'EEM_Base::get_one',
1200
-                sprintf(
1201
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1202
-                    gettype($query_params)
1203
-                ),
1204
-                '4.6.0'
1205
-            );
1206
-            $query_params = [];
1207
-        }
1208
-        $query_params['limit'] = 1;
1209
-        $items                 = $this->get_all($query_params);
1210
-        if (empty($items)) {
1211
-            return null;
1212
-        }
1213
-        return array_shift($items);
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * Returns the next x number of items in sequence from the given value as
1219
-     * found in the database matching the given query conditions.
1220
-     *
1221
-     * @param mixed $current_field_value    Value used for the reference point.
1222
-     * @param null  $field_to_order_by      What field is used for the
1223
-     *                                      reference point.
1224
-     * @param int   $limit                  How many to return.
1225
-     * @param array $query_params           Extra conditions on the query.
1226
-     * @param null  $columns_to_select      If left null, then an array of
1227
-     *                                      EE_Base_Class objects is returned,
1228
-     *                                      otherwise you can indicate just the
1229
-     *                                      columns you want returned.
1230
-     * @return EE_Base_Class[]|array
1231
-     * @throws EE_Error
1232
-     * @throws ReflectionException
1233
-     */
1234
-    public function next_x(
1235
-        $current_field_value,
1236
-        $field_to_order_by = null,
1237
-        $limit = 1,
1238
-        $query_params = [],
1239
-        $columns_to_select = null
1240
-    ) {
1241
-        return $this->_get_consecutive(
1242
-            $current_field_value,
1243
-            '>',
1244
-            $field_to_order_by,
1245
-            $limit,
1246
-            $query_params,
1247
-            $columns_to_select
1248
-        );
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Returns the previous x number of items in sequence from the given value
1254
-     * as found in the database matching the given query conditions.
1255
-     *
1256
-     * @param mixed $current_field_value    Value used for the reference point.
1257
-     * @param null  $field_to_order_by      What field is used for the
1258
-     *                                      reference point.
1259
-     * @param int   $limit                  How many to return.
1260
-     * @param array $query_params           Extra conditions on the query.
1261
-     * @param null  $columns_to_select      If left null, then an array of
1262
-     *                                      EE_Base_Class objects is returned,
1263
-     *                                      otherwise you can indicate just the
1264
-     *                                      columns you want returned.
1265
-     * @return EE_Base_Class[]|array
1266
-     * @throws EE_Error
1267
-     * @throws ReflectionException
1268
-     */
1269
-    public function previous_x(
1270
-        $current_field_value,
1271
-        $field_to_order_by = null,
1272
-        $limit = 1,
1273
-        $query_params = [],
1274
-        $columns_to_select = null
1275
-    ) {
1276
-        return $this->_get_consecutive(
1277
-            $current_field_value,
1278
-            '<',
1279
-            $field_to_order_by,
1280
-            $limit,
1281
-            $query_params,
1282
-            $columns_to_select
1283
-        );
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * Returns the next item in sequence from the given value as found in the
1289
-     * database matching the given query conditions.
1290
-     *
1291
-     * @param mixed $current_field_value    Value used for the reference point.
1292
-     * @param null  $field_to_order_by      What field is used for the
1293
-     *                                      reference point.
1294
-     * @param array $query_params           Extra conditions on the query.
1295
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1296
-     *                                      object is returned, otherwise you
1297
-     *                                      can indicate just the columns you
1298
-     *                                      want and a single array indexed by
1299
-     *                                      the columns will be returned.
1300
-     * @return EE_Base_Class|null|array()
1301
-     * @throws EE_Error
1302
-     * @throws ReflectionException
1303
-     */
1304
-    public function next(
1305
-        $current_field_value,
1306
-        $field_to_order_by = null,
1307
-        $query_params = [],
1308
-        $columns_to_select = null
1309
-    ) {
1310
-        $results = $this->_get_consecutive(
1311
-            $current_field_value,
1312
-            '>',
1313
-            $field_to_order_by,
1314
-            1,
1315
-            $query_params,
1316
-            $columns_to_select
1317
-        );
1318
-        return empty($results) ? null : reset($results);
1319
-    }
1320
-
1321
-
1322
-    /**
1323
-     * Returns the previous item in sequence from the given value as found in
1324
-     * the database matching the given query conditions.
1325
-     *
1326
-     * @param mixed $current_field_value    Value used for the reference point.
1327
-     * @param null  $field_to_order_by      What field is used for the
1328
-     *                                      reference point.
1329
-     * @param array $query_params           Extra conditions on the query.
1330
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1331
-     *                                      object is returned, otherwise you
1332
-     *                                      can indicate just the columns you
1333
-     *                                      want and a single array indexed by
1334
-     *                                      the columns will be returned.
1335
-     * @return EE_Base_Class|null|array()
1336
-     * @throws EE_Error
1337
-     * @throws ReflectionException
1338
-     */
1339
-    public function previous(
1340
-        $current_field_value,
1341
-        $field_to_order_by = null,
1342
-        $query_params = [],
1343
-        $columns_to_select = null
1344
-    ) {
1345
-        $results = $this->_get_consecutive(
1346
-            $current_field_value,
1347
-            '<',
1348
-            $field_to_order_by,
1349
-            1,
1350
-            $query_params,
1351
-            $columns_to_select
1352
-        );
1353
-        return empty($results) ? null : reset($results);
1354
-    }
1355
-
1356
-
1357
-    /**
1358
-     * Returns the a consecutive number of items in sequence from the given
1359
-     * value as found in the database matching the given query conditions.
1360
-     *
1361
-     * @param mixed  $current_field_value   Value used for the reference point.
1362
-     * @param string $operand               What operand is used for the sequence.
1363
-     * @param string $field_to_order_by     What field is used for the reference point.
1364
-     * @param int    $limit                 How many to return.
1365
-     * @param array  $query_params          Extra conditions on the query.
1366
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1367
-     *                                      otherwise you can indicate just the columns you want returned.
1368
-     * @return EE_Base_Class[]|array
1369
-     * @throws EE_Error
1370
-     * @throws ReflectionException
1371
-     */
1372
-    protected function _get_consecutive(
1373
-        $current_field_value,
1374
-        $operand = '>',
1375
-        $field_to_order_by = null,
1376
-        $limit = 1,
1377
-        $query_params = [],
1378
-        $columns_to_select = null
1379
-    ) {
1380
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1381
-        if (empty($field_to_order_by)) {
1382
-            if ($this->has_primary_key_field()) {
1383
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1384
-            } else {
1385
-                if (WP_DEBUG) {
1386
-                    throw new EE_Error(
1387
-                        esc_html__(
1388
-                            '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).',
1389
-                            'event_espresso'
1390
-                        )
1391
-                    );
1392
-                }
1393
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1394
-                return [];
1395
-            }
1396
-        }
1397
-        if (! is_array($query_params)) {
1398
-            EE_Error::doing_it_wrong(
1399
-                'EEM_Base::_get_consecutive',
1400
-                sprintf(
1401
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1402
-                    gettype($query_params)
1403
-                ),
1404
-                '4.6.0'
1405
-            );
1406
-            $query_params = [];
1407
-        }
1408
-        // let's add the where query param for consecutive look up.
1409
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1410
-        $query_params['limit']                 = $limit;
1411
-        // set direction
1412
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1413
-        $query_params['order_by'] = $operand === '>'
1414
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1415
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1416
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1417
-        if (empty($columns_to_select)) {
1418
-            return $this->get_all($query_params);
1419
-        }
1420
-        // getting just the fields
1421
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * This sets the _timezone property after model object has been instantiated.
1427
-     *
1428
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1429
-     */
1430
-    public function set_timezone($timezone = '')
1431
-    {
1432
-        static $set_in_progress = false;
1433
-        // if incoming timezone string is empty, then use the existing
1434
-        $valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1435
-            ? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1436
-            : $this->_timezone;
1437
-        // do NOT set the timezone if we are already in the process of setting the timezone
1438
-        // OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1439
-        // OR the existing timezone is already set and the validated value is the same as the existing timezone
1440
-        if (
1441
-            $set_in_progress
1442
-            || (
1443
-                ! empty($this->_timezone)
1444
-                && (
1445
-                    empty($timezone) || $valid_timezone === $this->_timezone
1446
-                )
1447
-            )
1448
-        ) {
1449
-            return;
1450
-        }
1451
-        $set_in_progress = true;
1452
-        $this->_timezone = $valid_timezone ?: EEH_DTT_Helper::get_valid_timezone_string();
1453
-        // note we need to loop through relations and set the timezone on those objects as well.
1454
-        foreach ($this->_model_relations as $relation) {
1455
-            $relation->set_timezone($this->_timezone);
1456
-        }
1457
-        // and finally we do the same for any datetime fields
1458
-        foreach ($this->_fields as $field) {
1459
-            if ($field instanceof EE_Datetime_Field) {
1460
-                $field->set_timezone($this->_timezone);
1461
-            }
1462
-        }
1463
-        $set_in_progress = false;
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This just returns whatever is set for the current timezone.
1469
-     *
1470
-     * @access public
1471
-     * @return string
1472
-     */
1473
-    public function get_timezone()
1474
-    {
1475
-        if (empty($this->_timezone)) {
1476
-            $this->set_timezone();
1477
-        }
1478
-        return $this->_timezone;
1479
-    }
1480
-
1481
-
1482
-    /**
1483
-     * This returns the date formats set for the given field name and also ensures that
1484
-     * $this->_timezone property is set correctly.
1485
-     *
1486
-     * @param string $field_name The name of the field the formats are being retrieved for.
1487
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488
-     * @return array formats in an array with the date format first, and the time format last.
1489
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1490
-     * @since 4.6.x
1491
-     */
1492
-    public function get_formats_for($field_name, $pretty = false)
1493
-    {
1494
-        $field_settings = $this->field_settings_for($field_name);
1495
-        // if not a valid EE_Datetime_Field then throw error
1496
-        if (! $field_settings instanceof EE_Datetime_Field) {
1497
-            throw new EE_Error(
1498
-                sprintf(
1499
-                    esc_html__(
1500
-                        '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.',
1501
-                        'event_espresso'
1502
-                    ),
1503
-                    $field_name
1504
-                )
1505
-            );
1506
-        }
1507
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1508
-        $field_timezone = $field_settings->get_timezone();
1509
-        if (empty($this->_timezone && $field_timezone)) {
1510
-            $this->set_timezone();
1511
-        } else {
1512
-            // or vice versa if the field TZ isn't set
1513
-            $model_timezone = $this->get_timezone();
1514
-            $field_settings->set_timezone($model_timezone);
1515
-        }
1516
-
1517
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1518
-    }
1519
-
1520
-
1521
-    /**
1522
-     * This returns the current time in a format setup for a query on this model.
1523
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
-     * it will return:
1525
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field
1526
-     *    for the given field for NOW
1527
-     *  - or a unix timestamp (equivalent to time())
1528
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
-     *
1532
-     * @param string $field_name    The field the current time is needed for.
1533
-     * @param bool $timestamp       True means to return a unix timestamp.
1534
-     *                              Otherwise a formatted string matching the set format for the field
1535
-     *                              in the set timezone will be returned.
1536
-     * @param string $what          Whether to return the string in just the time format, the date format, or both.
1537
-     * @return string               If the given field_name is not of the EE_Datetime_Field type,
1538
-     *                              then an EE_Error exception is triggered.
1539
-     * @throws EE_Error             If the given field_name is not of the EE_Datetime_Field type.
1540
-     * @throws Exception
1541
-     * @since 4.6.x
1542
-     */
1543
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1544
-    {
1545
-        $formats  = $this->get_formats_for($field_name);
1546
-        $DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1547
-        if ($timestamp) {
1548
-            return $DateTime->format('U');
1549
-        }
1550
-        // not returning timestamp, so return formatted string in timezone.
1551
-        switch ($what) {
1552
-            case 'time':
1553
-                return $DateTime->format($formats[1]);
1554
-            case 'date':
1555
-                return $DateTime->format($formats[0]);
1556
-            default:
1557
-                return $DateTime->format(implode(' ', $formats));
1558
-        }
1559
-    }
1560
-
1561
-
1562
-    /**
1563
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1564
-     * for the model are.  Returns a DateTime object.
1565
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1566
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1567
-     * ignored.
1568
-     *
1569
-     * @param string $field_name    The field being setup.
1570
-     * @param string $timestring    The date time string being used.
1571
-     * @param string $format        The format for the time string.
1572
-     * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1573
-     *                              the blog.  If this is not the case, then it can be specified here.
1574
-     *                              If incoming format is 'U', this is ignored.
1575
-     * @return DbSafeDateTime
1576
-     * @throws EE_Error
1577
-     * @throws Exception
1578
-     */
1579
-    public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1580
-    {
1581
-        // just using this to ensure the timezone is set correctly internally
1582
-        $this->get_formats_for($field_name);
1583
-        $timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1584
-        $db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1585
-        EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1586
-        return $db_safe_datetime;
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
-     *
1593
-     * @return EE_Table_Base[]
1594
-     */
1595
-    public function get_tables()
1596
-    {
1597
-        return $this->_tables;
1598
-    }
1599
-
1600
-
1601
-    /**
1602
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1603
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1604
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1605
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1606
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1607
-     * model object with EVT_ID = 1
1608
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1609
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1610
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1611
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1612
-     * are not specified)
1613
-     *
1614
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1615
-     *                                         columns!), values are strings, integers, floats, and maybe arrays if
1616
-     *                                         they
1617
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1620
-     *                                         ID=34, we'd use this method as follows:
1621
-     *                                         EEM_Transaction::instance()->update(
1622
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
-     *                                         array(array('TXN_ID'=>34)));
1624
-     * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1625
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1626
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1627
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1628
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1629
-     *                                         TRUE, it is assumed that you've already called
1630
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1631
-     *                                         malicious javascript. However, if
1632
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1633
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1634
-     *                                         and every other field, before insertion. We provide this parameter
1635
-     *                                         because model objects perform their prepare_for_set function on all
1636
-     *                                         their values, and so don't need to be called again (and in many cases,
1637
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1638
-     *                                         prepare_for_set method...)
1639
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1640
-     *                                         in this model's entity map according to $fields_n_values that match
1641
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1642
-     *                                         by setting this to FALSE, but be aware that model objects being used
1643
-     *                                         could get out-of-sync with the database
1644
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1645
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1646
-     *                                         bad)
1647
-     * @throws EE_Error
1648
-     * @throws ReflectionException
1649
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
-     */
1651
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
-    {
1653
-        if (! is_array($query_params)) {
1654
-            EE_Error::doing_it_wrong(
1655
-                'EEM_Base::update',
1656
-                sprintf(
1657
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1658
-                    gettype($query_params)
1659
-                ),
1660
-                '4.6.0'
1661
-            );
1662
-            $query_params = [];
1663
-        }
1664
-        /**
1665
-         * Action called before a model update call has been made.
1666
-         *
1667
-         * @param EEM_Base $model
1668
-         * @param array    $fields_n_values the updated fields and their new values
1669
-         * @param array    $query_params
1670
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1671
-         */
1672
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1673
-        /**
1674
-         * Filters the fields about to be updated given the query parameters. You can provide the
1675
-         * $query_params to $this->get_all() to find exactly which records will be updated
1676
-         *
1677
-         * @param array    $fields_n_values fields and their new values
1678
-         * @param EEM_Base $model           the model being queried
1679
-         * @param array    $query_params
1680
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1681
-         */
1682
-        $fields_n_values = (array)apply_filters(
1683
-            'FHEE__EEM_Base__update__fields_n_values',
1684
-            $fields_n_values,
1685
-            $this,
1686
-            $query_params
1687
-        );
1688
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1689
-        // to do that, for each table, verify that it's PK isn't null.
1690
-        $tables = $this->get_tables();
1691
-        // 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
1692
-        // NOTE: we should make this code more efficient by NOT querying twice
1693
-        // before the real update, but that needs to first go through ALPHA testing
1694
-        // as it's dangerous. says Mike August 8 2014
1695
-        // we want to make sure the default_where strategy is ignored
1696
-        $this->_ignore_where_strategy = true;
1697
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1698
-        foreach ($wpdb_select_results as $wpdb_result) {
1699
-            // type cast stdClass as array
1700
-            $wpdb_result = (array)$wpdb_result;
1701
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1702
-            if ($this->has_primary_key_field()) {
1703
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1704
-            } else {
1705
-                // 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)
1706
-                $main_table_pk_value = null;
1707
-            }
1708
-            // 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
1709
-            // 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
1710
-            if (count($tables) > 1) {
1711
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1712
-                // in that table, and so we'll want to insert one
1713
-                foreach ($tables as $table_obj) {
1714
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1715
-                    // if there is no private key for this table on the results, it means there's no entry
1716
-                    // in this table, right? so insert a row in the current table, using any fields available
1717
-                    if (
1718
-                    ! (array_key_exists($this_table_pk_column, $wpdb_result)
1719
-                       && $wpdb_result[ $this_table_pk_column ])
1720
-                    ) {
1721
-                        $success = $this->_insert_into_specific_table(
1722
-                            $table_obj,
1723
-                            $fields_n_values,
1724
-                            $main_table_pk_value
1725
-                        );
1726
-                        // if we died here, report the error
1727
-                        if (! $success) {
1728
-                            return false;
1729
-                        }
1730
-                    }
1731
-                }
1732
-            }
1733
-            // let's make sure default_where strategy is followed now
1734
-            $this->_ignore_where_strategy = false;
1735
-        }
1736
-        // if we want to keep model objects in sync, AND
1737
-        // if this wasn't called from a model object (to update itself)
1738
-        // then we want to make sure we keep all the existing
1739
-        // model objects in sync with the db
1740
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1741
-            if ($this->has_primary_key_field()) {
1742
-                $model_objs_affected_ids = $this->get_col($query_params);
1743
-            } else {
1744
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1745
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1746
-                $model_objs_affected_ids     = [];
1747
-                foreach ($models_affected_key_columns as $row) {
1748
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1749
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1750
-                }
1751
-            }
1752
-            if (! $model_objs_affected_ids) {
1753
-                // wait wait wait- if nothing was affected let's stop here
1754
-                return 0;
1755
-            }
1756
-            foreach ($model_objs_affected_ids as $id) {
1757
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1758
-                if ($model_obj_in_entity_map) {
1759
-                    foreach ($fields_n_values as $field => $new_value) {
1760
-                        $model_obj_in_entity_map->set($field, $new_value);
1761
-                    }
1762
-                }
1763
-            }
1764
-            // if there is a primary key on this model, we can now do a slight optimization
1765
-            if ($this->has_primary_key_field()) {
1766
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1767
-                $query_params = [
1768
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1769
-                    'limit'                    => count($model_objs_affected_ids),
1770
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1771
-                ];
1772
-            }
1773
-        }
1774
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1776
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1777
-                            . $model_query_info->get_where_sql();
1778
-        // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1779
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1780
-        /**
1781
-         * Action called after a model update call has been made.
1782
-         *
1783
-         * @param EEM_Base $model
1784
-         * @param array    $fields_n_values the updated fields and their new values
1785
-         * @param array    $query_params
1786
-         * @param int      $rows_affected
1787
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1788
-         */
1789
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1790
-        return $rows_affected;// how many supposedly got updated
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1796
-     * are teh values of the field specified (or by default the primary key field)
1797
-     * that matched the query params. Note that you should pass the name of the
1798
-     * model FIELD, not the database table's column name.
1799
-     *
1800
-     * @param array  $query_params
1801
-     * @param string $field_to_select
1802
-     * @return array just like $wpdb->get_col()
1803
-     * @throws EE_Error
1804
-     * @throws ReflectionException
1805
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1806
-     */
1807
-    public function get_col($query_params = [], $field_to_select = null)
1808
-    {
1809
-        if ($field_to_select) {
1810
-            $field = $this->field_settings_for($field_to_select);
1811
-        } elseif ($this->has_primary_key_field()) {
1812
-            $field = $this->get_primary_key_field();
1813
-        } else {
1814
-            $field_settings = $this->field_settings();
1815
-            // no primary key, just grab the first column
1816
-            $field = reset($field_settings);
1817
-        }
1818
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1819
-        $select_expressions = $field->get_qualified_column();
1820
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1821
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1822
-    }
1823
-
1824
-
1825
-    /**
1826
-     * Returns a single column value for a single row from the database
1827
-     *
1828
-     * @param array  $query_params
1829
-     * @param string $field_to_select
1830
-     * @return string
1831
-     * @throws EE_Error
1832
-     * @throws ReflectionException
1833
-     * @see EEM_Base::get_col()
1834
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1835
-     */
1836
-    public function get_var($query_params = [], $field_to_select = null)
1837
-    {
1838
-        $query_params['limit'] = 1;
1839
-        $col                   = $this->get_col($query_params, $field_to_select);
1840
-        if (! empty($col)) {
1841
-            return reset($col);
1842
-        }
1843
-        return null;
1844
-    }
1845
-
1846
-
1847
-    /**
1848
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1849
-     * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1850
-     * injection, but currently no further filtering is done
1851
-     *
1852
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1853
-     *                               be updated to in the DB
1854
-     * @return string of SQL
1855
-     * @throws EE_Error
1856
-     * @global      $wpdb
1857
-     */
1858
-    public function _construct_update_sql($fields_n_values)
1859
-    {
1860
-        global $wpdb;
1861
-        $cols_n_values = [];
1862
-        foreach ($fields_n_values as $field_name => $value) {
1863
-            $field_obj = $this->field_settings_for($field_name);
1864
-            // if the value is NULL, we want to assign the value to that.
1865
-            // wpdb->prepare doesn't really handle that properly
1866
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1867
-            $value_sql       = $prepared_value === null
1868
-                ? 'NULL'
1869
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1870
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1871
-        }
1872
-        return implode(",", $cols_n_values);
1873
-    }
1874
-
1875
-
1876
-    /**
1877
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1878
-     * Performs a HARD delete, meaning the database row should always be removed,
1879
-     * not just have a flag field on it switched
1880
-     * Wrapper for EEM_Base::delete_permanently()
1881
-     *
1882
-     * @param mixed   $id
1883
-     * @param boolean $allow_blocking
1884
-     * @return int the number of rows deleted
1885
-     * @throws EE_Error
1886
-     * @throws ReflectionException
1887
-     */
1888
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1889
-    {
1890
-        return $this->delete_permanently(
1891
-            [
1892
-                [$this->get_primary_key_field()->get_name() => $id],
1893
-                'limit' => 1,
1894
-            ],
1895
-            $allow_blocking
1896
-        );
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
-     * Wrapper for EEM_Base::delete()
1903
-     *
1904
-     * @param mixed   $id
1905
-     * @param boolean $allow_blocking
1906
-     * @return int the number of rows deleted
1907
-     * @throws EE_Error
1908
-     * @throws ReflectionException
1909
-     */
1910
-    public function delete_by_ID($id, $allow_blocking = true)
1911
-    {
1912
-        return $this->delete(
1913
-            [
1914
-                [$this->get_primary_key_field()->get_name() => $id],
1915
-                'limit' => 1,
1916
-            ],
1917
-            $allow_blocking
1918
-        );
1919
-    }
1920
-
1921
-
1922
-    /**
1923
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1924
-     * meaning if the model has a field that indicates its been "trashed" or
1925
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1926
-     *
1927
-     * @param array   $query_params
1928
-     * @param boolean $allow_blocking
1929
-     * @return int how many rows got deleted
1930
-     * @throws EE_Error
1931
-     * @throws ReflectionException
1932
-     * @see EEM_Base::delete_permanently
1933
-     */
1934
-    public function delete($query_params, $allow_blocking = true)
1935
-    {
1936
-        return $this->delete_permanently($query_params, $allow_blocking);
1937
-    }
1938
-
1939
-
1940
-    /**
1941
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1942
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1943
-     * as archived, not actually deleted
1944
-     *
1945
-     * @param array   $query_params
1946
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1947
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1948
-     *                                deletes regardless of other objects which may depend on it. Its generally
1949
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1950
-     *                                DB
1951
-     * @return int how many rows got deleted
1952
-     * @throws EE_Error
1953
-     * @throws ReflectionException
1954
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1955
-     */
1956
-    public function delete_permanently($query_params, $allow_blocking = true)
1957
-    {
1958
-        /**
1959
-         * Action called just before performing a real deletion query. You can use the
1960
-         * model and its $query_params to find exactly which items will be deleted
1961
-         *
1962
-         * @param EEM_Base $model
1963
-         * @param array    $query_params
1964
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1965
-         *                                 to block (prevent) this deletion
1966
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1967
-         */
1968
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1969
-        // some MySQL databases may be running safe mode, which may restrict
1970
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1971
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1972
-        // to delete them
1973
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1974
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1975
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1976
-            $columns_and_ids_for_deleting
1977
-        );
1978
-        /**
1979
-         * Allows client code to act on the items being deleted before the query is actually executed.
1980
-         *
1981
-         * @param EEM_Base $this                            The model instance being acted on.
1982
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1983
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1984
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1985
-         *                                                  derived from the incoming query parameters.
1986
-         * @see details on the structure of this array in the phpdocs
1987
-         *                                                  for the `_get_ids_for_delete_method`
1988
-         *
1989
-         */
1990
-        do_action(
1991
-            'AHEE__EEM_Base__delete__before_query',
1992
-            $this,
1993
-            $query_params,
1994
-            $allow_blocking,
1995
-            $columns_and_ids_for_deleting
1996
-        );
1997
-        if ($deletion_where_query_part) {
1998
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1999
-            $table_aliases    = implode(', ', array_keys($this->_tables));
2000
-            $SQL              = "DELETE " . $table_aliases
2001
-                                . " FROM " . $model_query_info->get_full_join_sql()
2002
-                                . " WHERE " . $deletion_where_query_part;
2003
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2004
-        } else {
2005
-            $rows_deleted = 0;
2006
-        }
2007
-
2008
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2009
-        // there was no error with the delete query.
2010
-        if (
2011
-            $this->has_primary_key_field()
2012
-            && $rows_deleted !== false
2013
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2014
-        ) {
2015
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2016
-            foreach ($ids_for_removal as $id) {
2017
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2018
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2019
-                }
2020
-            }
2021
-
2022
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2023
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2024
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2025
-            // (although it is possible).
2026
-            // Note this can be skipped by using the provided filter and returning false.
2027
-            if (
2028
-            apply_filters(
2029
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2030
-                ! $this instanceof EEM_Extra_Meta,
2031
-                $this
2032
-            )
2033
-            ) {
2034
-                EEM_Extra_Meta::instance()->delete_permanently(
2035
-                    [
2036
-                        0 => [
2037
-                            'EXM_type' => $this->get_this_model_name(),
2038
-                            'OBJ_ID'   => [
2039
-                                'IN',
2040
-                                $ids_for_removal,
2041
-                            ],
2042
-                        ],
2043
-                    ]
2044
-                );
2045
-            }
2046
-        }
2047
-
2048
-        /**
2049
-         * Action called just after performing a real deletion query. Although at this point the
2050
-         * items should have been deleted
2051
-         *
2052
-         * @param EEM_Base $model
2053
-         * @param array    $query_params
2054
-         * @param int      $rows_deleted
2055
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2056
-         */
2057
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;// how many supposedly got deleted
2059
-    }
2060
-
2061
-
2062
-    /**
2063
-     * Checks all the relations that throw error messages when there are blocking related objects
2064
-     * for related model objects. If there are any related model objects on those relations,
2065
-     * adds an EE_Error, and return true
2066
-     *
2067
-     * @param EE_Base_Class|int $this_model_obj_or_id
2068
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2069
-     *                                                 should be ignored when determining whether there are related
2070
-     *                                                 model objects which block this model object's deletion. Useful
2071
-     *                                                 if you know A is related to B and are considering deleting A,
2072
-     *                                                 but want to see if A has any other objects blocking its deletion
2073
-     *                                                 before removing the relation between A and B
2074
-     * @return boolean
2075
-     * @throws EE_Error
2076
-     * @throws ReflectionException
2077
-     */
2078
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
-    {
2080
-        // first, if $ignore_this_model_obj was supplied, get its model
2081
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
-            $ignored_model = $ignore_this_model_obj->get_model();
2083
-        } else {
2084
-            $ignored_model = null;
2085
-        }
2086
-        // now check all the relations of $this_model_obj_or_id and see if there
2087
-        // are any related model objects blocking it?
2088
-        $is_blocked = false;
2089
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2091
-                // if $ignore_this_model_obj was supplied, then for the query
2092
-                // on that model needs to be told to ignore $ignore_this_model_obj
2093
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
-                    $related_model_objects = $relation_obj->get_all_related(
2095
-                        $this_model_obj_or_id,
2096
-                        [
2097
-                            [
2098
-                                $ignored_model->get_primary_key_field()->get_name() => [
2099
-                                    '!=',
2100
-                                    $ignore_this_model_obj->ID(),
2101
-                                ],
2102
-                            ],
2103
-                        ]
2104
-                    );
2105
-                } else {
2106
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2107
-                }
2108
-                if ($related_model_objects) {
2109
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2110
-                    $is_blocked = true;
2111
-                }
2112
-            }
2113
-        }
2114
-        return $is_blocked;
2115
-    }
2116
-
2117
-
2118
-    /**
2119
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2120
-     *
2121
-     * @param array $row_results_for_deleting
2122
-     * @param bool  $allow_blocking
2123
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2124
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2125
-     *                              dimension array where the key is the fully qualified primary key column and the
2126
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2127
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2128
-     *                              be a two dimensional array where each element is a group of columns and values that
2129
-     *                              get deleted. Example: array(
2130
-     *                              0 => array(
2131
-     *                              'Term_Relationship.object_id' => 1
2132
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2133
-     *                              ),
2134
-     *                              1 => array(
2135
-     *                              'Term_Relationship.object_id' => 1
2136
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2137
-     *                              )
2138
-     *                              )
2139
-     * @throws EE_Error
2140
-     * @throws ReflectionException
2141
-     */
2142
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2143
-    {
2144
-        $ids_to_delete_indexed_by_column = [];
2145
-        if ($this->has_primary_key_field()) {
2146
-            $primary_table                   = $this->_get_main_table();
2147
-            $ids_to_delete_indexed_by_column = [];
2148
-            foreach ($row_results_for_deleting as $item_to_delete) {
2149
-                // before we mark this item for deletion,
2150
-                // make sure there's no related entities blocking its deletion (if we're checking)
2151
-                if (
2152
-                    $allow_blocking
2153
-                    && $this->delete_is_blocked_by_related_models(
2154
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2155
-                    )
2156
-                ) {
2157
-                    continue;
2158
-                }
2159
-                // primary table deletes
2160
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2161
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2162
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2163
-                }
2164
-            }
2165
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2166
-            $fields = $this->get_combined_primary_key_fields();
2167
-            foreach ($row_results_for_deleting as $item_to_delete) {
2168
-                $ids_to_delete_indexed_by_column_for_row = [];
2169
-                foreach ($fields as $cpk_field) {
2170
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2171
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2172
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2173
-                    }
2174
-                }
2175
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2176
-            }
2177
-        } else {
2178
-            // so there's no primary key and no combined key...
2179
-            // sorry, can't help you
2180
-            throw new EE_Error(
2181
-                sprintf(
2182
-                    esc_html__(
2183
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2184
-                        "event_espresso"
2185
-                    ),
2186
-                    get_class($this)
2187
-                )
2188
-            );
2189
-        }
2190
-        return $ids_to_delete_indexed_by_column;
2191
-    }
2192
-
2193
-
2194
-    /**
2195
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2196
-     * the corresponding query_part for the query performing the delete.
2197
-     *
2198
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2199
-     * @return string
2200
-     * @throws EE_Error
2201
-     */
2202
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2203
-    {
2204
-        $query_part = '';
2205
-        if (empty($ids_to_delete_indexed_by_column)) {
2206
-            return $query_part;
2207
-        } elseif ($this->has_primary_key_field()) {
2208
-            $query = [];
2209
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210
-                // make sure we have unique $ids
2211
-                $ids     = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2213
-            }
2214
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2216
-            $ways_to_identify_a_row = [];
2217
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218
-                $values_for_each_combined_primary_key_for_a_row = [];
2219
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2221
-                }
2222
-                $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2223
-                $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2224
-            }
2225
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2226
-        }
2227
-        return $query_part;
2228
-    }
2229
-
2230
-
2231
-    /**
2232
-     * Gets the model field by the fully qualified name
2233
-     *
2234
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2235
-     * @return EE_Model_Field_Base
2236
-     * @throws EE_Error
2237
-     */
2238
-    public function get_field_by_column($qualified_column_name)
2239
-    {
2240
-        foreach ($this->field_settings(true) as $field_obj) {
2241
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242
-                return $field_obj;
2243
-            }
2244
-        }
2245
-        throw new EE_Error(
2246
-            sprintf(
2247
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2248
-                $this->get_this_model_name(),
2249
-                $qualified_column_name
2250
-            )
2251
-        );
2252
-    }
2253
-
2254
-
2255
-    /**
2256
-     * Count all the rows that match criteria the model query params.
2257
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2258
-     * column
2259
-     *
2260
-     * @param array  $query_params
2261
-     * @param string $field_to_count field on model to count by (not column name)
2262
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2263
-     *                               that by the setting $distinct to TRUE;
2264
-     * @return int
2265
-     * @throws EE_Error
2266
-     * @throws ReflectionException
2267
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2268
-     */
2269
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2270
-    {
2271
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
-        if ($field_to_count) {
2273
-            $field_obj       = $this->field_settings_for($field_to_count);
2274
-            $column_to_count = $field_obj->get_qualified_column();
2275
-        } elseif ($this->has_primary_key_field()) {
2276
-            $pk_field_obj    = $this->get_primary_key_field();
2277
-            $column_to_count = $pk_field_obj->get_qualified_column();
2278
-        } else {
2279
-            // there's no primary key
2280
-            // if we're counting distinct items, and there's no primary key,
2281
-            // we need to list out the columns for distinction;
2282
-            // otherwise we can just use star
2283
-            if ($distinct) {
2284
-                $columns_to_use = [];
2285
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2286
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2287
-                }
2288
-                $column_to_count = implode(',', $columns_to_use);
2289
-            } else {
2290
-                $column_to_count = '*';
2291
-            }
2292
-        }
2293
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2294
-        $SQL             =
2295
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2297
-    }
2298
-
2299
-
2300
-    /**
2301
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2302
-     *
2303
-     * @param array  $query_params
2304
-     * @param string $field_to_sum name of field (array key in $_fields array)
2305
-     * @return float
2306
-     * @throws EE_Error
2307
-     * @throws ReflectionException
2308
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2309
-     */
2310
-    public function sum($query_params, $field_to_sum = null)
2311
-    {
2312
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2313
-        if ($field_to_sum) {
2314
-            $field_obj = $this->field_settings_for($field_to_sum);
2315
-        } else {
2316
-            $field_obj = $this->get_primary_key_field();
2317
-        }
2318
-        $column_to_count = $field_obj->get_qualified_column();
2319
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2320
-                           . $this->_construct_2nd_half_of_select_query($model_query_info);
2321
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2322
-        // $data_type       = $field_obj->get_wpdb_data_type();
2323
-        // if ($data_type === '%d' || $data_type === '%s') {
2324
-        //     return (float)$return_value;
2325
-        // }
2326
-        // must be %f
2327
-        return (float)$return_value;
2328
-    }
2329
-
2330
-
2331
-    /**
2332
-     * Just calls the specified method on $wpdb with the given arguments
2333
-     * Consolidates a little extra error handling code
2334
-     *
2335
-     * @param string $wpdb_method
2336
-     * @param array  $arguments_to_provide
2337
-     * @return mixed
2338
-     * @throws EE_Error
2339
-     * @throws ReflectionException
2340
-     * @global wpdb  $wpdb
2341
-     */
2342
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2343
-    {
2344
-        // if we're in maintenance mode level 2, DON'T run any queries
2345
-        // because level 2 indicates the database needs updating and
2346
-        // is probably out of sync with the code
2347
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2348
-            throw new EE_Error(
2349
-                esc_html__(
2350
-                    '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.',
2351
-                    'event_espresso'
2352
-                )
2353
-            );
2354
-        }
2355
-        global $wpdb;
2356
-        if (! method_exists($wpdb, $wpdb_method)) {
2357
-            throw new EE_Error(
2358
-                sprintf(
2359
-                    esc_html__(
2360
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2361
-                        'event_espresso'
2362
-                    ),
2363
-                    $wpdb_method
2364
-                )
2365
-            );
2366
-        }
2367
-        $old_show_errors_value = $wpdb->show_errors;
2368
-        if (WP_DEBUG) {
2369
-            $wpdb->show_errors(false);
2370
-        }
2371
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2372
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2373
-        if (WP_DEBUG) {
2374
-            $wpdb->show_errors($old_show_errors_value);
2375
-            if (! empty($wpdb->last_error)) {
2376
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2377
-            }
2378
-            if ($result === false) {
2379
-                throw new EE_Error(
2380
-                    sprintf(
2381
-                        esc_html__(
2382
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2383
-                            'event_espresso'
2384
-                        ),
2385
-                        $wpdb_method,
2386
-                        var_export($arguments_to_provide, true)
2387
-                    )
2388
-                );
2389
-            }
2390
-        } elseif ($result === false) {
2391
-            EE_Error::add_error(
2392
-                sprintf(
2393
-                    esc_html__(
2394
-                        '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"',
2395
-                        'event_espresso'
2396
-                    ),
2397
-                    $wpdb_method,
2398
-                    var_export($arguments_to_provide, true),
2399
-                    $wpdb->last_error
2400
-                ),
2401
-                __FILE__,
2402
-                __FUNCTION__,
2403
-                __LINE__
2404
-            );
2405
-        }
2406
-        return $result;
2407
-    }
2408
-
2409
-
2410
-    /**
2411
-     * Attempts to run the indicated WPDB method with the provided arguments,
2412
-     * and if there's an error tries to verify the DB is correct. Uses
2413
-     * the static property EEM_Base::$_db_verification_level to determine whether
2414
-     * we should try to fix the EE core db, the addons, or just give up
2415
-     *
2416
-     * @param string $wpdb_method
2417
-     * @param array  $arguments_to_provide
2418
-     * @return mixed
2419
-     * @throws EE_Error
2420
-     * @throws ReflectionException
2421
-     */
2422
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2423
-    {
2424
-        global $wpdb;
2425
-        $wpdb->last_error = null;
2426
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2427
-        // was there an error running the query? but we don't care on new activations
2428
-        // (we're going to setup the DB anyway on new activations)
2429
-        if (
2430
-            ($result === false || ! empty($wpdb->last_error))
2431
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2432
-        ) {
2433
-            switch (EEM_Base::$_db_verification_level) {
2434
-                case EEM_Base::db_verified_none:
2435
-                    // let's double-check core's DB
2436
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2437
-                    break;
2438
-                case EEM_Base::db_verified_core:
2439
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2440
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2441
-                    break;
2442
-                case EEM_Base::db_verified_addons:
2443
-                    // ummmm... you in trouble
2444
-                    return $result;
2445
-            }
2446
-            if (! empty($error_message)) {
2447
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2448
-                trigger_error($error_message);
2449
-            }
2450
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2451
-        }
2452
-        return $result;
2453
-    }
2454
-
2455
-
2456
-    /**
2457
-     * Verifies the EE core database is up-to-date and records that we've done it on
2458
-     * EEM_Base::$_db_verification_level
2459
-     *
2460
-     * @param string $wpdb_method
2461
-     * @param array  $arguments_to_provide
2462
-     * @return string
2463
-     * @throws EE_Error
2464
-     * @throws ReflectionException
2465
-     */
2466
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2467
-    {
2468
-        global $wpdb;
2469
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2470
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2471
-        $error_message                    = sprintf(
2472
-            esc_html__(
2473
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2474
-                'event_espresso'
2475
-            ),
2476
-            $wpdb->last_error,
2477
-            $wpdb_method,
2478
-            wp_json_encode($arguments_to_provide)
2479
-        );
2480
-        EE_System::instance()->initialize_db_if_no_migrations_required();
2481
-        return $error_message;
2482
-    }
2483
-
2484
-
2485
-    /**
2486
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2487
-     * EEM_Base::$_db_verification_level
2488
-     *
2489
-     * @param $wpdb_method
2490
-     * @param $arguments_to_provide
2491
-     * @return string
2492
-     * @throws EE_Error
2493
-     * @throws ReflectionException
2494
-     */
2495
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2496
-    {
2497
-        global $wpdb;
2498
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2499
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2500
-        $error_message                    = sprintf(
2501
-            esc_html__(
2502
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2503
-                'event_espresso'
2504
-            ),
2505
-            $wpdb->last_error,
2506
-            $wpdb_method,
2507
-            wp_json_encode($arguments_to_provide)
2508
-        );
2509
-        EE_System::instance()->initialize_addons();
2510
-        return $error_message;
2511
-    }
2512
-
2513
-
2514
-    /**
2515
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2516
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2517
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2518
-     * ..."
2519
-     *
2520
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2521
-     * @return string
2522
-     */
2523
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2524
-    {
2525
-        return " FROM " . $model_query_info->get_full_join_sql() .
2526
-               $model_query_info->get_where_sql() .
2527
-               $model_query_info->get_group_by_sql() .
2528
-               $model_query_info->get_having_sql() .
2529
-               $model_query_info->get_order_by_sql() .
2530
-               $model_query_info->get_limit_sql();
2531
-    }
2532
-
2533
-
2534
-    /**
2535
-     * Set to easily debug the next X queries ran from this model.
2536
-     *
2537
-     * @param int $count
2538
-     */
2539
-    public function show_next_x_db_queries($count = 1)
2540
-    {
2541
-        $this->_show_next_x_db_queries = $count;
2542
-    }
2543
-
2544
-
2545
-    /**
2546
-     * @param $sql_query
2547
-     */
2548
-    public function show_db_query_if_previously_requested($sql_query)
2549
-    {
2550
-        if ($this->_show_next_x_db_queries > 0) {
2551
-            echo $sql_query;
2552
-            $this->_show_next_x_db_queries--;
2553
-        }
2554
-    }
2555
-
2556
-
2557
-    /**
2558
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2559
-     * There are the 3 cases:
2560
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2561
-     * $otherModelObject has no ID, it is first saved.
2562
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2563
-     * has no ID, it is first saved.
2564
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2565
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2566
-     * join table
2567
-     *
2568
-     * @param EE_Base_Class                     /int $thisModelObject
2569
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2570
-     * @param string $relationName                     , key in EEM_Base::_relations
2571
-     *                                                 an attendee to a group, you also want to specify which role they
2572
-     *                                                 will have in that group. So you would use this parameter to
2573
-     *                                                 specify array('role-column-name'=>'role-id')
2574
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2575
-     *                                                 to for relation to methods that allow you to further specify
2576
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2577
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2578
-     *                                                 because these will be inserted in any new rows created as well.
2579
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2580
-     * @throws EE_Error
2581
-     */
2582
-    public function add_relationship_to(
2583
-        $id_or_obj,
2584
-        $other_model_id_or_obj,
2585
-        $relationName,
2586
-        $extra_join_model_fields_n_values = []
2587
-    ) {
2588
-        $relation_obj = $this->related_settings_for($relationName);
2589
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2590
-    }
2591
-
2592
-
2593
-    /**
2594
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2595
-     * There are the 3 cases:
2596
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2597
-     * error
2598
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2599
-     * an error
2600
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2601
-     *
2602
-     * @param EE_Base_Class /int $id_or_obj
2603
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2604
-     * @param string $relationName key in EEM_Base::_relations
2605
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2606
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2607
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2608
-     *                             because these will be inserted in any new rows created as well.
2609
-     * @return boolean of success
2610
-     * @throws EE_Error
2611
-     */
2612
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2613
-    {
2614
-        $relation_obj = $this->related_settings_for($relationName);
2615
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2616
-    }
2617
-
2618
-
2619
-    /**
2620
-     * @param mixed  $id_or_obj
2621
-     * @param string $relationName
2622
-     * @param array  $where_query_params
2623
-     * @param EE_Base_Class[] objects to which relations were removed
2624
-     * @return EE_Base_Class[]
2625
-     * @throws EE_Error
2626
-     */
2627
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2628
-    {
2629
-        $relation_obj = $this->related_settings_for($relationName);
2630
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2631
-    }
2632
-
2633
-
2634
-    /**
2635
-     * Gets all the related items of the specified $model_name, using $query_params.
2636
-     * Note: by default, we remove the "default query params"
2637
-     * because we want to get even deleted items etc.
2638
-     *
2639
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2640
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2641
-     * @param array  $query_params see github link below for more info
2642
-     * @return EE_Base_Class[]
2643
-     * @throws EE_Error
2644
-     * @throws ReflectionException
2645
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2646
-     */
2647
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2648
-    {
2649
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2650
-        $relation_settings = $this->related_settings_for($model_name);
2651
-        return $relation_settings->get_all_related($model_obj, $query_params);
2652
-    }
2653
-
2654
-
2655
-    /**
2656
-     * Deletes all the model objects across the relation indicated by $model_name
2657
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2658
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2659
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2660
-     *
2661
-     * @param EE_Base_Class|int|string $id_or_obj
2662
-     * @param string                   $model_name
2663
-     * @param array                    $query_params
2664
-     * @return int how many deleted
2665
-     * @throws EE_Error
2666
-     * @throws ReflectionException
2667
-     */
2668
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2669
-    {
2670
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2671
-        $relation_settings = $this->related_settings_for($model_name);
2672
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2673
-    }
2674
-
2675
-
2676
-    /**
2677
-     * Hard deletes all the model objects across the relation indicated by $model_name
2678
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2679
-     * the model objects can't be hard deleted because of blocking related model objects,
2680
-     * just does a soft-delete on them instead.
2681
-     *
2682
-     * @param EE_Base_Class|int|string $id_or_obj
2683
-     * @param string                   $model_name
2684
-     * @param array                    $query_params
2685
-     * @return int how many deleted
2686
-     * @throws EE_Error
2687
-     * @throws ReflectionException
2688
-     */
2689
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2690
-    {
2691
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2692
-        $relation_settings = $this->related_settings_for($model_name);
2693
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2694
-    }
2695
-
2696
-
2697
-    /**
2698
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2699
-     * unless otherwise specified in the $query_params
2700
-     *
2701
-     * @param int             /EE_Base_Class $id_or_obj
2702
-     * @param string $model_name     like 'Event', or 'Registration'
2703
-     * @param array  $query_params
2704
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2705
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2706
-     *                               that by the setting $distinct to TRUE;
2707
-     * @return int
2708
-     * @throws EE_Error
2709
-     * @throws ReflectionException
2710
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2711
-     */
2712
-    public function count_related(
2713
-        $id_or_obj,
2714
-        $model_name,
2715
-        $query_params = [],
2716
-        $field_to_count = null,
2717
-        $distinct = false
2718
-    ) {
2719
-        $related_model = $this->get_related_model_obj($model_name);
2720
-        // we're just going to use the query params on the related model's normal get_all query,
2721
-        // except add a condition to say to match the current mod
2722
-        if (! isset($query_params['default_where_conditions'])) {
2723
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2724
-        }
2725
-        $this_model_name                                                 = $this->get_this_model_name();
2726
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2727
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2728
-        return $related_model->count($query_params, $field_to_count, $distinct);
2729
-    }
2730
-
2731
-
2732
-    /**
2733
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2734
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2735
-     *
2736
-     * @param int           /EE_Base_Class $id_or_obj
2737
-     * @param string $model_name   like 'Event', or 'Registration'
2738
-     * @param array  $query_params
2739
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2740
-     * @return float
2741
-     * @throws EE_Error
2742
-     * @throws ReflectionException
2743
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2744
-     */
2745
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2746
-    {
2747
-        $related_model = $this->get_related_model_obj($model_name);
2748
-        if (! is_array($query_params)) {
2749
-            EE_Error::doing_it_wrong(
2750
-                'EEM_Base::sum_related',
2751
-                sprintf(
2752
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2753
-                    gettype($query_params)
2754
-                ),
2755
-                '4.6.0'
2756
-            );
2757
-            $query_params = [];
2758
-        }
2759
-        // we're just going to use the query params on the related model's normal get_all query,
2760
-        // except add a condition to say to match the current mod
2761
-        if (! isset($query_params['default_where_conditions'])) {
2762
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2763
-        }
2764
-        $this_model_name                                                 = $this->get_this_model_name();
2765
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2766
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2767
-        return $related_model->sum($query_params, $field_to_sum);
2768
-    }
2769
-
2770
-
2771
-    /**
2772
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2773
-     * $modelObject
2774
-     *
2775
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2776
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2777
-     * @param array               $query_params     see github link below for more info
2778
-     * @return EE_Base_Class
2779
-     * @throws EE_Error
2780
-     * @throws ReflectionException
2781
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2782
-     */
2783
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2784
-    {
2785
-        $query_params['limit'] = 1;
2786
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2787
-        if ($results) {
2788
-            return array_shift($results);
2789
-        }
2790
-        return null;
2791
-    }
2792
-
2793
-
2794
-    /**
2795
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2796
-     *
2797
-     * @return string
2798
-     */
2799
-    public function get_this_model_name()
2800
-    {
2801
-        return str_replace("EEM_", "", get_class($this));
2802
-    }
2803
-
2804
-
2805
-    /**
2806
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2807
-     *
2808
-     * @return EE_Any_Foreign_Model_Name_Field
2809
-     * @throws EE_Error
2810
-     */
2811
-    public function get_field_containing_related_model_name()
2812
-    {
2813
-        foreach ($this->field_settings(true) as $field) {
2814
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2815
-                $field_with_model_name = $field;
2816
-            }
2817
-        }
2818
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2819
-            throw new EE_Error(
2820
-                sprintf(
2821
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2822
-                    $this->get_this_model_name()
2823
-                )
2824
-            );
2825
-        }
2826
-        return $field_with_model_name;
2827
-    }
2828
-
2829
-
2830
-    /**
2831
-     * Inserts a new entry into the database, for each table.
2832
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2833
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2834
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2835
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2836
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2837
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2838
-     *
2839
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2840
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2841
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2842
-     *                              of EEM_Base)
2843
-     * @return int|string new primary key on main table that got inserted
2844
-     * @throws EE_Error
2845
-     * @throws ReflectionException
2846
-     */
2847
-    public function insert($field_n_values)
2848
-    {
2849
-        /**
2850
-         * Filters the fields and their values before inserting an item using the models
2851
-         *
2852
-         * @param array    $fields_n_values keys are the fields and values are their new values
2853
-         * @param EEM_Base $model           the model used
2854
-         */
2855
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2856
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2857
-            $main_table = $this->_get_main_table();
2858
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2859
-            if ($new_id !== false) {
2860
-                foreach ($this->_get_other_tables() as $other_table) {
2861
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2862
-                }
2863
-            }
2864
-            /**
2865
-             * Done just after attempting to insert a new model object
2866
-             *
2867
-             * @param EEM_Base $model           used
2868
-             * @param array    $fields_n_values fields and their values
2869
-             * @param int|string the              ID of the newly-inserted model object
2870
-             */
2871
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2872
-            return $new_id;
2873
-        }
2874
-        return false;
2875
-    }
2876
-
2877
-
2878
-    /**
2879
-     * Checks that the result would satisfy the unique indexes on this model
2880
-     *
2881
-     * @param array  $field_n_values
2882
-     * @param string $action
2883
-     * @return boolean
2884
-     * @throws EE_Error
2885
-     * @throws ReflectionException
2886
-     */
2887
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2888
-    {
2889
-        foreach ($this->unique_indexes() as $index_name => $index) {
2890
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2891
-            if ($this->exists([$uniqueness_where_params])) {
2892
-                EE_Error::add_error(
2893
-                    sprintf(
2894
-                        esc_html__(
2895
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2896
-                            "event_espresso"
2897
-                        ),
2898
-                        $action,
2899
-                        $this->_get_class_name(),
2900
-                        $index_name,
2901
-                        implode(",", $index->field_names()),
2902
-                        http_build_query($uniqueness_where_params)
2903
-                    ),
2904
-                    __FILE__,
2905
-                    __FUNCTION__,
2906
-                    __LINE__
2907
-                );
2908
-                return false;
2909
-            }
2910
-        }
2911
-        return true;
2912
-    }
2913
-
2914
-
2915
-    /**
2916
-     * Checks the database for an item that conflicts (ie, if this item were
2917
-     * saved to the DB would break some uniqueness requirement, like a primary key
2918
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2919
-     * can be either an EE_Base_Class or an array of fields n values
2920
-     *
2921
-     * @param EE_Base_Class|array $obj_or_fields_array
2922
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2923
-     *                                                 when looking for conflicts
2924
-     *                                                 (ie, if false, we ignore the model object's primary key
2925
-     *                                                 when finding "conflicts". If true, it's also considered).
2926
-     *                                                 Only works for INT primary key,
2927
-     *                                                 STRING primary keys cannot be ignored
2928
-     * @return EE_Base_Class|array
2929
-     * @throws EE_Error
2930
-     * @throws ReflectionException
2931
-     */
2932
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2933
-    {
2934
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2935
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2936
-        } elseif (is_array($obj_or_fields_array)) {
2937
-            $fields_n_values = $obj_or_fields_array;
2938
-        } else {
2939
-            throw new EE_Error(
2940
-                sprintf(
2941
-                    esc_html__(
2942
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2943
-                        "event_espresso"
2944
-                    ),
2945
-                    get_class($this),
2946
-                    $obj_or_fields_array
2947
-                )
2948
-            );
2949
-        }
2950
-        $query_params = [];
2951
-        if (
2952
-            $this->has_primary_key_field()
2953
-            && ($include_primary_key
2954
-                || $this->get_primary_key_field()
2955
-                   instanceof
2956
-                   EE_Primary_Key_String_Field)
2957
-            && isset($fields_n_values[ $this->primary_key_name() ])
2958
-        ) {
2959
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2960
-        }
2961
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2962
-            $uniqueness_where_params                              =
2963
-                array_intersect_key($fields_n_values, $unique_index->fields());
2964
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2965
-        }
2966
-        // if there is nothing to base this search on, then we shouldn't find anything
2967
-        if (empty($query_params)) {
2968
-            return [];
2969
-        }
2970
-        return $this->get_one($query_params);
2971
-    }
2972
-
2973
-
2974
-    /**
2975
-     * Like count, but is optimized and returns a boolean instead of an int
2976
-     *
2977
-     * @param array $query_params
2978
-     * @return boolean
2979
-     * @throws EE_Error
2980
-     * @throws ReflectionException
2981
-     */
2982
-    public function exists($query_params)
2983
-    {
2984
-        $query_params['limit'] = 1;
2985
-        return $this->count($query_params) > 0;
2986
-    }
2987
-
2988
-
2989
-    /**
2990
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2991
-     *
2992
-     * @param int|string $id
2993
-     * @return boolean
2994
-     * @throws EE_Error
2995
-     * @throws ReflectionException
2996
-     */
2997
-    public function exists_by_ID($id)
2998
-    {
2999
-        return $this->exists(
3000
-            [
3001
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3002
-                [
3003
-                    $this->primary_key_name() => $id,
3004
-                ],
3005
-            ]
3006
-        );
3007
-    }
3008
-
3009
-
3010
-    /**
3011
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3012
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3013
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3014
-     * on the main table)
3015
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3016
-     * cases where we want to call it directly rather than via insert().
3017
-     *
3018
-     * @access   protected
3019
-     * @param EE_Table_Base $table
3020
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3021
-     *                                       float
3022
-     * @param int           $new_id          for now we assume only int keys
3023
-     * @return int ID of new row inserted, or FALSE on failure
3024
-     * @throws EE_Error
3025
-     * @throws ReflectionException
3026
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3027
-     */
3028
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3029
-    {
3030
-        global $wpdb;
3031
-        $insertion_col_n_values = [];
3032
-        $format_for_insertion   = [];
3033
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3034
-        foreach ($fields_on_table as $field_obj) {
3035
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3036
-            if ($field_obj->is_auto_increment()) {
3037
-                continue;
3038
-            }
3039
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3040
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3041
-            if ($prepared_value !== null) {
3042
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3043
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3044
-            }
3045
-        }
3046
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3047
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3048
-            // so add the fk to the main table as a column
3049
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3050
-            $format_for_insertion[]                              =
3051
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3052
-        }
3053
-        // insert the new entry
3054
-        $result = $this->_do_wpdb_query(
3055
-            'insert',
3056
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3057
-        );
3058
-        if ($result === false) {
3059
-            return false;
3060
-        }
3061
-        // ok, now what do we return for the ID of the newly-inserted thing?
3062
-        if ($this->has_primary_key_field()) {
3063
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3064
-                return $wpdb->insert_id;
3065
-            }
3066
-            // it's not an auto-increment primary key, so
3067
-            // it must have been supplied
3068
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3069
-        }
3070
-        // we can't return a  primary key because there is none. instead return
3071
-        // a unique string indicating this model
3072
-        return $this->get_index_primary_key_string($fields_n_values);
3073
-    }
3074
-
3075
-
3076
-    /**
3077
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3078
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3079
-     * and there is no default, we pass it along. WPDB will take care of it)
3080
-     *
3081
-     * @param EE_Model_Field_Base $field_obj
3082
-     * @param array               $fields_n_values
3083
-     * @return mixed string|int|float depending on what the table column will be expecting
3084
-     * @throws EE_Error
3085
-     */
3086
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3087
-    {
3088
-        // if this field doesn't allow nullable, don't allow it
3089
-        if (
3090
-            ! $field_obj->is_nullable()
3091
-            && (
3092
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3093
-                || $fields_n_values[ $field_obj->get_name() ] === null
3094
-            )
3095
-        ) {
3096
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3097
-        }
3098
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3099
-            ? $fields_n_values[ $field_obj->get_name() ]
3100
-            : null;
3101
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3102
-    }
3103
-
3104
-
3105
-    /**
3106
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3107
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3108
-     * the field's prepare_for_set() method.
3109
-     *
3110
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3111
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3112
-     *                                   top of file)
3113
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3114
-     *                                   $value is a custom selection
3115
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3116
-     */
3117
-    private function _prepare_value_for_use_in_db($value, $field)
3118
-    {
3119
-        if ($field && $field instanceof EE_Model_Field_Base) {
3120
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3121
-            switch ($this->_values_already_prepared_by_model_object) {
3122
-                /** @noinspection PhpMissingBreakStatementInspection */
3123
-                case self::not_prepared_by_model_object:
3124
-                    $value = $field->prepare_for_set($value);
3125
-                // purposefully left out "return"
3126
-                case self::prepared_by_model_object:
3127
-                    /** @noinspection SuspiciousAssignmentsInspection */
3128
-                    $value = $field->prepare_for_use_in_db($value);
3129
-                case self::prepared_for_use_in_db:
3130
-                    // leave the value alone
3131
-            }
3132
-            return $value;
3133
-            // phpcs:enable
3134
-        }
3135
-        return $value;
3136
-    }
3137
-
3138
-
3139
-    /**
3140
-     * Returns the main table on this model
3141
-     *
3142
-     * @return EE_Primary_Table
3143
-     * @throws EE_Error
3144
-     */
3145
-    protected function _get_main_table()
3146
-    {
3147
-        foreach ($this->_tables as $table) {
3148
-            if ($table instanceof EE_Primary_Table) {
3149
-                return $table;
3150
-            }
3151
-        }
3152
-        throw new EE_Error(
3153
-            sprintf(
3154
-                esc_html__(
3155
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3156
-                    'event_espresso'
3157
-                ),
3158
-                get_class($this)
3159
-            )
3160
-        );
3161
-    }
3162
-
3163
-
3164
-    /**
3165
-     * table
3166
-     * returns EE_Primary_Table table name
3167
-     *
3168
-     * @return string
3169
-     * @throws EE_Error
3170
-     */
3171
-    public function table()
3172
-    {
3173
-        return $this->_get_main_table()->get_table_name();
3174
-    }
3175
-
3176
-
3177
-    /**
3178
-     * table
3179
-     * returns first EE_Secondary_Table table name
3180
-     *
3181
-     * @return string
3182
-     */
3183
-    public function second_table()
3184
-    {
3185
-        // grab second table from tables array
3186
-        $second_table = end($this->_tables);
3187
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * get_table_obj_by_alias
3193
-     * returns table name given it's alias
3194
-     *
3195
-     * @param string $table_alias
3196
-     * @return EE_Primary_Table | EE_Secondary_Table
3197
-     */
3198
-    public function get_table_obj_by_alias($table_alias = '')
3199
-    {
3200
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3201
-    }
3202
-
3203
-
3204
-    /**
3205
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3206
-     *
3207
-     * @return EE_Secondary_Table[]
3208
-     */
3209
-    protected function _get_other_tables()
3210
-    {
3211
-        $other_tables = [];
3212
-        foreach ($this->_tables as $table_alias => $table) {
3213
-            if ($table instanceof EE_Secondary_Table) {
3214
-                $other_tables[ $table_alias ] = $table;
3215
-            }
3216
-        }
3217
-        return $other_tables;
3218
-    }
3219
-
3220
-
3221
-    /**
3222
-     * Finds all the fields that correspond to the given table
3223
-     *
3224
-     * @param string $table_alias , array key in EEM_Base::_tables
3225
-     * @return EE_Model_Field_Base[]
3226
-     */
3227
-    public function _get_fields_for_table($table_alias)
3228
-    {
3229
-        return $this->_fields[ $table_alias ];
3230
-    }
3231
-
3232
-
3233
-    /**
3234
-     * Recurses through all the where parameters, and finds all the related models we'll need
3235
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3236
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3237
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3238
-     * related Registration, Transaction, and Payment models.
3239
-     *
3240
-     * @param array $query_params see github link below for more info
3241
-     * @return EE_Model_Query_Info_Carrier
3242
-     * @throws EE_Error
3243
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3244
-     */
3245
-    public function _extract_related_models_from_query($query_params)
3246
-    {
3247
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3248
-        if (array_key_exists(0, $query_params)) {
3249
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3250
-        }
3251
-        if (array_key_exists('group_by', $query_params)) {
3252
-            if (is_array($query_params['group_by'])) {
3253
-                $this->_extract_related_models_from_sub_params_array_values(
3254
-                    $query_params['group_by'],
3255
-                    $query_info_carrier,
3256
-                    'group_by'
3257
-                );
3258
-            } elseif (! empty($query_params['group_by'])) {
3259
-                $this->_extract_related_model_info_from_query_param(
3260
-                    $query_params['group_by'],
3261
-                    $query_info_carrier,
3262
-                    'group_by'
3263
-                );
3264
-            }
3265
-        }
3266
-        if (array_key_exists('having', $query_params)) {
3267
-            $this->_extract_related_models_from_sub_params_array_keys(
3268
-                $query_params[0],
3269
-                $query_info_carrier,
3270
-                'having'
3271
-            );
3272
-        }
3273
-        if (array_key_exists('order_by', $query_params)) {
3274
-            if (is_array($query_params['order_by'])) {
3275
-                $this->_extract_related_models_from_sub_params_array_keys(
3276
-                    $query_params['order_by'],
3277
-                    $query_info_carrier,
3278
-                    'order_by'
3279
-                );
3280
-            } elseif (! empty($query_params['order_by'])) {
3281
-                $this->_extract_related_model_info_from_query_param(
3282
-                    $query_params['order_by'],
3283
-                    $query_info_carrier,
3284
-                    'order_by'
3285
-                );
3286
-            }
3287
-        }
3288
-        if (array_key_exists('force_join', $query_params)) {
3289
-            $this->_extract_related_models_from_sub_params_array_values(
3290
-                $query_params['force_join'],
3291
-                $query_info_carrier,
3292
-                'force_join'
3293
-            );
3294
-        }
3295
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3296
-        return $query_info_carrier;
3297
-    }
3298
-
3299
-
3300
-    /**
3301
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3302
-     *
3303
-     * @param array                       $sub_query_params
3304
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3306
-     * @throws EE_Error
3307
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3308
-     */
3309
-    private function _extract_related_models_from_sub_params_array_keys(
3310
-        $sub_query_params,
3311
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
-        $query_param_type
3313
-    ) {
3314
-        if (! empty($sub_query_params)) {
3315
-            $sub_query_params = (array)$sub_query_params;
3316
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3317
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3318
-                $this->_extract_related_model_info_from_query_param(
3319
-                    $param,
3320
-                    $model_query_info_carrier,
3321
-                    $query_param_type
3322
-                );
3323
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3324
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3325
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3326
-                // of array('Registration.TXN_ID'=>23)
3327
-                $query_param_sans_stars =
3328
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3329
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3330
-                    if (! is_array($possibly_array_of_params)) {
3331
-                        throw new EE_Error(
3332
-                            sprintf(
3333
-                                esc_html__(
3334
-                                    "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'))",
3335
-                                    "event_espresso"
3336
-                                ),
3337
-                                $param,
3338
-                                $possibly_array_of_params
3339
-                            )
3340
-                        );
3341
-                    }
3342
-                    $this->_extract_related_models_from_sub_params_array_keys(
3343
-                        $possibly_array_of_params,
3344
-                        $model_query_info_carrier,
3345
-                        $query_param_type
3346
-                    );
3347
-                } elseif (
3348
-                    $query_param_type === 0 // ie WHERE
3349
-                    && is_array($possibly_array_of_params)
3350
-                    && isset($possibly_array_of_params[2])
3351
-                    && $possibly_array_of_params[2] == true
3352
-                ) {
3353
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3354
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3355
-                    // from which we should extract query parameters!
3356
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3357
-                        throw new EE_Error(
3358
-                            sprintf(
3359
-                                esc_html__(
3360
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3361
-                                    "event_espresso"
3362
-                                ),
3363
-                                $query_param_type,
3364
-                                implode(",", $possibly_array_of_params)
3365
-                            )
3366
-                        );
3367
-                    }
3368
-                    $this->_extract_related_model_info_from_query_param(
3369
-                        $possibly_array_of_params[1],
3370
-                        $model_query_info_carrier,
3371
-                        $query_param_type
3372
-                    );
3373
-                }
3374
-            }
3375
-        }
3376
-    }
3377
-
3378
-
3379
-    /**
3380
-     * For extracting related models from forced_joins, where the array values contain the info about what
3381
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3382
-     *
3383
-     * @param array                       $sub_query_params
3384
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3385
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3386
-     * @throws EE_Error
3387
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3388
-     */
3389
-    private function _extract_related_models_from_sub_params_array_values(
3390
-        $sub_query_params,
3391
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392
-        $query_param_type
3393
-    ) {
3394
-        if (! empty($sub_query_params)) {
3395
-            if (! is_array($sub_query_params)) {
3396
-                throw new EE_Error(
3397
-                    sprintf(
3398
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
-                        $sub_query_params
3400
-                    )
3401
-                );
3402
-            }
3403
-            foreach ($sub_query_params as $param) {
3404
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3405
-                $this->_extract_related_model_info_from_query_param(
3406
-                    $param,
3407
-                    $model_query_info_carrier,
3408
-                    $query_param_type
3409
-                );
3410
-            }
3411
-        }
3412
-    }
3413
-
3414
-
3415
-    /**
3416
-     * Extract all the query parts from  model query params
3417
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
-     * but use them in a different order. Eg, we need to know what models we are querying
3420
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
-     * other models before we can finalize the where clause SQL.
3422
-     *
3423
-     * @param array $query_params see github link below for more info
3424
-     * @return EE_Model_Query_Info_Carrier
3425
-     * @throws EE_Error
3426
-     * @throws ModelConfigurationException
3427
-     * @throws ReflectionException
3428
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3429
-     */
3430
-    public function _create_model_query_info_carrier($query_params)
3431
-    {
3432
-        if (! is_array($query_params)) {
3433
-            EE_Error::doing_it_wrong(
3434
-                'EEM_Base::_create_model_query_info_carrier',
3435
-                sprintf(
3436
-                    esc_html__(
3437
-                        '$query_params should be an array, you passed a variable of type %s',
3438
-                        'event_espresso'
3439
-                    ),
3440
-                    gettype($query_params)
3441
-                ),
3442
-                '4.6.0'
3443
-            );
3444
-            $query_params = [];
3445
-        }
3446
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3447
-        // first check if we should alter the query to account for caps or not
3448
-        // because the caps might require us to do extra joins
3449
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3450
-            $query_params[0] = array_replace_recursive(
3451
-                $query_params[0],
3452
-                $this->caps_where_conditions(
3453
-                    $query_params['caps']
3454
-                )
3455
-            );
3456
-        }
3457
-
3458
-        // check if we should alter the query to remove data related to protected
3459
-        // custom post types
3460
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3461
-            $where_param_key_for_password = $this->modelChainAndPassword();
3462
-            // only include if related to a cpt where no password has been set
3463
-            $query_params[0]['OR*nopassword'] = [
3464
-                $where_param_key_for_password       => '',
3465
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3466
-            ];
3467
-        }
3468
-        $query_object = $this->_extract_related_models_from_query($query_params);
3469
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
-        foreach ($query_params[0] as $key => $value) {
3471
-            if (is_int($key)) {
3472
-                throw new EE_Error(
3473
-                    sprintf(
3474
-                        esc_html__(
3475
-                            "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.",
3476
-                            "event_espresso"
3477
-                        ),
3478
-                        $key,
3479
-                        var_export($value, true),
3480
-                        var_export($query_params, true),
3481
-                        get_class($this)
3482
-                    )
3483
-                );
3484
-            }
3485
-        }
3486
-        if (
3487
-            array_key_exists('default_where_conditions', $query_params)
3488
-            && ! empty($query_params['default_where_conditions'])
3489
-        ) {
3490
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3491
-        } else {
3492
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3493
-        }
3494
-        $query_params[0] = array_merge(
3495
-            $this->_get_default_where_conditions_for_models_in_query(
3496
-                $query_object,
3497
-                $use_default_where_conditions,
3498
-                $query_params[0]
3499
-            ),
3500
-            $query_params[0]
3501
-        );
3502
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3503
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3504
-        // So we need to setup a subquery and use that for the main join.
3505
-        // Note for now this only works on the primary table for the model.
3506
-        // So for instance, you could set the limit array like this:
3507
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3508
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3509
-            $query_object->set_main_model_join_sql(
3510
-                $this->_construct_limit_join_select(
3511
-                    $query_params['on_join_limit'][0],
3512
-                    $query_params['on_join_limit'][1]
3513
-                )
3514
-            );
3515
-        }
3516
-        // set limit
3517
-        if (array_key_exists('limit', $query_params)) {
3518
-            if (is_array($query_params['limit'])) {
3519
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3520
-                    $e = sprintf(
3521
-                        esc_html__(
3522
-                            "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)",
3523
-                            "event_espresso"
3524
-                        ),
3525
-                        http_build_query($query_params['limit'])
3526
-                    );
3527
-                    throw new EE_Error($e . "|" . $e);
3528
-                }
3529
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3531
-            } elseif (! empty($query_params['limit'])) {
3532
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3533
-            }
3534
-        }
3535
-        // set order by
3536
-        if (array_key_exists('order_by', $query_params)) {
3537
-            if (is_array($query_params['order_by'])) {
3538
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3539
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3540
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3541
-                if (array_key_exists('order', $query_params)) {
3542
-                    throw new EE_Error(
3543
-                        sprintf(
3544
-                            esc_html__(
3545
-                                "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 ",
3546
-                                "event_espresso"
3547
-                            ),
3548
-                            get_class($this),
3549
-                            implode(", ", array_keys($query_params['order_by'])),
3550
-                            implode(", ", $query_params['order_by']),
3551
-                            $query_params['order']
3552
-                        )
3553
-                    );
3554
-                }
3555
-                $this->_extract_related_models_from_sub_params_array_keys(
3556
-                    $query_params['order_by'],
3557
-                    $query_object,
3558
-                    'order_by'
3559
-                );
3560
-                // assume it's an array of fields to order by
3561
-                $order_array = [];
3562
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3563
-                    $order         = $this->_extract_order($order);
3564
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3565
-                }
3566
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3567
-            } elseif (! empty($query_params['order_by'])) {
3568
-                $this->_extract_related_model_info_from_query_param(
3569
-                    $query_params['order_by'],
3570
-                    $query_object,
3571
-                    'order',
3572
-                    $query_params['order_by']
3573
-                );
3574
-                $order = isset($query_params['order'])
3575
-                    ? $this->_extract_order($query_params['order'])
3576
-                    : 'DESC';
3577
-                $query_object->set_order_by_sql(
3578
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3579
-                );
3580
-            }
3581
-        }
3582
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3583
-        if (
3584
-            ! array_key_exists('order_by', $query_params)
3585
-            && array_key_exists('order', $query_params)
3586
-            && ! empty($query_params['order'])
3587
-        ) {
3588
-            $pk_field = $this->get_primary_key_field();
3589
-            $order    = $this->_extract_order($query_params['order']);
3590
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3591
-        }
3592
-        // set group by
3593
-        if (array_key_exists('group_by', $query_params)) {
3594
-            if (is_array($query_params['group_by'])) {
3595
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3596
-                $group_by_array = [];
3597
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3598
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3599
-                }
3600
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3601
-            } elseif (! empty($query_params['group_by'])) {
3602
-                $query_object->set_group_by_sql(
3603
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3604
-                );
3605
-            }
3606
-        }
3607
-        // set having
3608
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3609
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3610
-        }
3611
-        // now, just verify they didn't pass anything wack
3612
-        foreach ($query_params as $query_key => $query_value) {
3613
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3614
-                throw new EE_Error(
3615
-                    sprintf(
3616
-                        esc_html__(
3617
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3618
-                            'event_espresso'
3619
-                        ),
3620
-                        $query_key,
3621
-                        get_class($this),
3622
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3623
-                        implode(',', $this->_allowed_query_params)
3624
-                    )
3625
-                );
3626
-            }
3627
-        }
3628
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3629
-        if (empty($main_model_join_sql)) {
3630
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3631
-        }
3632
-        return $query_object;
3633
-    }
3634
-
3635
-
3636
-    /**
3637
-     * Gets the where conditions that should be imposed on the query based on the
3638
-     * context (eg reading frontend, backend, edit or delete).
3639
-     *
3640
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3641
-     * @return array
3642
-     * @throws EE_Error
3643
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3644
-     */
3645
-    public function caps_where_conditions($context = self::caps_read)
3646
-    {
3647
-        EEM_Base::verify_is_valid_cap_context($context);
3648
-        $cap_where_conditions = [];
3649
-        $cap_restrictions     = $this->caps_missing($context);
3650
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3651
-            $cap_where_conditions = array_replace_recursive(
3652
-                $cap_where_conditions,
3653
-                $restriction_if_no_cap->get_default_where_conditions()
3654
-            );
3655
-        }
3656
-        return apply_filters(
3657
-            'FHEE__EEM_Base__caps_where_conditions__return',
3658
-            $cap_where_conditions,
3659
-            $this,
3660
-            $context,
3661
-            $cap_restrictions
3662
-        );
3663
-    }
3664
-
3665
-
3666
-    /**
3667
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3668
-     * otherwise throws an exception
3669
-     *
3670
-     * @param string $should_be_order_string
3671
-     * @return string either ASC, asc, DESC or desc
3672
-     * @throws EE_Error
3673
-     */
3674
-    private function _extract_order($should_be_order_string)
3675
-    {
3676
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3677
-            return $should_be_order_string;
3678
-        }
3679
-        throw new EE_Error(
3680
-            sprintf(
3681
-                esc_html__(
3682
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3683
-                    "event_espresso"
3684
-                ),
3685
-                get_class($this),
3686
-                $should_be_order_string
3687
-            )
3688
-        );
3689
-    }
3690
-
3691
-
3692
-    /**
3693
-     * Looks at all the models which are included in this query, and asks each
3694
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3695
-     * so they can be merged
3696
-     *
3697
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3698
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3699
-     *                                                                  'none' means NO default where conditions will
3700
-     *                                                                  be used AT ALL during this query.
3701
-     *                                                                  'other_models_only' means default where
3702
-     *                                                                  conditions from other models will be used, but
3703
-     *                                                                  not for this primary model. 'all', the default,
3704
-     *                                                                  means default where conditions will apply as
3705
-     *                                                                  normal
3706
-     * @param array                       $where_query_params
3707
-     * @return array
3708
-     * @throws EE_Error
3709
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3710
-     */
3711
-    private function _get_default_where_conditions_for_models_in_query(
3712
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3713
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3714
-        $where_query_params = []
3715
-    ) {
3716
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3717
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3718
-            throw new EE_Error(
3719
-                sprintf(
3720
-                    esc_html__(
3721
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3722
-                        "event_espresso"
3723
-                    ),
3724
-                    $use_default_where_conditions,
3725
-                    implode(", ", $allowed_used_default_where_conditions_values)
3726
-                )
3727
-            );
3728
-        }
3729
-        $universal_query_params = [];
3730
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3731
-            $universal_query_params = $this->_get_default_where_conditions();
3732
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3733
-            $universal_query_params = $this->_get_minimum_where_conditions();
3734
-        }
3735
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
-            $related_model = $this->get_related_model_obj($model_name);
3737
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
-                $related_model_universal_where_params =
3739
-                    $related_model->_get_default_where_conditions($model_relation_path);
3740
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3741
-                $related_model_universal_where_params =
3742
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3743
-            } else {
3744
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3745
-                continue;
3746
-            }
3747
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3748
-                $related_model_universal_where_params,
3749
-                $where_query_params,
3750
-                $related_model,
3751
-                $model_relation_path
3752
-            );
3753
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3754
-                $universal_query_params,
3755
-                $overrides
3756
-            );
3757
-        }
3758
-        return $universal_query_params;
3759
-    }
3760
-
3761
-
3762
-    /**
3763
-     * Determines whether or not we should use default where conditions for the model in question
3764
-     * (this model, or other related models).
3765
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3766
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3767
-     * We should use default where conditions on related models when they requested to use default where conditions
3768
-     * on all models, or specifically just on other related models
3769
-     *
3770
-     * @param      $default_where_conditions_value
3771
-     * @param bool $for_this_model false means this is for OTHER related models
3772
-     * @return bool
3773
-     */
3774
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3775
-    {
3776
-        return (
3777
-                   $for_this_model
3778
-                   && in_array(
3779
-                       $default_where_conditions_value,
3780
-                       [
3781
-                           EEM_Base::default_where_conditions_all,
3782
-                           EEM_Base::default_where_conditions_this_only,
3783
-                           EEM_Base::default_where_conditions_minimum_others,
3784
-                       ],
3785
-                       true
3786
-                   )
3787
-               )
3788
-               || (
3789
-                   ! $for_this_model
3790
-                   && in_array(
3791
-                       $default_where_conditions_value,
3792
-                       [
3793
-                           EEM_Base::default_where_conditions_all,
3794
-                           EEM_Base::default_where_conditions_others_only,
3795
-                       ],
3796
-                       true
3797
-                   )
3798
-               );
3799
-    }
3800
-
3801
-
3802
-    /**
3803
-     * Determines whether or not we should use default minimum conditions for the model in question
3804
-     * (this model, or other related models).
3805
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3806
-     * where conditions.
3807
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3808
-     * on this model or others
3809
-     *
3810
-     * @param      $default_where_conditions_value
3811
-     * @param bool $for_this_model false means this is for OTHER related models
3812
-     * @return bool
3813
-     */
3814
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3815
-    {
3816
-        return (
3817
-                   $for_this_model
3818
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3819
-               )
3820
-               || (
3821
-                   ! $for_this_model
3822
-                   && in_array(
3823
-                       $default_where_conditions_value,
3824
-                       [
3825
-                           EEM_Base::default_where_conditions_minimum_others,
3826
-                           EEM_Base::default_where_conditions_minimum_all,
3827
-                       ],
3828
-                       true
3829
-                   )
3830
-               );
3831
-    }
3832
-
3833
-
3834
-    /**
3835
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3836
-     * then we also add a special where condition which allows for that model's primary key
3837
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3838
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3839
-     *
3840
-     * @param array    $default_where_conditions
3841
-     * @param array    $provided_where_conditions
3842
-     * @param EEM_Base $model
3843
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3844
-     * @return array
3845
-     * @throws EE_Error
3846
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3847
-     */
3848
-    private function _override_defaults_or_make_null_friendly(
3849
-        $default_where_conditions,
3850
-        $provided_where_conditions,
3851
-        $model,
3852
-        $model_relation_path
3853
-    ) {
3854
-        $null_friendly_where_conditions = [];
3855
-        $none_overridden                = true;
3856
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3857
-        foreach ($default_where_conditions as $key => $val) {
3858
-            if (isset($provided_where_conditions[ $key ])) {
3859
-                $none_overridden = false;
3860
-            } else {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3862
-            }
3863
-        }
3864
-        if ($none_overridden && $default_where_conditions) {
3865
-            if ($model->has_primary_key_field()) {
3866
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3867
-                                                                                   . "."
3868
-                                                                                   . $model->primary_key_name() ] =
3869
-                    ['IS NULL'];
3870
-            }/*else{
40
+	/**
41
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
+	 */
43
+	const caps_read       = 'read';
44
+
45
+	const caps_read_admin = 'read_admin';
46
+
47
+	const caps_edit       = 'edit';
48
+
49
+	const caps_delete     = 'delete';
50
+
51
+
52
+	/**
53
+	 * constant used to show EEM_Base has not yet verified the db on this http request
54
+	 */
55
+	const db_verified_none = 0;
56
+
57
+	/**
58
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
59
+	 * but not the addons' dbs
60
+	 */
61
+	const db_verified_core = 1;
62
+
63
+	/**
64
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
+	 * the EE core db too)
66
+	 */
67
+	const db_verified_addons = 2;
68
+
69
+	/**
70
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
73
+	 */
74
+	const default_where_conditions_all = 'all';
75
+
76
+	/**
77
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
+	 *        models which share tables with other models, this can return data for the wrong model.
82
+	 */
83
+	const default_where_conditions_this_only = 'this_model_only';
84
+
85
+	/**
86
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
+	 */
90
+	const default_where_conditions_others_only = 'other_models_only';
91
+
92
+	/**
93
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
96
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
+	 *        (regardless of whether those events and venues are trashed)
98
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
+	 *        events.
100
+	 */
101
+	const default_where_conditions_minimum_all = 'minimum';
102
+
103
+	/**
104
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
+	 *        not)
108
+	 */
109
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
+
111
+	/**
112
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
+	 *        it's possible it will return table entries for other models. You should use
115
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
116
+	 */
117
+	const default_where_conditions_none = 'none';
118
+
119
+	/**
120
+	 * when $_values_already_prepared_by_model_object equals this, we assume
121
+	 * the data is just like form input that needs to have the model fields'
122
+	 * prepare_for_set and prepare_for_use_in_db called on it
123
+	 */
124
+	const not_prepared_by_model_object = 0;
125
+
126
+	/**
127
+	 * when $_values_already_prepared_by_model_object equals this, we
128
+	 * assume this value is coming from a model object and doesn't need to have
129
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
130
+	 */
131
+	const prepared_by_model_object = 1;
132
+
133
+	/**
134
+	 * when $_values_already_prepared_by_model_object equals this, we assume
135
+	 * the values are already to be used in the database (ie no processing is done
136
+	 * on them by the model's fields)
137
+	 */
138
+	const prepared_for_use_in_db = 2;
139
+
140
+	/**
141
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
144
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
+	 *
146
+	 * @var boolean
147
+	 */
148
+	private $_values_already_prepared_by_model_object = 0;
149
+
150
+
151
+	/**
152
+	 * @var string
153
+	 */
154
+	protected $singular_item = 'Item';
155
+
156
+	/**
157
+	 * @var string
158
+	 */
159
+	protected $plural_item = 'Items';
160
+
161
+	/**
162
+	 * array of EE_Table objects for defining which tables comprise this model.
163
+	 *
164
+	 * @type EE_Table_Base[] $_tables
165
+	 */
166
+	protected $_tables;
167
+
168
+	/**
169
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
+	 *
173
+	 * @var EE_Model_Field_Base[][] $_fields
174
+	 */
175
+	protected $_fields;
176
+
177
+	/**
178
+	 * array of different kinds of relations
179
+	 *
180
+	 * @var EE_Model_Relation_Base[] $_model_relations
181
+	 */
182
+	protected $_model_relations;
183
+
184
+	/**
185
+	 * @var EE_Index[] $_indexes
186
+	 */
187
+	protected $_indexes = [];
188
+
189
+	/**
190
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
191
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
+	 * by setting the same columns as used in these queries in the query yourself.
193
+	 *
194
+	 * @var EE_Default_Where_Conditions
195
+	 */
196
+	protected $_default_where_conditions_strategy;
197
+
198
+	/**
199
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
+	 * This is particularly useful when you want something between 'none' and 'default'
201
+	 *
202
+	 * @var EE_Default_Where_Conditions
203
+	 */
204
+	protected $_minimum_where_conditions_strategy;
205
+
206
+	/**
207
+	 * String describing how to find the "owner" of this model's objects.
208
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
+	 * But when there isn't, this indicates which related model, or transiently-related model,
210
+	 * has the foreign key to the wp_users table.
211
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
+	 * related to events, and events have a foreign key to wp_users.
213
+	 * On EEM_Transaction, this would be 'Transaction.Event'
214
+	 *
215
+	 * @var string
216
+	 */
217
+	protected $_model_chain_to_wp_user = '';
218
+
219
+	/**
220
+	 * String describing how to find the model with a password controlling access to this model. This property has the
221
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
+	 * This value is the path of models to follow to arrive at the model with the password field.
223
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
+	 * model with a password that should affect reading this on the front-end.
225
+	 * Eg this is an empty string for the Event model because it has a password.
226
+	 * This is null for the Registration model, because its event's password has no bearing on whether
227
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
+	 * should hide tickets for datetimes for events that have a password set.
230
+	 *
231
+	 * @var string |null
232
+	 */
233
+	protected $model_chain_to_password = null;
234
+
235
+	/**
236
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
+	 * don't need it (particularly CPT models)
238
+	 *
239
+	 * @var bool
240
+	 */
241
+	protected $_ignore_where_strategy = false;
242
+
243
+	/**
244
+	 * String used in caps relating to this model. Eg, if the caps relating to this
245
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
+	 *
247
+	 * @var string. If null it hasn't been initialized yet. If false then we
248
+	 * have indicated capabilities don't apply to this
249
+	 */
250
+	protected $_caps_slug = null;
251
+
252
+	/**
253
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
+	 * and next-level keys are capability names, and values are a
255
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
257
+	 * and then each capability in the corresponding sub-array that they're missing
258
+	 * adds the where conditions onto the query.
259
+	 *
260
+	 * @var array
261
+	 */
262
+	protected $_cap_restrictions = [
263
+		self::caps_read       => [],
264
+		self::caps_read_admin => [],
265
+		self::caps_edit       => [],
266
+		self::caps_delete     => [],
267
+	];
268
+
269
+	/**
270
+	 * Array defining which cap restriction generators to use to create default
271
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
272
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
+	 * automatically set this to false (not just null).
275
+	 *
276
+	 * @var EE_Restriction_Generator_Base[]
277
+	 */
278
+	protected $_cap_restriction_generators = [];
279
+
280
+	/**
281
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
+	 * maps to 'read' because when looking for relevant permissions we're going to use
284
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
285
+	 *
286
+	 * @var array
287
+	 */
288
+	protected $_cap_contexts_to_cap_action_map = [
289
+		self::caps_read       => 'read',
290
+		self::caps_read_admin => 'read',
291
+		self::caps_edit       => 'edit',
292
+		self::caps_delete     => 'delete',
293
+	];
294
+
295
+	/**
296
+	 * Timezone
297
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
+	 * EE_Datetime_Field data type will have access to it.
301
+	 *
302
+	 * @var string
303
+	 */
304
+	protected $_timezone;
305
+
306
+
307
+	/**
308
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
+	 * multisite.
310
+	 *
311
+	 * @var int
312
+	 */
313
+	protected static $_model_query_blog_id;
314
+
315
+	/**
316
+	 * A copy of _fields, except the array keys are the model names pointed to by
317
+	 * the field
318
+	 *
319
+	 * @var EE_Model_Field_Base[]
320
+	 */
321
+	private $_cache_foreign_key_to_fields = [];
322
+
323
+	/**
324
+	 * Cached list of all the fields on the model, indexed by their name
325
+	 *
326
+	 * @var EE_Model_Field_Base[]
327
+	 */
328
+	private $_cached_fields = null;
329
+
330
+	/**
331
+	 * Cached list of all the fields on the model, except those that are
332
+	 * marked as only pertinent to the database
333
+	 *
334
+	 * @var EE_Model_Field_Base[]
335
+	 */
336
+	private $_cached_fields_non_db_only = null;
337
+
338
+	/**
339
+	 * A cached reference to the primary key for quick lookup
340
+	 *
341
+	 * @var EE_Model_Field_Base
342
+	 */
343
+	private $_primary_key_field = null;
344
+
345
+	/**
346
+	 * Flag indicating whether this model has a primary key or not
347
+	 *
348
+	 * @var boolean
349
+	 */
350
+	protected $_has_primary_key_field = null;
351
+
352
+	/**
353
+	 * array in the format:  [ FK alias => full PK ]
354
+	 * where keys are local column name aliases for foreign keys
355
+	 * and values are the fully qualified column name for the primary key they represent
356
+	 *  ex:
357
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
+	 *
359
+	 * @var array $foreign_key_aliases
360
+	 */
361
+	protected $foreign_key_aliases = [];
362
+
363
+	/**
364
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
365
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
+	 * This should be true for models that deal with data that should exist independent of EE.
367
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
369
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
371
+	 *
372
+	 * @var boolean
373
+	 */
374
+	protected $_wp_core_model = false;
375
+
376
+	/**
377
+	 * @var bool stores whether this model has a password field or not.
378
+	 * null until initialized by hasPasswordField()
379
+	 */
380
+	protected $has_password_field;
381
+
382
+	/**
383
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
+	 */
385
+	protected $password_field;
386
+
387
+	/**
388
+	 *    List of valid operators that can be used for querying.
389
+	 * The keys are all operators we'll accept, the values are the real SQL
390
+	 * operators used
391
+	 *
392
+	 * @var array
393
+	 */
394
+	protected $_valid_operators = [
395
+		'='           => '=',
396
+		'<='          => '<=',
397
+		'<'           => '<',
398
+		'>='          => '>=',
399
+		'>'           => '>',
400
+		'!='          => '!=',
401
+		'LIKE'        => 'LIKE',
402
+		'like'        => 'LIKE',
403
+		'NOT_LIKE'    => 'NOT LIKE',
404
+		'not_like'    => 'NOT LIKE',
405
+		'NOT LIKE'    => 'NOT LIKE',
406
+		'not like'    => 'NOT LIKE',
407
+		'IN'          => 'IN',
408
+		'in'          => 'IN',
409
+		'NOT_IN'      => 'NOT IN',
410
+		'not_in'      => 'NOT IN',
411
+		'NOT IN'      => 'NOT IN',
412
+		'not in'      => 'NOT IN',
413
+		'between'     => 'BETWEEN',
414
+		'BETWEEN'     => 'BETWEEN',
415
+		'IS_NOT_NULL' => 'IS NOT NULL',
416
+		'is_not_null' => 'IS NOT NULL',
417
+		'IS NOT NULL' => 'IS NOT NULL',
418
+		'is not null' => 'IS NOT NULL',
419
+		'IS_NULL'     => 'IS NULL',
420
+		'is_null'     => 'IS NULL',
421
+		'IS NULL'     => 'IS NULL',
422
+		'is null'     => 'IS NULL',
423
+		'REGEXP'      => 'REGEXP',
424
+		'regexp'      => 'REGEXP',
425
+		'NOT_REGEXP'  => 'NOT REGEXP',
426
+		'not_regexp'  => 'NOT REGEXP',
427
+		'NOT REGEXP'  => 'NOT REGEXP',
428
+		'not regexp'  => 'NOT REGEXP',
429
+	];
430
+
431
+	/**
432
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
+	 *
434
+	 * @var array
435
+	 */
436
+	protected $_in_style_operators = ['IN', 'NOT IN'];
437
+
438
+	/**
439
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
+	 * '12-31-2012'"
441
+	 *
442
+	 * @var array
443
+	 */
444
+	protected $_between_style_operators = ['BETWEEN'];
445
+
446
+	/**
447
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
+
453
+	/**
454
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
+	 * on a join table.
456
+	 *
457
+	 * @var array
458
+	 */
459
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
+
461
+	/**
462
+	 * Allowed values for $query_params['order'] for ordering in queries
463
+	 *
464
+	 * @var array
465
+	 */
466
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
+
468
+	/**
469
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
471
+	 *
472
+	 * @var array
473
+	 */
474
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
+
476
+	/**
477
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
479
+	 *
480
+	 * @var array
481
+	 */
482
+	private $_allowed_query_params = [
483
+		0,
484
+		'limit',
485
+		'order_by',
486
+		'group_by',
487
+		'having',
488
+		'force_join',
489
+		'order',
490
+		'on_join_limit',
491
+		'default_where_conditions',
492
+		'caps',
493
+		'extra_selects',
494
+		'exclude_protected',
495
+	];
496
+
497
+	/**
498
+	 * All the data types that can be used in $wpdb->prepare statements.
499
+	 *
500
+	 * @var array
501
+	 */
502
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
+
504
+	/**
505
+	 * @var EE_Registry $EE
506
+	 */
507
+	protected $EE = null;
508
+
509
+
510
+	/**
511
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
+	 *
513
+	 * @var int
514
+	 */
515
+	protected $_show_next_x_db_queries = 0;
516
+
517
+	/**
518
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
+	 * WHERE, GROUP_BY, etc.
521
+	 *
522
+	 * @var CustomSelects
523
+	 */
524
+	protected $_custom_selections = [];
525
+
526
+	/**
527
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
+	 * caches every model object we've fetched from the DB on this request
529
+	 *
530
+	 * @var array
531
+	 */
532
+	protected $_entity_map;
533
+
534
+	/**
535
+	 * @var LoaderInterface $loader
536
+	 */
537
+	private static $loader;
538
+
539
+	/**
540
+	 * indicates whether an EEM_Base child has already re-verified the DB
541
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
542
+	 * looking like EEM_Base::db_verified_*
543
+	 *
544
+	 * @var int - 0 = none, 1 = core, 2 = addons
545
+	 */
546
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
547
+
548
+
549
+	/**
550
+	 * About all child constructors:
551
+	 * they should define the _tables, _fields and _model_relations arrays.
552
+	 * Should ALWAYS be called after child constructor.
553
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
554
+	 * finalizes constructing all the object's attributes.
555
+	 * Generally, rather than requiring a child to code
556
+	 * $this->_tables = array(
557
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
+	 *        ...);
559
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
+	 * each EE_Table has a function to set the table's alias after the constructor, using
561
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
+	 * do something similar.
563
+	 *
564
+	 * @param string $timezone
565
+	 * @throws EE_Error
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blog id for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				/** @var $table_obj EE_Secondary_Table */
599
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
+			}
601
+		}
602
+		/**
603
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
+		 * EE_Register_Model_Extension
605
+		 *
606
+		 * @param EE_Model_Field_Base[] $_fields
607
+		 */
608
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
+		$this->_invalidate_field_caches();
610
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
611
+			if (! array_key_exists($table_alias, $this->_tables)) {
612
+				throw new EE_Error(
613
+					sprintf(
614
+						esc_html__(
615
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
+							'event_espresso'
617
+						),
618
+						$table_alias,
619
+						implode(",", $this->_fields)
620
+					)
621
+				);
622
+			}
623
+			foreach ($fields_for_table as $field_name => $field_obj) {
624
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
+				// primary key field base has a slightly different _construct_finalize
626
+				/** @var $field_obj EE_Model_Field_Base */
627
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
+			}
629
+		}
630
+		// everything is related to Extra_Meta
631
+		if (get_class($this) !== 'EEM_Extra_Meta') {
632
+			// make extra meta related to everything, but don't block deleting things just
633
+			// because they have related extra meta info. For now just orphan those extra meta
634
+			// in the future we should automatically delete them
635
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
+		}
637
+		// and change logs
638
+		if (get_class($this) !== 'EEM_Change_Log') {
639
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
+		}
641
+		/**
642
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
+		 * EE_Register_Model_Extension
644
+		 *
645
+		 * @param EE_Model_Relation_Base[] $_model_relations
646
+		 */
647
+		$this->_model_relations = (array)apply_filters(
648
+			'FHEE__' . get_class($this) . '__construct__model_relations',
649
+			$this->_model_relations
650
+		);
651
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
652
+			/** @var $relation_obj EE_Model_Relation_Base */
653
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
+		}
655
+		foreach ($this->_indexes as $index_name => $index_obj) {
656
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
+		}
658
+		$this->set_timezone($timezone);
659
+		// finalize default where condition strategy, or set default
660
+		if (! $this->_default_where_conditions_strategy) {
661
+			// nothing was set during child constructor, so set default
662
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
+		}
664
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
665
+		if (! $this->_minimum_where_conditions_strategy) {
666
+			// nothing was set during child constructor, so set default
667
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
+		}
669
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
671
+		// to indicate to NOT set it, set it to the logical default
672
+		if ($this->_caps_slug === null) {
673
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
+		}
675
+		// initialize the standard cap restriction generators if none were specified by the child constructor
676
+		if (! empty($this->_cap_restriction_generators)) {
677
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
+						new EE_Restriction_Generator_Protected(),
682
+						$cap_context,
683
+						$this
684
+					);
685
+				}
686
+			}
687
+		// }
688
+		// if ($this->_cap_restriction_generators !== false) {
689
+		// if there are cap restriction generators, use them to make the default cap restrictions
690
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
+				if (! $generator_object) {
692
+					continue;
693
+				}
694
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
+					throw new EE_Error(
696
+						sprintf(
697
+							esc_html__(
698
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
699
+								'event_espresso'
700
+							),
701
+							$context,
702
+							$this->get_this_model_name()
703
+						)
704
+					);
705
+				}
706
+				$action = $this->cap_action_for_context($context);
707
+				if (! $generator_object->construction_finalized()) {
708
+					$generator_object->_construct_finalize($this, $action);
709
+				}
710
+			}
711
+		}
712
+		do_action('AHEE__' . get_class($this) . '__construct__end');
713
+	}
714
+
715
+
716
+	/**
717
+	 * Used to set the $_model_query_blog_id static property.
718
+	 *
719
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
+	 *                      value for get_current_blog_id() will be used.
721
+	 */
722
+	public static function set_model_query_blog_id($blog_id = 0)
723
+	{
724
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
725
+	}
726
+
727
+
728
+	/**
729
+	 * Returns whatever is set as the internal $model_query_blog_id.
730
+	 *
731
+	 * @return int
732
+	 */
733
+	public static function get_model_query_blog_id()
734
+	{
735
+		return EEM_Base::$_model_query_blog_id;
736
+	}
737
+
738
+
739
+	/**
740
+	 * This function is a singleton method used to instantiate the Espresso_model object
741
+	 *
742
+	 * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
+	 *                                (and any incoming timezone data that gets saved).
744
+	 *                                Note this just sends the timezone info to the date time model field objects.
745
+	 *                                Default is NULL
746
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
+	 * @return static (as in the concrete child class)
748
+	 * @throws EE_Error
749
+	 * @throws InvalidArgumentException
750
+	 * @throws InvalidDataTypeException
751
+	 * @throws InvalidInterfaceException
752
+	 */
753
+	public static function instance($timezone = '')
754
+	{
755
+		// check if instance of Espresso_model already exists
756
+		if (! static::$_instance instanceof static) {
757
+			// instantiate Espresso_model
758
+			static::$_instance = new static(
759
+				$timezone,
760
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
+			);
762
+		}
763
+		// Espresso model object
764
+		return static::$_instance;
765
+	}
766
+
767
+
768
+	/**
769
+	 * resets the model and returns it
770
+	 *
771
+	 * @param string $timezone
772
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
+	 * all its properties reset; if it wasn't instantiated, returns null)
774
+	 * @throws EE_Error
775
+	 * @throws ReflectionException
776
+	 * @throws InvalidArgumentException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws InvalidInterfaceException
779
+	 */
780
+	public static function reset($timezone = '')
781
+	{
782
+		if (static::$_instance instanceof EEM_Base) {
783
+			// let's try to NOT swap out the current instance for a new one
784
+			// because if someone has a reference to it, we can't remove their reference
785
+			// so it's best to keep using the same reference, but change the original object
786
+			// reset all its properties to their original values as defined in the class
787
+			$r                 = new ReflectionClass(get_class(static::$_instance));
788
+			$static_properties = $r->getStaticProperties();
789
+			foreach ($r->getDefaultProperties() as $property => $value) {
790
+				// don't set instance to null like it was originally,
791
+				// but it's static anyways, and we're ignoring static properties (for now at least)
792
+				if (! isset($static_properties[ $property ])) {
793
+					static::$_instance->{$property} = $value;
794
+				}
795
+			}
796
+			EEH_DTT_Helper::resetDefaultTimezoneString();
797
+			// and then directly call its constructor again, like we would if we were creating a new one
798
+			static::$_instance->__construct(
799
+				$timezone,
800
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
+			);
802
+			return static::instance();
803
+		}
804
+		return null;
805
+	}
806
+
807
+
808
+	/**
809
+	 * @return LoaderInterface
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 */
814
+	private static function getLoader()
815
+	{
816
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
817
+			EEM_Base::$loader = LoaderFactory::getLoader();
818
+		}
819
+		return EEM_Base::$loader;
820
+	}
821
+
822
+
823
+	/**
824
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
+	 *
826
+	 * @param boolean $translated return localized strings or JUST the array.
827
+	 * @return array
828
+	 * @throws EE_Error
829
+	 * @throws InvalidArgumentException
830
+	 * @throws InvalidDataTypeException
831
+	 * @throws InvalidInterfaceException
832
+	 * @throws ReflectionException
833
+	 */
834
+	public function status_array($translated = false)
835
+	{
836
+		if (! array_key_exists('Status', $this->_model_relations)) {
837
+			return [];
838
+		}
839
+		$model_name   = $this->get_this_model_name();
840
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
+		$statuses      = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
+		$status_array = [];
843
+		foreach ($statuses as $status) {
844
+			$status_array[ $status->ID() ] = $status->get('STS_code');
845
+		}
846
+		return $translated
847
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
+			: $status_array;
849
+	}
850
+
851
+
852
+	/**
853
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
+	 *
855
+	 * @param array $query_params             see github link below for more info
856
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
861
+	 *                                        'OR'=>array(
862
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
+	 *                                        )
865
+	 *                                        ),
866
+	 *                                        'limit'=>10,
867
+	 *                                        'group_by'=>'TXN_ID'
868
+	 *                                        ));
869
+	 *                                        get all the answers to the question titled "shirt size" for event with id
870
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
+	 *                                        'Question.QST_display_text'=>'shirt size',
872
+	 *                                        'Registration.Event.EVT_ID'=>12
873
+	 *                                        ),
874
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
875
+	 *                                        ));
876
+	 * @throws EE_Error
877
+	 * @throws ReflectionException
878
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
+	 *                                        or if you have the development copy of EE you can view this at the path:
880
+	 *                                        /docs/G--Model-System/model-query-params.md
881
+	 */
882
+	public function get_all($query_params = [])
883
+	{
884
+		if (
885
+			isset($query_params['limit'])
886
+			&& ! isset($query_params['group_by'])
887
+		) {
888
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
+		}
890
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
+	}
892
+
893
+
894
+	/**
895
+	 * Modifies the query parameters so we only get back model objects
896
+	 * that "belong" to the current user
897
+	 *
898
+	 * @param array $query_params see github link below for more info
899
+	 * @return array
900
+	 * @throws ReflectionException
901
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 */
903
+	public function alter_query_params_to_only_include_mine($query_params = [])
904
+	{
905
+		$wp_user_field_name = $this->wp_user_field_name();
906
+		if ($wp_user_field_name) {
907
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
+		}
909
+		return $query_params;
910
+	}
911
+
912
+
913
+	/**
914
+	 * Returns the name of the field's name that points to the WP_User table
915
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
+	 * foreign key to the WP_User table)
917
+	 *
918
+	 * @return string|boolean string on success, boolean false when there is no
919
+	 * foreign key to the WP_User table
920
+	 * @throws ReflectionException
921
+	 */
922
+	public function wp_user_field_name()
923
+	{
924
+		try {
925
+			if (! empty($this->_model_chain_to_wp_user)) {
926
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
+				$last_model_name              = end($models_to_follow_to_wp_users);
928
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
+			} else {
931
+				$model_with_fk_to_wp_users = $this;
932
+				$model_chain_to_wp_user    = '';
933
+			}
934
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
936
+		} catch (EE_Error $e) {
937
+			return false;
938
+		}
939
+	}
940
+
941
+
942
+	/**
943
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
944
+	 * (or transiently-related model) has a foreign key to the wp_users table;
945
+	 * useful for finding if model objects of this type are 'owned' by the current user.
946
+	 * This is an empty string when the foreign key is on this model and when it isn't,
947
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
948
+	 * (or transiently-related model)
949
+	 *
950
+	 * @return string
951
+	 */
952
+	public function model_chain_to_wp_user()
953
+	{
954
+		return $this->_model_chain_to_wp_user;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
+	 * like how registrations don't have a foreign key to wp_users, but the
961
+	 * events they are for are), or is unrelated to wp users.
962
+	 * generally available
963
+	 *
964
+	 * @return boolean
965
+	 */
966
+	public function is_owned()
967
+	{
968
+		if ($this->model_chain_to_wp_user()) {
969
+			return true;
970
+		}
971
+		try {
972
+			$this->get_foreign_key_to('WP_User');
973
+			return true;
974
+		} catch (EE_Error $e) {
975
+			return false;
976
+		}
977
+	}
978
+
979
+
980
+	/**
981
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
+	 * the model)
984
+	 *
985
+	 * @param array  $query_params
986
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
989
+	 *                                  override this and set the select to "*", or a specific column name, like
990
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
+	 *                                  the aliases used to refer to this selection, and values are to be
993
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws ReflectionException
999
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
+	 */
1001
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
+	{
1003
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
+		$select_expressions       = $columns_to_select === null
1006
+			? $this->_construct_default_select_sql($model_query_info)
1007
+			: '';
1008
+		if ($this->_custom_selections instanceof CustomSelects) {
1009
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
+			$select_expressions .= $select_expressions
1011
+				? ', ' . $custom_expressions
1012
+				: $custom_expressions;
1013
+		}
1014
+
1015
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
+	 * method of including extra select information.
1024
+	 *
1025
+	 * @param array             $query_params
1026
+	 * @param null|array|string $columns_to_select
1027
+	 * @return null|CustomSelects
1028
+	 * @throws InvalidArgumentException
1029
+	 */
1030
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
+	{
1032
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
+			return null;
1034
+		}
1035
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
+		return new CustomSelects($selects);
1038
+	}
1039
+
1040
+
1041
+	/**
1042
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1043
+	 * but you can use the model query params to more easily
1044
+	 * take care of joins, field preparation etc.
1045
+	 *
1046
+	 * @param array  $query_params
1047
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1050
+	 *                                  override this and set the select to "*", or a specific column name, like
1051
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
+	 *                                  the aliases used to refer to this selection, and values are to be
1054
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
+	 * @throws EE_Error
1058
+	 * @throws ReflectionException
1059
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
+	 */
1061
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
+	{
1063
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * For creating a custom select statement
1069
+	 *
1070
+	 * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
+	 *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
+	 *                                        selection SQL, and 1=>is the datatype
1073
+	 * @return string
1074
+	 * @throws EE_Error
1075
+	 */
1076
+	private function _construct_select_from_input($columns_to_select)
1077
+	{
1078
+		if (is_array($columns_to_select)) {
1079
+			$select_sql_array = [];
1080
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype,
1089
+							$alias
1090
+						)
1091
+					);
1092
+				}
1093
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
+					throw new EE_Error(
1095
+						sprintf(
1096
+							esc_html__(
1097
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
+								'event_espresso'
1099
+							),
1100
+							$selection_and_datatype[1],
1101
+							$selection_and_datatype[0],
1102
+							$alias,
1103
+							implode(', ', $this->_valid_wpdb_data_types)
1104
+						)
1105
+					);
1106
+				}
1107
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
+			}
1109
+			$columns_to_select_string = implode(', ', $select_sql_array);
1110
+		} else {
1111
+			$columns_to_select_string = $columns_to_select;
1112
+		}
1113
+		return $columns_to_select_string;
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
+	 *
1120
+	 * @return string
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function primary_key_name()
1124
+	{
1125
+		return $this->get_primary_key_field()->get_name();
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
+	 * If there is no primary key on this model, $id is treated as primary key string
1132
+	 *
1133
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1134
+	 * @return EE_Base_Class
1135
+	 * @throws EE_Error
1136
+	 * @throws ReflectionException
1137
+	 */
1138
+	public function get_one_by_ID($id)
1139
+	{
1140
+		if ($this->get_from_entity_map($id)) {
1141
+			return $this->get_from_entity_map($id);
1142
+		}
1143
+		$model_object = $this->get_one(
1144
+			$this->alter_query_params_to_restrict_by_ID(
1145
+				$id,
1146
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
+			)
1148
+		);
1149
+		$className = $this->_get_class_name();
1150
+		if ($model_object instanceof $className) {
1151
+			// make sure valid objects get added to the entity map
1152
+			// so that the next call to this method doesn't trigger another trip to the db
1153
+			$this->add_to_entity_map($model_object);
1154
+		}
1155
+		return $model_object;
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * Alters query parameters to only get items with this ID are returned.
1161
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1162
+	 * or could just be a simple primary key ID
1163
+	 *
1164
+	 * @param int   $id
1165
+	 * @param array $query_params see github link below for more info
1166
+	 * @return array of normal query params,
1167
+	 * @throws EE_Error
1168
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1169
+	 */
1170
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1171
+	{
1172
+		if (! isset($query_params[0])) {
1173
+			$query_params[0] = [];
1174
+		}
1175
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1176
+		if ($conditions_from_id === null) {
1177
+			$query_params[0][ $this->primary_key_name() ] = $id;
1178
+		} else {
1179
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1180
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1181
+		}
1182
+		return $query_params;
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1188
+	 * array. If no item is found, null is returned.
1189
+	 *
1190
+	 * @param array $query_params like EEM_Base's $query_params variable.
1191
+	 * @return EE_Base_Class|null
1192
+	 * @throws EE_Error
1193
+	 * @throws ReflectionException
1194
+	 */
1195
+	public function get_one(array $query_params = [])
1196
+	{
1197
+		if (! is_array($query_params)) {
1198
+			EE_Error::doing_it_wrong(
1199
+				'EEM_Base::get_one',
1200
+				sprintf(
1201
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1202
+					gettype($query_params)
1203
+				),
1204
+				'4.6.0'
1205
+			);
1206
+			$query_params = [];
1207
+		}
1208
+		$query_params['limit'] = 1;
1209
+		$items                 = $this->get_all($query_params);
1210
+		if (empty($items)) {
1211
+			return null;
1212
+		}
1213
+		return array_shift($items);
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * Returns the next x number of items in sequence from the given value as
1219
+	 * found in the database matching the given query conditions.
1220
+	 *
1221
+	 * @param mixed $current_field_value    Value used for the reference point.
1222
+	 * @param null  $field_to_order_by      What field is used for the
1223
+	 *                                      reference point.
1224
+	 * @param int   $limit                  How many to return.
1225
+	 * @param array $query_params           Extra conditions on the query.
1226
+	 * @param null  $columns_to_select      If left null, then an array of
1227
+	 *                                      EE_Base_Class objects is returned,
1228
+	 *                                      otherwise you can indicate just the
1229
+	 *                                      columns you want returned.
1230
+	 * @return EE_Base_Class[]|array
1231
+	 * @throws EE_Error
1232
+	 * @throws ReflectionException
1233
+	 */
1234
+	public function next_x(
1235
+		$current_field_value,
1236
+		$field_to_order_by = null,
1237
+		$limit = 1,
1238
+		$query_params = [],
1239
+		$columns_to_select = null
1240
+	) {
1241
+		return $this->_get_consecutive(
1242
+			$current_field_value,
1243
+			'>',
1244
+			$field_to_order_by,
1245
+			$limit,
1246
+			$query_params,
1247
+			$columns_to_select
1248
+		);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Returns the previous x number of items in sequence from the given value
1254
+	 * as found in the database matching the given query conditions.
1255
+	 *
1256
+	 * @param mixed $current_field_value    Value used for the reference point.
1257
+	 * @param null  $field_to_order_by      What field is used for the
1258
+	 *                                      reference point.
1259
+	 * @param int   $limit                  How many to return.
1260
+	 * @param array $query_params           Extra conditions on the query.
1261
+	 * @param null  $columns_to_select      If left null, then an array of
1262
+	 *                                      EE_Base_Class objects is returned,
1263
+	 *                                      otherwise you can indicate just the
1264
+	 *                                      columns you want returned.
1265
+	 * @return EE_Base_Class[]|array
1266
+	 * @throws EE_Error
1267
+	 * @throws ReflectionException
1268
+	 */
1269
+	public function previous_x(
1270
+		$current_field_value,
1271
+		$field_to_order_by = null,
1272
+		$limit = 1,
1273
+		$query_params = [],
1274
+		$columns_to_select = null
1275
+	) {
1276
+		return $this->_get_consecutive(
1277
+			$current_field_value,
1278
+			'<',
1279
+			$field_to_order_by,
1280
+			$limit,
1281
+			$query_params,
1282
+			$columns_to_select
1283
+		);
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * Returns the next item in sequence from the given value as found in the
1289
+	 * database matching the given query conditions.
1290
+	 *
1291
+	 * @param mixed $current_field_value    Value used for the reference point.
1292
+	 * @param null  $field_to_order_by      What field is used for the
1293
+	 *                                      reference point.
1294
+	 * @param array $query_params           Extra conditions on the query.
1295
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1296
+	 *                                      object is returned, otherwise you
1297
+	 *                                      can indicate just the columns you
1298
+	 *                                      want and a single array indexed by
1299
+	 *                                      the columns will be returned.
1300
+	 * @return EE_Base_Class|null|array()
1301
+	 * @throws EE_Error
1302
+	 * @throws ReflectionException
1303
+	 */
1304
+	public function next(
1305
+		$current_field_value,
1306
+		$field_to_order_by = null,
1307
+		$query_params = [],
1308
+		$columns_to_select = null
1309
+	) {
1310
+		$results = $this->_get_consecutive(
1311
+			$current_field_value,
1312
+			'>',
1313
+			$field_to_order_by,
1314
+			1,
1315
+			$query_params,
1316
+			$columns_to_select
1317
+		);
1318
+		return empty($results) ? null : reset($results);
1319
+	}
1320
+
1321
+
1322
+	/**
1323
+	 * Returns the previous item in sequence from the given value as found in
1324
+	 * the database matching the given query conditions.
1325
+	 *
1326
+	 * @param mixed $current_field_value    Value used for the reference point.
1327
+	 * @param null  $field_to_order_by      What field is used for the
1328
+	 *                                      reference point.
1329
+	 * @param array $query_params           Extra conditions on the query.
1330
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1331
+	 *                                      object is returned, otherwise you
1332
+	 *                                      can indicate just the columns you
1333
+	 *                                      want and a single array indexed by
1334
+	 *                                      the columns will be returned.
1335
+	 * @return EE_Base_Class|null|array()
1336
+	 * @throws EE_Error
1337
+	 * @throws ReflectionException
1338
+	 */
1339
+	public function previous(
1340
+		$current_field_value,
1341
+		$field_to_order_by = null,
1342
+		$query_params = [],
1343
+		$columns_to_select = null
1344
+	) {
1345
+		$results = $this->_get_consecutive(
1346
+			$current_field_value,
1347
+			'<',
1348
+			$field_to_order_by,
1349
+			1,
1350
+			$query_params,
1351
+			$columns_to_select
1352
+		);
1353
+		return empty($results) ? null : reset($results);
1354
+	}
1355
+
1356
+
1357
+	/**
1358
+	 * Returns the a consecutive number of items in sequence from the given
1359
+	 * value as found in the database matching the given query conditions.
1360
+	 *
1361
+	 * @param mixed  $current_field_value   Value used for the reference point.
1362
+	 * @param string $operand               What operand is used for the sequence.
1363
+	 * @param string $field_to_order_by     What field is used for the reference point.
1364
+	 * @param int    $limit                 How many to return.
1365
+	 * @param array  $query_params          Extra conditions on the query.
1366
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1367
+	 *                                      otherwise you can indicate just the columns you want returned.
1368
+	 * @return EE_Base_Class[]|array
1369
+	 * @throws EE_Error
1370
+	 * @throws ReflectionException
1371
+	 */
1372
+	protected function _get_consecutive(
1373
+		$current_field_value,
1374
+		$operand = '>',
1375
+		$field_to_order_by = null,
1376
+		$limit = 1,
1377
+		$query_params = [],
1378
+		$columns_to_select = null
1379
+	) {
1380
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1381
+		if (empty($field_to_order_by)) {
1382
+			if ($this->has_primary_key_field()) {
1383
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1384
+			} else {
1385
+				if (WP_DEBUG) {
1386
+					throw new EE_Error(
1387
+						esc_html__(
1388
+							'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).',
1389
+							'event_espresso'
1390
+						)
1391
+					);
1392
+				}
1393
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1394
+				return [];
1395
+			}
1396
+		}
1397
+		if (! is_array($query_params)) {
1398
+			EE_Error::doing_it_wrong(
1399
+				'EEM_Base::_get_consecutive',
1400
+				sprintf(
1401
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1402
+					gettype($query_params)
1403
+				),
1404
+				'4.6.0'
1405
+			);
1406
+			$query_params = [];
1407
+		}
1408
+		// let's add the where query param for consecutive look up.
1409
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1410
+		$query_params['limit']                 = $limit;
1411
+		// set direction
1412
+		$incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1413
+		$query_params['order_by'] = $operand === '>'
1414
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1415
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1416
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1417
+		if (empty($columns_to_select)) {
1418
+			return $this->get_all($query_params);
1419
+		}
1420
+		// getting just the fields
1421
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * This sets the _timezone property after model object has been instantiated.
1427
+	 *
1428
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1429
+	 */
1430
+	public function set_timezone($timezone = '')
1431
+	{
1432
+		static $set_in_progress = false;
1433
+		// if incoming timezone string is empty, then use the existing
1434
+		$valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1435
+			? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1436
+			: $this->_timezone;
1437
+		// do NOT set the timezone if we are already in the process of setting the timezone
1438
+		// OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1439
+		// OR the existing timezone is already set and the validated value is the same as the existing timezone
1440
+		if (
1441
+			$set_in_progress
1442
+			|| (
1443
+				! empty($this->_timezone)
1444
+				&& (
1445
+					empty($timezone) || $valid_timezone === $this->_timezone
1446
+				)
1447
+			)
1448
+		) {
1449
+			return;
1450
+		}
1451
+		$set_in_progress = true;
1452
+		$this->_timezone = $valid_timezone ?: EEH_DTT_Helper::get_valid_timezone_string();
1453
+		// note we need to loop through relations and set the timezone on those objects as well.
1454
+		foreach ($this->_model_relations as $relation) {
1455
+			$relation->set_timezone($this->_timezone);
1456
+		}
1457
+		// and finally we do the same for any datetime fields
1458
+		foreach ($this->_fields as $field) {
1459
+			if ($field instanceof EE_Datetime_Field) {
1460
+				$field->set_timezone($this->_timezone);
1461
+			}
1462
+		}
1463
+		$set_in_progress = false;
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This just returns whatever is set for the current timezone.
1469
+	 *
1470
+	 * @access public
1471
+	 * @return string
1472
+	 */
1473
+	public function get_timezone()
1474
+	{
1475
+		if (empty($this->_timezone)) {
1476
+			$this->set_timezone();
1477
+		}
1478
+		return $this->_timezone;
1479
+	}
1480
+
1481
+
1482
+	/**
1483
+	 * This returns the date formats set for the given field name and also ensures that
1484
+	 * $this->_timezone property is set correctly.
1485
+	 *
1486
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1487
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488
+	 * @return array formats in an array with the date format first, and the time format last.
1489
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1490
+	 * @since 4.6.x
1491
+	 */
1492
+	public function get_formats_for($field_name, $pretty = false)
1493
+	{
1494
+		$field_settings = $this->field_settings_for($field_name);
1495
+		// if not a valid EE_Datetime_Field then throw error
1496
+		if (! $field_settings instanceof EE_Datetime_Field) {
1497
+			throw new EE_Error(
1498
+				sprintf(
1499
+					esc_html__(
1500
+						'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.',
1501
+						'event_espresso'
1502
+					),
1503
+					$field_name
1504
+				)
1505
+			);
1506
+		}
1507
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1508
+		$field_timezone = $field_settings->get_timezone();
1509
+		if (empty($this->_timezone && $field_timezone)) {
1510
+			$this->set_timezone();
1511
+		} else {
1512
+			// or vice versa if the field TZ isn't set
1513
+			$model_timezone = $this->get_timezone();
1514
+			$field_settings->set_timezone($model_timezone);
1515
+		}
1516
+
1517
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1518
+	}
1519
+
1520
+
1521
+	/**
1522
+	 * This returns the current time in a format setup for a query on this model.
1523
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
+	 * it will return:
1525
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field
1526
+	 *    for the given field for NOW
1527
+	 *  - or a unix timestamp (equivalent to time())
1528
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
+	 *
1532
+	 * @param string $field_name    The field the current time is needed for.
1533
+	 * @param bool $timestamp       True means to return a unix timestamp.
1534
+	 *                              Otherwise a formatted string matching the set format for the field
1535
+	 *                              in the set timezone will be returned.
1536
+	 * @param string $what          Whether to return the string in just the time format, the date format, or both.
1537
+	 * @return string               If the given field_name is not of the EE_Datetime_Field type,
1538
+	 *                              then an EE_Error exception is triggered.
1539
+	 * @throws EE_Error             If the given field_name is not of the EE_Datetime_Field type.
1540
+	 * @throws Exception
1541
+	 * @since 4.6.x
1542
+	 */
1543
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1544
+	{
1545
+		$formats  = $this->get_formats_for($field_name);
1546
+		$DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1547
+		if ($timestamp) {
1548
+			return $DateTime->format('U');
1549
+		}
1550
+		// not returning timestamp, so return formatted string in timezone.
1551
+		switch ($what) {
1552
+			case 'time':
1553
+				return $DateTime->format($formats[1]);
1554
+			case 'date':
1555
+				return $DateTime->format($formats[0]);
1556
+			default:
1557
+				return $DateTime->format(implode(' ', $formats));
1558
+		}
1559
+	}
1560
+
1561
+
1562
+	/**
1563
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1564
+	 * for the model are.  Returns a DateTime object.
1565
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1566
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1567
+	 * ignored.
1568
+	 *
1569
+	 * @param string $field_name    The field being setup.
1570
+	 * @param string $timestring    The date time string being used.
1571
+	 * @param string $format        The format for the time string.
1572
+	 * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1573
+	 *                              the blog.  If this is not the case, then it can be specified here.
1574
+	 *                              If incoming format is 'U', this is ignored.
1575
+	 * @return DbSafeDateTime
1576
+	 * @throws EE_Error
1577
+	 * @throws Exception
1578
+	 */
1579
+	public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1580
+	{
1581
+		// just using this to ensure the timezone is set correctly internally
1582
+		$this->get_formats_for($field_name);
1583
+		$timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1584
+		$db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1585
+		EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1586
+		return $db_safe_datetime;
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
+	 *
1593
+	 * @return EE_Table_Base[]
1594
+	 */
1595
+	public function get_tables()
1596
+	{
1597
+		return $this->_tables;
1598
+	}
1599
+
1600
+
1601
+	/**
1602
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1603
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1604
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1605
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1606
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1607
+	 * model object with EVT_ID = 1
1608
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1609
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1610
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1611
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1612
+	 * are not specified)
1613
+	 *
1614
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1615
+	 *                                         columns!), values are strings, integers, floats, and maybe arrays if
1616
+	 *                                         they
1617
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1620
+	 *                                         ID=34, we'd use this method as follows:
1621
+	 *                                         EEM_Transaction::instance()->update(
1622
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
+	 *                                         array(array('TXN_ID'=>34)));
1624
+	 * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1625
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1626
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1627
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1628
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1629
+	 *                                         TRUE, it is assumed that you've already called
1630
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1631
+	 *                                         malicious javascript. However, if
1632
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1633
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1634
+	 *                                         and every other field, before insertion. We provide this parameter
1635
+	 *                                         because model objects perform their prepare_for_set function on all
1636
+	 *                                         their values, and so don't need to be called again (and in many cases,
1637
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1638
+	 *                                         prepare_for_set method...)
1639
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1640
+	 *                                         in this model's entity map according to $fields_n_values that match
1641
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1642
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1643
+	 *                                         could get out-of-sync with the database
1644
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1645
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1646
+	 *                                         bad)
1647
+	 * @throws EE_Error
1648
+	 * @throws ReflectionException
1649
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
+	 */
1651
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
+	{
1653
+		if (! is_array($query_params)) {
1654
+			EE_Error::doing_it_wrong(
1655
+				'EEM_Base::update',
1656
+				sprintf(
1657
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1658
+					gettype($query_params)
1659
+				),
1660
+				'4.6.0'
1661
+			);
1662
+			$query_params = [];
1663
+		}
1664
+		/**
1665
+		 * Action called before a model update call has been made.
1666
+		 *
1667
+		 * @param EEM_Base $model
1668
+		 * @param array    $fields_n_values the updated fields and their new values
1669
+		 * @param array    $query_params
1670
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1671
+		 */
1672
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1673
+		/**
1674
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1675
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1676
+		 *
1677
+		 * @param array    $fields_n_values fields and their new values
1678
+		 * @param EEM_Base $model           the model being queried
1679
+		 * @param array    $query_params
1680
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1681
+		 */
1682
+		$fields_n_values = (array)apply_filters(
1683
+			'FHEE__EEM_Base__update__fields_n_values',
1684
+			$fields_n_values,
1685
+			$this,
1686
+			$query_params
1687
+		);
1688
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1689
+		// to do that, for each table, verify that it's PK isn't null.
1690
+		$tables = $this->get_tables();
1691
+		// 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
1692
+		// NOTE: we should make this code more efficient by NOT querying twice
1693
+		// before the real update, but that needs to first go through ALPHA testing
1694
+		// as it's dangerous. says Mike August 8 2014
1695
+		// we want to make sure the default_where strategy is ignored
1696
+		$this->_ignore_where_strategy = true;
1697
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1698
+		foreach ($wpdb_select_results as $wpdb_result) {
1699
+			// type cast stdClass as array
1700
+			$wpdb_result = (array)$wpdb_result;
1701
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1702
+			if ($this->has_primary_key_field()) {
1703
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1704
+			} else {
1705
+				// 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)
1706
+				$main_table_pk_value = null;
1707
+			}
1708
+			// 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
1709
+			// 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
1710
+			if (count($tables) > 1) {
1711
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1712
+				// in that table, and so we'll want to insert one
1713
+				foreach ($tables as $table_obj) {
1714
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1715
+					// if there is no private key for this table on the results, it means there's no entry
1716
+					// in this table, right? so insert a row in the current table, using any fields available
1717
+					if (
1718
+					! (array_key_exists($this_table_pk_column, $wpdb_result)
1719
+					   && $wpdb_result[ $this_table_pk_column ])
1720
+					) {
1721
+						$success = $this->_insert_into_specific_table(
1722
+							$table_obj,
1723
+							$fields_n_values,
1724
+							$main_table_pk_value
1725
+						);
1726
+						// if we died here, report the error
1727
+						if (! $success) {
1728
+							return false;
1729
+						}
1730
+					}
1731
+				}
1732
+			}
1733
+			// let's make sure default_where strategy is followed now
1734
+			$this->_ignore_where_strategy = false;
1735
+		}
1736
+		// if we want to keep model objects in sync, AND
1737
+		// if this wasn't called from a model object (to update itself)
1738
+		// then we want to make sure we keep all the existing
1739
+		// model objects in sync with the db
1740
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1741
+			if ($this->has_primary_key_field()) {
1742
+				$model_objs_affected_ids = $this->get_col($query_params);
1743
+			} else {
1744
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1745
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1746
+				$model_objs_affected_ids     = [];
1747
+				foreach ($models_affected_key_columns as $row) {
1748
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1749
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1750
+				}
1751
+			}
1752
+			if (! $model_objs_affected_ids) {
1753
+				// wait wait wait- if nothing was affected let's stop here
1754
+				return 0;
1755
+			}
1756
+			foreach ($model_objs_affected_ids as $id) {
1757
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1758
+				if ($model_obj_in_entity_map) {
1759
+					foreach ($fields_n_values as $field => $new_value) {
1760
+						$model_obj_in_entity_map->set($field, $new_value);
1761
+					}
1762
+				}
1763
+			}
1764
+			// if there is a primary key on this model, we can now do a slight optimization
1765
+			if ($this->has_primary_key_field()) {
1766
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1767
+				$query_params = [
1768
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1769
+					'limit'                    => count($model_objs_affected_ids),
1770
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1771
+				];
1772
+			}
1773
+		}
1774
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
+		$SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1776
+							. " SET " . $this->_construct_update_sql($fields_n_values)
1777
+							. $model_query_info->get_where_sql();
1778
+		// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1779
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1780
+		/**
1781
+		 * Action called after a model update call has been made.
1782
+		 *
1783
+		 * @param EEM_Base $model
1784
+		 * @param array    $fields_n_values the updated fields and their new values
1785
+		 * @param array    $query_params
1786
+		 * @param int      $rows_affected
1787
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1788
+		 */
1789
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1790
+		return $rows_affected;// how many supposedly got updated
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1796
+	 * are teh values of the field specified (or by default the primary key field)
1797
+	 * that matched the query params. Note that you should pass the name of the
1798
+	 * model FIELD, not the database table's column name.
1799
+	 *
1800
+	 * @param array  $query_params
1801
+	 * @param string $field_to_select
1802
+	 * @return array just like $wpdb->get_col()
1803
+	 * @throws EE_Error
1804
+	 * @throws ReflectionException
1805
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1806
+	 */
1807
+	public function get_col($query_params = [], $field_to_select = null)
1808
+	{
1809
+		if ($field_to_select) {
1810
+			$field = $this->field_settings_for($field_to_select);
1811
+		} elseif ($this->has_primary_key_field()) {
1812
+			$field = $this->get_primary_key_field();
1813
+		} else {
1814
+			$field_settings = $this->field_settings();
1815
+			// no primary key, just grab the first column
1816
+			$field = reset($field_settings);
1817
+		}
1818
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1819
+		$select_expressions = $field->get_qualified_column();
1820
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1821
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1822
+	}
1823
+
1824
+
1825
+	/**
1826
+	 * Returns a single column value for a single row from the database
1827
+	 *
1828
+	 * @param array  $query_params
1829
+	 * @param string $field_to_select
1830
+	 * @return string
1831
+	 * @throws EE_Error
1832
+	 * @throws ReflectionException
1833
+	 * @see EEM_Base::get_col()
1834
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1835
+	 */
1836
+	public function get_var($query_params = [], $field_to_select = null)
1837
+	{
1838
+		$query_params['limit'] = 1;
1839
+		$col                   = $this->get_col($query_params, $field_to_select);
1840
+		if (! empty($col)) {
1841
+			return reset($col);
1842
+		}
1843
+		return null;
1844
+	}
1845
+
1846
+
1847
+	/**
1848
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1849
+	 * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1850
+	 * injection, but currently no further filtering is done
1851
+	 *
1852
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1853
+	 *                               be updated to in the DB
1854
+	 * @return string of SQL
1855
+	 * @throws EE_Error
1856
+	 * @global      $wpdb
1857
+	 */
1858
+	public function _construct_update_sql($fields_n_values)
1859
+	{
1860
+		global $wpdb;
1861
+		$cols_n_values = [];
1862
+		foreach ($fields_n_values as $field_name => $value) {
1863
+			$field_obj = $this->field_settings_for($field_name);
1864
+			// if the value is NULL, we want to assign the value to that.
1865
+			// wpdb->prepare doesn't really handle that properly
1866
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1867
+			$value_sql       = $prepared_value === null
1868
+				? 'NULL'
1869
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1870
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1871
+		}
1872
+		return implode(",", $cols_n_values);
1873
+	}
1874
+
1875
+
1876
+	/**
1877
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1878
+	 * Performs a HARD delete, meaning the database row should always be removed,
1879
+	 * not just have a flag field on it switched
1880
+	 * Wrapper for EEM_Base::delete_permanently()
1881
+	 *
1882
+	 * @param mixed   $id
1883
+	 * @param boolean $allow_blocking
1884
+	 * @return int the number of rows deleted
1885
+	 * @throws EE_Error
1886
+	 * @throws ReflectionException
1887
+	 */
1888
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1889
+	{
1890
+		return $this->delete_permanently(
1891
+			[
1892
+				[$this->get_primary_key_field()->get_name() => $id],
1893
+				'limit' => 1,
1894
+			],
1895
+			$allow_blocking
1896
+		);
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
+	 * Wrapper for EEM_Base::delete()
1903
+	 *
1904
+	 * @param mixed   $id
1905
+	 * @param boolean $allow_blocking
1906
+	 * @return int the number of rows deleted
1907
+	 * @throws EE_Error
1908
+	 * @throws ReflectionException
1909
+	 */
1910
+	public function delete_by_ID($id, $allow_blocking = true)
1911
+	{
1912
+		return $this->delete(
1913
+			[
1914
+				[$this->get_primary_key_field()->get_name() => $id],
1915
+				'limit' => 1,
1916
+			],
1917
+			$allow_blocking
1918
+		);
1919
+	}
1920
+
1921
+
1922
+	/**
1923
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1924
+	 * meaning if the model has a field that indicates its been "trashed" or
1925
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1926
+	 *
1927
+	 * @param array   $query_params
1928
+	 * @param boolean $allow_blocking
1929
+	 * @return int how many rows got deleted
1930
+	 * @throws EE_Error
1931
+	 * @throws ReflectionException
1932
+	 * @see EEM_Base::delete_permanently
1933
+	 */
1934
+	public function delete($query_params, $allow_blocking = true)
1935
+	{
1936
+		return $this->delete_permanently($query_params, $allow_blocking);
1937
+	}
1938
+
1939
+
1940
+	/**
1941
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1942
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1943
+	 * as archived, not actually deleted
1944
+	 *
1945
+	 * @param array   $query_params
1946
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1947
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1948
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1949
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1950
+	 *                                DB
1951
+	 * @return int how many rows got deleted
1952
+	 * @throws EE_Error
1953
+	 * @throws ReflectionException
1954
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1955
+	 */
1956
+	public function delete_permanently($query_params, $allow_blocking = true)
1957
+	{
1958
+		/**
1959
+		 * Action called just before performing a real deletion query. You can use the
1960
+		 * model and its $query_params to find exactly which items will be deleted
1961
+		 *
1962
+		 * @param EEM_Base $model
1963
+		 * @param array    $query_params
1964
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1965
+		 *                                 to block (prevent) this deletion
1966
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1967
+		 */
1968
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1969
+		// some MySQL databases may be running safe mode, which may restrict
1970
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1971
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1972
+		// to delete them
1973
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1974
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1975
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1976
+			$columns_and_ids_for_deleting
1977
+		);
1978
+		/**
1979
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1980
+		 *
1981
+		 * @param EEM_Base $this                            The model instance being acted on.
1982
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1983
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1984
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1985
+		 *                                                  derived from the incoming query parameters.
1986
+		 * @see details on the structure of this array in the phpdocs
1987
+		 *                                                  for the `_get_ids_for_delete_method`
1988
+		 *
1989
+		 */
1990
+		do_action(
1991
+			'AHEE__EEM_Base__delete__before_query',
1992
+			$this,
1993
+			$query_params,
1994
+			$allow_blocking,
1995
+			$columns_and_ids_for_deleting
1996
+		);
1997
+		if ($deletion_where_query_part) {
1998
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1999
+			$table_aliases    = implode(', ', array_keys($this->_tables));
2000
+			$SQL              = "DELETE " . $table_aliases
2001
+								. " FROM " . $model_query_info->get_full_join_sql()
2002
+								. " WHERE " . $deletion_where_query_part;
2003
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2004
+		} else {
2005
+			$rows_deleted = 0;
2006
+		}
2007
+
2008
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2009
+		// there was no error with the delete query.
2010
+		if (
2011
+			$this->has_primary_key_field()
2012
+			&& $rows_deleted !== false
2013
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2014
+		) {
2015
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2016
+			foreach ($ids_for_removal as $id) {
2017
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2018
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2019
+				}
2020
+			}
2021
+
2022
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2023
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2024
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2025
+			// (although it is possible).
2026
+			// Note this can be skipped by using the provided filter and returning false.
2027
+			if (
2028
+			apply_filters(
2029
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2030
+				! $this instanceof EEM_Extra_Meta,
2031
+				$this
2032
+			)
2033
+			) {
2034
+				EEM_Extra_Meta::instance()->delete_permanently(
2035
+					[
2036
+						0 => [
2037
+							'EXM_type' => $this->get_this_model_name(),
2038
+							'OBJ_ID'   => [
2039
+								'IN',
2040
+								$ids_for_removal,
2041
+							],
2042
+						],
2043
+					]
2044
+				);
2045
+			}
2046
+		}
2047
+
2048
+		/**
2049
+		 * Action called just after performing a real deletion query. Although at this point the
2050
+		 * items should have been deleted
2051
+		 *
2052
+		 * @param EEM_Base $model
2053
+		 * @param array    $query_params
2054
+		 * @param int      $rows_deleted
2055
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2056
+		 */
2057
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
+		return $rows_deleted;// how many supposedly got deleted
2059
+	}
2060
+
2061
+
2062
+	/**
2063
+	 * Checks all the relations that throw error messages when there are blocking related objects
2064
+	 * for related model objects. If there are any related model objects on those relations,
2065
+	 * adds an EE_Error, and return true
2066
+	 *
2067
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2068
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2069
+	 *                                                 should be ignored when determining whether there are related
2070
+	 *                                                 model objects which block this model object's deletion. Useful
2071
+	 *                                                 if you know A is related to B and are considering deleting A,
2072
+	 *                                                 but want to see if A has any other objects blocking its deletion
2073
+	 *                                                 before removing the relation between A and B
2074
+	 * @return boolean
2075
+	 * @throws EE_Error
2076
+	 * @throws ReflectionException
2077
+	 */
2078
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
+	{
2080
+		// first, if $ignore_this_model_obj was supplied, get its model
2081
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
+			$ignored_model = $ignore_this_model_obj->get_model();
2083
+		} else {
2084
+			$ignored_model = null;
2085
+		}
2086
+		// now check all the relations of $this_model_obj_or_id and see if there
2087
+		// are any related model objects blocking it?
2088
+		$is_blocked = false;
2089
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2091
+				// if $ignore_this_model_obj was supplied, then for the query
2092
+				// on that model needs to be told to ignore $ignore_this_model_obj
2093
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
+					$related_model_objects = $relation_obj->get_all_related(
2095
+						$this_model_obj_or_id,
2096
+						[
2097
+							[
2098
+								$ignored_model->get_primary_key_field()->get_name() => [
2099
+									'!=',
2100
+									$ignore_this_model_obj->ID(),
2101
+								],
2102
+							],
2103
+						]
2104
+					);
2105
+				} else {
2106
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2107
+				}
2108
+				if ($related_model_objects) {
2109
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2110
+					$is_blocked = true;
2111
+				}
2112
+			}
2113
+		}
2114
+		return $is_blocked;
2115
+	}
2116
+
2117
+
2118
+	/**
2119
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2120
+	 *
2121
+	 * @param array $row_results_for_deleting
2122
+	 * @param bool  $allow_blocking
2123
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2124
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2125
+	 *                              dimension array where the key is the fully qualified primary key column and the
2126
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2127
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2128
+	 *                              be a two dimensional array where each element is a group of columns and values that
2129
+	 *                              get deleted. Example: array(
2130
+	 *                              0 => array(
2131
+	 *                              'Term_Relationship.object_id' => 1
2132
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2133
+	 *                              ),
2134
+	 *                              1 => array(
2135
+	 *                              'Term_Relationship.object_id' => 1
2136
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2137
+	 *                              )
2138
+	 *                              )
2139
+	 * @throws EE_Error
2140
+	 * @throws ReflectionException
2141
+	 */
2142
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2143
+	{
2144
+		$ids_to_delete_indexed_by_column = [];
2145
+		if ($this->has_primary_key_field()) {
2146
+			$primary_table                   = $this->_get_main_table();
2147
+			$ids_to_delete_indexed_by_column = [];
2148
+			foreach ($row_results_for_deleting as $item_to_delete) {
2149
+				// before we mark this item for deletion,
2150
+				// make sure there's no related entities blocking its deletion (if we're checking)
2151
+				if (
2152
+					$allow_blocking
2153
+					&& $this->delete_is_blocked_by_related_models(
2154
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2155
+					)
2156
+				) {
2157
+					continue;
2158
+				}
2159
+				// primary table deletes
2160
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2161
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2162
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2163
+				}
2164
+			}
2165
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2166
+			$fields = $this->get_combined_primary_key_fields();
2167
+			foreach ($row_results_for_deleting as $item_to_delete) {
2168
+				$ids_to_delete_indexed_by_column_for_row = [];
2169
+				foreach ($fields as $cpk_field) {
2170
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2171
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2172
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2173
+					}
2174
+				}
2175
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2176
+			}
2177
+		} else {
2178
+			// so there's no primary key and no combined key...
2179
+			// sorry, can't help you
2180
+			throw new EE_Error(
2181
+				sprintf(
2182
+					esc_html__(
2183
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2184
+						"event_espresso"
2185
+					),
2186
+					get_class($this)
2187
+				)
2188
+			);
2189
+		}
2190
+		return $ids_to_delete_indexed_by_column;
2191
+	}
2192
+
2193
+
2194
+	/**
2195
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2196
+	 * the corresponding query_part for the query performing the delete.
2197
+	 *
2198
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2199
+	 * @return string
2200
+	 * @throws EE_Error
2201
+	 */
2202
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2203
+	{
2204
+		$query_part = '';
2205
+		if (empty($ids_to_delete_indexed_by_column)) {
2206
+			return $query_part;
2207
+		} elseif ($this->has_primary_key_field()) {
2208
+			$query = [];
2209
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210
+				// make sure we have unique $ids
2211
+				$ids     = array_unique($ids);
2212
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2213
+			}
2214
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2216
+			$ways_to_identify_a_row = [];
2217
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218
+				$values_for_each_combined_primary_key_for_a_row = [];
2219
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2221
+				}
2222
+				$value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2223
+				$ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2224
+			}
2225
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2226
+		}
2227
+		return $query_part;
2228
+	}
2229
+
2230
+
2231
+	/**
2232
+	 * Gets the model field by the fully qualified name
2233
+	 *
2234
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2235
+	 * @return EE_Model_Field_Base
2236
+	 * @throws EE_Error
2237
+	 */
2238
+	public function get_field_by_column($qualified_column_name)
2239
+	{
2240
+		foreach ($this->field_settings(true) as $field_obj) {
2241
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242
+				return $field_obj;
2243
+			}
2244
+		}
2245
+		throw new EE_Error(
2246
+			sprintf(
2247
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2248
+				$this->get_this_model_name(),
2249
+				$qualified_column_name
2250
+			)
2251
+		);
2252
+	}
2253
+
2254
+
2255
+	/**
2256
+	 * Count all the rows that match criteria the model query params.
2257
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2258
+	 * column
2259
+	 *
2260
+	 * @param array  $query_params
2261
+	 * @param string $field_to_count field on model to count by (not column name)
2262
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2263
+	 *                               that by the setting $distinct to TRUE;
2264
+	 * @return int
2265
+	 * @throws EE_Error
2266
+	 * @throws ReflectionException
2267
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2268
+	 */
2269
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2270
+	{
2271
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
+		if ($field_to_count) {
2273
+			$field_obj       = $this->field_settings_for($field_to_count);
2274
+			$column_to_count = $field_obj->get_qualified_column();
2275
+		} elseif ($this->has_primary_key_field()) {
2276
+			$pk_field_obj    = $this->get_primary_key_field();
2277
+			$column_to_count = $pk_field_obj->get_qualified_column();
2278
+		} else {
2279
+			// there's no primary key
2280
+			// if we're counting distinct items, and there's no primary key,
2281
+			// we need to list out the columns for distinction;
2282
+			// otherwise we can just use star
2283
+			if ($distinct) {
2284
+				$columns_to_use = [];
2285
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2286
+					$columns_to_use[] = $field_obj->get_qualified_column();
2287
+				}
2288
+				$column_to_count = implode(',', $columns_to_use);
2289
+			} else {
2290
+				$column_to_count = '*';
2291
+			}
2292
+		}
2293
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2294
+		$SQL             =
2295
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
+		return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2297
+	}
2298
+
2299
+
2300
+	/**
2301
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2302
+	 *
2303
+	 * @param array  $query_params
2304
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2305
+	 * @return float
2306
+	 * @throws EE_Error
2307
+	 * @throws ReflectionException
2308
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2309
+	 */
2310
+	public function sum($query_params, $field_to_sum = null)
2311
+	{
2312
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2313
+		if ($field_to_sum) {
2314
+			$field_obj = $this->field_settings_for($field_to_sum);
2315
+		} else {
2316
+			$field_obj = $this->get_primary_key_field();
2317
+		}
2318
+		$column_to_count = $field_obj->get_qualified_column();
2319
+		$SQL             = "SELECT SUM(" . $column_to_count . ")"
2320
+						   . $this->_construct_2nd_half_of_select_query($model_query_info);
2321
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2322
+		// $data_type       = $field_obj->get_wpdb_data_type();
2323
+		// if ($data_type === '%d' || $data_type === '%s') {
2324
+		//     return (float)$return_value;
2325
+		// }
2326
+		// must be %f
2327
+		return (float)$return_value;
2328
+	}
2329
+
2330
+
2331
+	/**
2332
+	 * Just calls the specified method on $wpdb with the given arguments
2333
+	 * Consolidates a little extra error handling code
2334
+	 *
2335
+	 * @param string $wpdb_method
2336
+	 * @param array  $arguments_to_provide
2337
+	 * @return mixed
2338
+	 * @throws EE_Error
2339
+	 * @throws ReflectionException
2340
+	 * @global wpdb  $wpdb
2341
+	 */
2342
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2343
+	{
2344
+		// if we're in maintenance mode level 2, DON'T run any queries
2345
+		// because level 2 indicates the database needs updating and
2346
+		// is probably out of sync with the code
2347
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2348
+			throw new EE_Error(
2349
+				esc_html__(
2350
+					'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.',
2351
+					'event_espresso'
2352
+				)
2353
+			);
2354
+		}
2355
+		global $wpdb;
2356
+		if (! method_exists($wpdb, $wpdb_method)) {
2357
+			throw new EE_Error(
2358
+				sprintf(
2359
+					esc_html__(
2360
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2361
+						'event_espresso'
2362
+					),
2363
+					$wpdb_method
2364
+				)
2365
+			);
2366
+		}
2367
+		$old_show_errors_value = $wpdb->show_errors;
2368
+		if (WP_DEBUG) {
2369
+			$wpdb->show_errors(false);
2370
+		}
2371
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2372
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2373
+		if (WP_DEBUG) {
2374
+			$wpdb->show_errors($old_show_errors_value);
2375
+			if (! empty($wpdb->last_error)) {
2376
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2377
+			}
2378
+			if ($result === false) {
2379
+				throw new EE_Error(
2380
+					sprintf(
2381
+						esc_html__(
2382
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2383
+							'event_espresso'
2384
+						),
2385
+						$wpdb_method,
2386
+						var_export($arguments_to_provide, true)
2387
+					)
2388
+				);
2389
+			}
2390
+		} elseif ($result === false) {
2391
+			EE_Error::add_error(
2392
+				sprintf(
2393
+					esc_html__(
2394
+						'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"',
2395
+						'event_espresso'
2396
+					),
2397
+					$wpdb_method,
2398
+					var_export($arguments_to_provide, true),
2399
+					$wpdb->last_error
2400
+				),
2401
+				__FILE__,
2402
+				__FUNCTION__,
2403
+				__LINE__
2404
+			);
2405
+		}
2406
+		return $result;
2407
+	}
2408
+
2409
+
2410
+	/**
2411
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2412
+	 * and if there's an error tries to verify the DB is correct. Uses
2413
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2414
+	 * we should try to fix the EE core db, the addons, or just give up
2415
+	 *
2416
+	 * @param string $wpdb_method
2417
+	 * @param array  $arguments_to_provide
2418
+	 * @return mixed
2419
+	 * @throws EE_Error
2420
+	 * @throws ReflectionException
2421
+	 */
2422
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2423
+	{
2424
+		global $wpdb;
2425
+		$wpdb->last_error = null;
2426
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2427
+		// was there an error running the query? but we don't care on new activations
2428
+		// (we're going to setup the DB anyway on new activations)
2429
+		if (
2430
+			($result === false || ! empty($wpdb->last_error))
2431
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2432
+		) {
2433
+			switch (EEM_Base::$_db_verification_level) {
2434
+				case EEM_Base::db_verified_none:
2435
+					// let's double-check core's DB
2436
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2437
+					break;
2438
+				case EEM_Base::db_verified_core:
2439
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2440
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2441
+					break;
2442
+				case EEM_Base::db_verified_addons:
2443
+					// ummmm... you in trouble
2444
+					return $result;
2445
+			}
2446
+			if (! empty($error_message)) {
2447
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2448
+				trigger_error($error_message);
2449
+			}
2450
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2451
+		}
2452
+		return $result;
2453
+	}
2454
+
2455
+
2456
+	/**
2457
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2458
+	 * EEM_Base::$_db_verification_level
2459
+	 *
2460
+	 * @param string $wpdb_method
2461
+	 * @param array  $arguments_to_provide
2462
+	 * @return string
2463
+	 * @throws EE_Error
2464
+	 * @throws ReflectionException
2465
+	 */
2466
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2467
+	{
2468
+		global $wpdb;
2469
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2470
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2471
+		$error_message                    = sprintf(
2472
+			esc_html__(
2473
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2474
+				'event_espresso'
2475
+			),
2476
+			$wpdb->last_error,
2477
+			$wpdb_method,
2478
+			wp_json_encode($arguments_to_provide)
2479
+		);
2480
+		EE_System::instance()->initialize_db_if_no_migrations_required();
2481
+		return $error_message;
2482
+	}
2483
+
2484
+
2485
+	/**
2486
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2487
+	 * EEM_Base::$_db_verification_level
2488
+	 *
2489
+	 * @param $wpdb_method
2490
+	 * @param $arguments_to_provide
2491
+	 * @return string
2492
+	 * @throws EE_Error
2493
+	 * @throws ReflectionException
2494
+	 */
2495
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2496
+	{
2497
+		global $wpdb;
2498
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2499
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2500
+		$error_message                    = sprintf(
2501
+			esc_html__(
2502
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2503
+				'event_espresso'
2504
+			),
2505
+			$wpdb->last_error,
2506
+			$wpdb_method,
2507
+			wp_json_encode($arguments_to_provide)
2508
+		);
2509
+		EE_System::instance()->initialize_addons();
2510
+		return $error_message;
2511
+	}
2512
+
2513
+
2514
+	/**
2515
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2516
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2517
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2518
+	 * ..."
2519
+	 *
2520
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2521
+	 * @return string
2522
+	 */
2523
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2524
+	{
2525
+		return " FROM " . $model_query_info->get_full_join_sql() .
2526
+			   $model_query_info->get_where_sql() .
2527
+			   $model_query_info->get_group_by_sql() .
2528
+			   $model_query_info->get_having_sql() .
2529
+			   $model_query_info->get_order_by_sql() .
2530
+			   $model_query_info->get_limit_sql();
2531
+	}
2532
+
2533
+
2534
+	/**
2535
+	 * Set to easily debug the next X queries ran from this model.
2536
+	 *
2537
+	 * @param int $count
2538
+	 */
2539
+	public function show_next_x_db_queries($count = 1)
2540
+	{
2541
+		$this->_show_next_x_db_queries = $count;
2542
+	}
2543
+
2544
+
2545
+	/**
2546
+	 * @param $sql_query
2547
+	 */
2548
+	public function show_db_query_if_previously_requested($sql_query)
2549
+	{
2550
+		if ($this->_show_next_x_db_queries > 0) {
2551
+			echo $sql_query;
2552
+			$this->_show_next_x_db_queries--;
2553
+		}
2554
+	}
2555
+
2556
+
2557
+	/**
2558
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2559
+	 * There are the 3 cases:
2560
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2561
+	 * $otherModelObject has no ID, it is first saved.
2562
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2563
+	 * has no ID, it is first saved.
2564
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2565
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2566
+	 * join table
2567
+	 *
2568
+	 * @param EE_Base_Class                     /int $thisModelObject
2569
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2570
+	 * @param string $relationName                     , key in EEM_Base::_relations
2571
+	 *                                                 an attendee to a group, you also want to specify which role they
2572
+	 *                                                 will have in that group. So you would use this parameter to
2573
+	 *                                                 specify array('role-column-name'=>'role-id')
2574
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2575
+	 *                                                 to for relation to methods that allow you to further specify
2576
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2577
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2578
+	 *                                                 because these will be inserted in any new rows created as well.
2579
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2580
+	 * @throws EE_Error
2581
+	 */
2582
+	public function add_relationship_to(
2583
+		$id_or_obj,
2584
+		$other_model_id_or_obj,
2585
+		$relationName,
2586
+		$extra_join_model_fields_n_values = []
2587
+	) {
2588
+		$relation_obj = $this->related_settings_for($relationName);
2589
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2590
+	}
2591
+
2592
+
2593
+	/**
2594
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2595
+	 * There are the 3 cases:
2596
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2597
+	 * error
2598
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2599
+	 * an error
2600
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2601
+	 *
2602
+	 * @param EE_Base_Class /int $id_or_obj
2603
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2604
+	 * @param string $relationName key in EEM_Base::_relations
2605
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2606
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2607
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2608
+	 *                             because these will be inserted in any new rows created as well.
2609
+	 * @return boolean of success
2610
+	 * @throws EE_Error
2611
+	 */
2612
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2613
+	{
2614
+		$relation_obj = $this->related_settings_for($relationName);
2615
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2616
+	}
2617
+
2618
+
2619
+	/**
2620
+	 * @param mixed  $id_or_obj
2621
+	 * @param string $relationName
2622
+	 * @param array  $where_query_params
2623
+	 * @param EE_Base_Class[] objects to which relations were removed
2624
+	 * @return EE_Base_Class[]
2625
+	 * @throws EE_Error
2626
+	 */
2627
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2628
+	{
2629
+		$relation_obj = $this->related_settings_for($relationName);
2630
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2631
+	}
2632
+
2633
+
2634
+	/**
2635
+	 * Gets all the related items of the specified $model_name, using $query_params.
2636
+	 * Note: by default, we remove the "default query params"
2637
+	 * because we want to get even deleted items etc.
2638
+	 *
2639
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2640
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2641
+	 * @param array  $query_params see github link below for more info
2642
+	 * @return EE_Base_Class[]
2643
+	 * @throws EE_Error
2644
+	 * @throws ReflectionException
2645
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2646
+	 */
2647
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2648
+	{
2649
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2650
+		$relation_settings = $this->related_settings_for($model_name);
2651
+		return $relation_settings->get_all_related($model_obj, $query_params);
2652
+	}
2653
+
2654
+
2655
+	/**
2656
+	 * Deletes all the model objects across the relation indicated by $model_name
2657
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2658
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2659
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2660
+	 *
2661
+	 * @param EE_Base_Class|int|string $id_or_obj
2662
+	 * @param string                   $model_name
2663
+	 * @param array                    $query_params
2664
+	 * @return int how many deleted
2665
+	 * @throws EE_Error
2666
+	 * @throws ReflectionException
2667
+	 */
2668
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2669
+	{
2670
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2671
+		$relation_settings = $this->related_settings_for($model_name);
2672
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2673
+	}
2674
+
2675
+
2676
+	/**
2677
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2678
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2679
+	 * the model objects can't be hard deleted because of blocking related model objects,
2680
+	 * just does a soft-delete on them instead.
2681
+	 *
2682
+	 * @param EE_Base_Class|int|string $id_or_obj
2683
+	 * @param string                   $model_name
2684
+	 * @param array                    $query_params
2685
+	 * @return int how many deleted
2686
+	 * @throws EE_Error
2687
+	 * @throws ReflectionException
2688
+	 */
2689
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2690
+	{
2691
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2692
+		$relation_settings = $this->related_settings_for($model_name);
2693
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2694
+	}
2695
+
2696
+
2697
+	/**
2698
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2699
+	 * unless otherwise specified in the $query_params
2700
+	 *
2701
+	 * @param int             /EE_Base_Class $id_or_obj
2702
+	 * @param string $model_name     like 'Event', or 'Registration'
2703
+	 * @param array  $query_params
2704
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2705
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2706
+	 *                               that by the setting $distinct to TRUE;
2707
+	 * @return int
2708
+	 * @throws EE_Error
2709
+	 * @throws ReflectionException
2710
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2711
+	 */
2712
+	public function count_related(
2713
+		$id_or_obj,
2714
+		$model_name,
2715
+		$query_params = [],
2716
+		$field_to_count = null,
2717
+		$distinct = false
2718
+	) {
2719
+		$related_model = $this->get_related_model_obj($model_name);
2720
+		// we're just going to use the query params on the related model's normal get_all query,
2721
+		// except add a condition to say to match the current mod
2722
+		if (! isset($query_params['default_where_conditions'])) {
2723
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2724
+		}
2725
+		$this_model_name                                                 = $this->get_this_model_name();
2726
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2727
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2728
+		return $related_model->count($query_params, $field_to_count, $distinct);
2729
+	}
2730
+
2731
+
2732
+	/**
2733
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2734
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2735
+	 *
2736
+	 * @param int           /EE_Base_Class $id_or_obj
2737
+	 * @param string $model_name   like 'Event', or 'Registration'
2738
+	 * @param array  $query_params
2739
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2740
+	 * @return float
2741
+	 * @throws EE_Error
2742
+	 * @throws ReflectionException
2743
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2744
+	 */
2745
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2746
+	{
2747
+		$related_model = $this->get_related_model_obj($model_name);
2748
+		if (! is_array($query_params)) {
2749
+			EE_Error::doing_it_wrong(
2750
+				'EEM_Base::sum_related',
2751
+				sprintf(
2752
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2753
+					gettype($query_params)
2754
+				),
2755
+				'4.6.0'
2756
+			);
2757
+			$query_params = [];
2758
+		}
2759
+		// we're just going to use the query params on the related model's normal get_all query,
2760
+		// except add a condition to say to match the current mod
2761
+		if (! isset($query_params['default_where_conditions'])) {
2762
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2763
+		}
2764
+		$this_model_name                                                 = $this->get_this_model_name();
2765
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2766
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2767
+		return $related_model->sum($query_params, $field_to_sum);
2768
+	}
2769
+
2770
+
2771
+	/**
2772
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2773
+	 * $modelObject
2774
+	 *
2775
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2776
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2777
+	 * @param array               $query_params     see github link below for more info
2778
+	 * @return EE_Base_Class
2779
+	 * @throws EE_Error
2780
+	 * @throws ReflectionException
2781
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2782
+	 */
2783
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2784
+	{
2785
+		$query_params['limit'] = 1;
2786
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2787
+		if ($results) {
2788
+			return array_shift($results);
2789
+		}
2790
+		return null;
2791
+	}
2792
+
2793
+
2794
+	/**
2795
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2796
+	 *
2797
+	 * @return string
2798
+	 */
2799
+	public function get_this_model_name()
2800
+	{
2801
+		return str_replace("EEM_", "", get_class($this));
2802
+	}
2803
+
2804
+
2805
+	/**
2806
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2807
+	 *
2808
+	 * @return EE_Any_Foreign_Model_Name_Field
2809
+	 * @throws EE_Error
2810
+	 */
2811
+	public function get_field_containing_related_model_name()
2812
+	{
2813
+		foreach ($this->field_settings(true) as $field) {
2814
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2815
+				$field_with_model_name = $field;
2816
+			}
2817
+		}
2818
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2819
+			throw new EE_Error(
2820
+				sprintf(
2821
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2822
+					$this->get_this_model_name()
2823
+				)
2824
+			);
2825
+		}
2826
+		return $field_with_model_name;
2827
+	}
2828
+
2829
+
2830
+	/**
2831
+	 * Inserts a new entry into the database, for each table.
2832
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2833
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2834
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2835
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2836
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2837
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2838
+	 *
2839
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2840
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2841
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2842
+	 *                              of EEM_Base)
2843
+	 * @return int|string new primary key on main table that got inserted
2844
+	 * @throws EE_Error
2845
+	 * @throws ReflectionException
2846
+	 */
2847
+	public function insert($field_n_values)
2848
+	{
2849
+		/**
2850
+		 * Filters the fields and their values before inserting an item using the models
2851
+		 *
2852
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2853
+		 * @param EEM_Base $model           the model used
2854
+		 */
2855
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2856
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2857
+			$main_table = $this->_get_main_table();
2858
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2859
+			if ($new_id !== false) {
2860
+				foreach ($this->_get_other_tables() as $other_table) {
2861
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2862
+				}
2863
+			}
2864
+			/**
2865
+			 * Done just after attempting to insert a new model object
2866
+			 *
2867
+			 * @param EEM_Base $model           used
2868
+			 * @param array    $fields_n_values fields and their values
2869
+			 * @param int|string the              ID of the newly-inserted model object
2870
+			 */
2871
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2872
+			return $new_id;
2873
+		}
2874
+		return false;
2875
+	}
2876
+
2877
+
2878
+	/**
2879
+	 * Checks that the result would satisfy the unique indexes on this model
2880
+	 *
2881
+	 * @param array  $field_n_values
2882
+	 * @param string $action
2883
+	 * @return boolean
2884
+	 * @throws EE_Error
2885
+	 * @throws ReflectionException
2886
+	 */
2887
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2888
+	{
2889
+		foreach ($this->unique_indexes() as $index_name => $index) {
2890
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2891
+			if ($this->exists([$uniqueness_where_params])) {
2892
+				EE_Error::add_error(
2893
+					sprintf(
2894
+						esc_html__(
2895
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2896
+							"event_espresso"
2897
+						),
2898
+						$action,
2899
+						$this->_get_class_name(),
2900
+						$index_name,
2901
+						implode(",", $index->field_names()),
2902
+						http_build_query($uniqueness_where_params)
2903
+					),
2904
+					__FILE__,
2905
+					__FUNCTION__,
2906
+					__LINE__
2907
+				);
2908
+				return false;
2909
+			}
2910
+		}
2911
+		return true;
2912
+	}
2913
+
2914
+
2915
+	/**
2916
+	 * Checks the database for an item that conflicts (ie, if this item were
2917
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2918
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2919
+	 * can be either an EE_Base_Class or an array of fields n values
2920
+	 *
2921
+	 * @param EE_Base_Class|array $obj_or_fields_array
2922
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2923
+	 *                                                 when looking for conflicts
2924
+	 *                                                 (ie, if false, we ignore the model object's primary key
2925
+	 *                                                 when finding "conflicts". If true, it's also considered).
2926
+	 *                                                 Only works for INT primary key,
2927
+	 *                                                 STRING primary keys cannot be ignored
2928
+	 * @return EE_Base_Class|array
2929
+	 * @throws EE_Error
2930
+	 * @throws ReflectionException
2931
+	 */
2932
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2933
+	{
2934
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2935
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2936
+		} elseif (is_array($obj_or_fields_array)) {
2937
+			$fields_n_values = $obj_or_fields_array;
2938
+		} else {
2939
+			throw new EE_Error(
2940
+				sprintf(
2941
+					esc_html__(
2942
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2943
+						"event_espresso"
2944
+					),
2945
+					get_class($this),
2946
+					$obj_or_fields_array
2947
+				)
2948
+			);
2949
+		}
2950
+		$query_params = [];
2951
+		if (
2952
+			$this->has_primary_key_field()
2953
+			&& ($include_primary_key
2954
+				|| $this->get_primary_key_field()
2955
+				   instanceof
2956
+				   EE_Primary_Key_String_Field)
2957
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2958
+		) {
2959
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2960
+		}
2961
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2962
+			$uniqueness_where_params                              =
2963
+				array_intersect_key($fields_n_values, $unique_index->fields());
2964
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2965
+		}
2966
+		// if there is nothing to base this search on, then we shouldn't find anything
2967
+		if (empty($query_params)) {
2968
+			return [];
2969
+		}
2970
+		return $this->get_one($query_params);
2971
+	}
2972
+
2973
+
2974
+	/**
2975
+	 * Like count, but is optimized and returns a boolean instead of an int
2976
+	 *
2977
+	 * @param array $query_params
2978
+	 * @return boolean
2979
+	 * @throws EE_Error
2980
+	 * @throws ReflectionException
2981
+	 */
2982
+	public function exists($query_params)
2983
+	{
2984
+		$query_params['limit'] = 1;
2985
+		return $this->count($query_params) > 0;
2986
+	}
2987
+
2988
+
2989
+	/**
2990
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2991
+	 *
2992
+	 * @param int|string $id
2993
+	 * @return boolean
2994
+	 * @throws EE_Error
2995
+	 * @throws ReflectionException
2996
+	 */
2997
+	public function exists_by_ID($id)
2998
+	{
2999
+		return $this->exists(
3000
+			[
3001
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3002
+				[
3003
+					$this->primary_key_name() => $id,
3004
+				],
3005
+			]
3006
+		);
3007
+	}
3008
+
3009
+
3010
+	/**
3011
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3012
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3013
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3014
+	 * on the main table)
3015
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3016
+	 * cases where we want to call it directly rather than via insert().
3017
+	 *
3018
+	 * @access   protected
3019
+	 * @param EE_Table_Base $table
3020
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3021
+	 *                                       float
3022
+	 * @param int           $new_id          for now we assume only int keys
3023
+	 * @return int ID of new row inserted, or FALSE on failure
3024
+	 * @throws EE_Error
3025
+	 * @throws ReflectionException
3026
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3027
+	 */
3028
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3029
+	{
3030
+		global $wpdb;
3031
+		$insertion_col_n_values = [];
3032
+		$format_for_insertion   = [];
3033
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3034
+		foreach ($fields_on_table as $field_obj) {
3035
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3036
+			if ($field_obj->is_auto_increment()) {
3037
+				continue;
3038
+			}
3039
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3040
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3041
+			if ($prepared_value !== null) {
3042
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3043
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3044
+			}
3045
+		}
3046
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3047
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3048
+			// so add the fk to the main table as a column
3049
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3050
+			$format_for_insertion[]                              =
3051
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3052
+		}
3053
+		// insert the new entry
3054
+		$result = $this->_do_wpdb_query(
3055
+			'insert',
3056
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3057
+		);
3058
+		if ($result === false) {
3059
+			return false;
3060
+		}
3061
+		// ok, now what do we return for the ID of the newly-inserted thing?
3062
+		if ($this->has_primary_key_field()) {
3063
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3064
+				return $wpdb->insert_id;
3065
+			}
3066
+			// it's not an auto-increment primary key, so
3067
+			// it must have been supplied
3068
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3069
+		}
3070
+		// we can't return a  primary key because there is none. instead return
3071
+		// a unique string indicating this model
3072
+		return $this->get_index_primary_key_string($fields_n_values);
3073
+	}
3074
+
3075
+
3076
+	/**
3077
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3078
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3079
+	 * and there is no default, we pass it along. WPDB will take care of it)
3080
+	 *
3081
+	 * @param EE_Model_Field_Base $field_obj
3082
+	 * @param array               $fields_n_values
3083
+	 * @return mixed string|int|float depending on what the table column will be expecting
3084
+	 * @throws EE_Error
3085
+	 */
3086
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3087
+	{
3088
+		// if this field doesn't allow nullable, don't allow it
3089
+		if (
3090
+			! $field_obj->is_nullable()
3091
+			&& (
3092
+				! isset($fields_n_values[ $field_obj->get_name() ])
3093
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3094
+			)
3095
+		) {
3096
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3097
+		}
3098
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3099
+			? $fields_n_values[ $field_obj->get_name() ]
3100
+			: null;
3101
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3102
+	}
3103
+
3104
+
3105
+	/**
3106
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3107
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3108
+	 * the field's prepare_for_set() method.
3109
+	 *
3110
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3111
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3112
+	 *                                   top of file)
3113
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3114
+	 *                                   $value is a custom selection
3115
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3116
+	 */
3117
+	private function _prepare_value_for_use_in_db($value, $field)
3118
+	{
3119
+		if ($field && $field instanceof EE_Model_Field_Base) {
3120
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3121
+			switch ($this->_values_already_prepared_by_model_object) {
3122
+				/** @noinspection PhpMissingBreakStatementInspection */
3123
+				case self::not_prepared_by_model_object:
3124
+					$value = $field->prepare_for_set($value);
3125
+				// purposefully left out "return"
3126
+				case self::prepared_by_model_object:
3127
+					/** @noinspection SuspiciousAssignmentsInspection */
3128
+					$value = $field->prepare_for_use_in_db($value);
3129
+				case self::prepared_for_use_in_db:
3130
+					// leave the value alone
3131
+			}
3132
+			return $value;
3133
+			// phpcs:enable
3134
+		}
3135
+		return $value;
3136
+	}
3137
+
3138
+
3139
+	/**
3140
+	 * Returns the main table on this model
3141
+	 *
3142
+	 * @return EE_Primary_Table
3143
+	 * @throws EE_Error
3144
+	 */
3145
+	protected function _get_main_table()
3146
+	{
3147
+		foreach ($this->_tables as $table) {
3148
+			if ($table instanceof EE_Primary_Table) {
3149
+				return $table;
3150
+			}
3151
+		}
3152
+		throw new EE_Error(
3153
+			sprintf(
3154
+				esc_html__(
3155
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3156
+					'event_espresso'
3157
+				),
3158
+				get_class($this)
3159
+			)
3160
+		);
3161
+	}
3162
+
3163
+
3164
+	/**
3165
+	 * table
3166
+	 * returns EE_Primary_Table table name
3167
+	 *
3168
+	 * @return string
3169
+	 * @throws EE_Error
3170
+	 */
3171
+	public function table()
3172
+	{
3173
+		return $this->_get_main_table()->get_table_name();
3174
+	}
3175
+
3176
+
3177
+	/**
3178
+	 * table
3179
+	 * returns first EE_Secondary_Table table name
3180
+	 *
3181
+	 * @return string
3182
+	 */
3183
+	public function second_table()
3184
+	{
3185
+		// grab second table from tables array
3186
+		$second_table = end($this->_tables);
3187
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * get_table_obj_by_alias
3193
+	 * returns table name given it's alias
3194
+	 *
3195
+	 * @param string $table_alias
3196
+	 * @return EE_Primary_Table | EE_Secondary_Table
3197
+	 */
3198
+	public function get_table_obj_by_alias($table_alias = '')
3199
+	{
3200
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3201
+	}
3202
+
3203
+
3204
+	/**
3205
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3206
+	 *
3207
+	 * @return EE_Secondary_Table[]
3208
+	 */
3209
+	protected function _get_other_tables()
3210
+	{
3211
+		$other_tables = [];
3212
+		foreach ($this->_tables as $table_alias => $table) {
3213
+			if ($table instanceof EE_Secondary_Table) {
3214
+				$other_tables[ $table_alias ] = $table;
3215
+			}
3216
+		}
3217
+		return $other_tables;
3218
+	}
3219
+
3220
+
3221
+	/**
3222
+	 * Finds all the fields that correspond to the given table
3223
+	 *
3224
+	 * @param string $table_alias , array key in EEM_Base::_tables
3225
+	 * @return EE_Model_Field_Base[]
3226
+	 */
3227
+	public function _get_fields_for_table($table_alias)
3228
+	{
3229
+		return $this->_fields[ $table_alias ];
3230
+	}
3231
+
3232
+
3233
+	/**
3234
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3235
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3236
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3237
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3238
+	 * related Registration, Transaction, and Payment models.
3239
+	 *
3240
+	 * @param array $query_params see github link below for more info
3241
+	 * @return EE_Model_Query_Info_Carrier
3242
+	 * @throws EE_Error
3243
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3244
+	 */
3245
+	public function _extract_related_models_from_query($query_params)
3246
+	{
3247
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3248
+		if (array_key_exists(0, $query_params)) {
3249
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3250
+		}
3251
+		if (array_key_exists('group_by', $query_params)) {
3252
+			if (is_array($query_params['group_by'])) {
3253
+				$this->_extract_related_models_from_sub_params_array_values(
3254
+					$query_params['group_by'],
3255
+					$query_info_carrier,
3256
+					'group_by'
3257
+				);
3258
+			} elseif (! empty($query_params['group_by'])) {
3259
+				$this->_extract_related_model_info_from_query_param(
3260
+					$query_params['group_by'],
3261
+					$query_info_carrier,
3262
+					'group_by'
3263
+				);
3264
+			}
3265
+		}
3266
+		if (array_key_exists('having', $query_params)) {
3267
+			$this->_extract_related_models_from_sub_params_array_keys(
3268
+				$query_params[0],
3269
+				$query_info_carrier,
3270
+				'having'
3271
+			);
3272
+		}
3273
+		if (array_key_exists('order_by', $query_params)) {
3274
+			if (is_array($query_params['order_by'])) {
3275
+				$this->_extract_related_models_from_sub_params_array_keys(
3276
+					$query_params['order_by'],
3277
+					$query_info_carrier,
3278
+					'order_by'
3279
+				);
3280
+			} elseif (! empty($query_params['order_by'])) {
3281
+				$this->_extract_related_model_info_from_query_param(
3282
+					$query_params['order_by'],
3283
+					$query_info_carrier,
3284
+					'order_by'
3285
+				);
3286
+			}
3287
+		}
3288
+		if (array_key_exists('force_join', $query_params)) {
3289
+			$this->_extract_related_models_from_sub_params_array_values(
3290
+				$query_params['force_join'],
3291
+				$query_info_carrier,
3292
+				'force_join'
3293
+			);
3294
+		}
3295
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3296
+		return $query_info_carrier;
3297
+	}
3298
+
3299
+
3300
+	/**
3301
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3302
+	 *
3303
+	 * @param array                       $sub_query_params
3304
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3306
+	 * @throws EE_Error
3307
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3308
+	 */
3309
+	private function _extract_related_models_from_sub_params_array_keys(
3310
+		$sub_query_params,
3311
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
+		$query_param_type
3313
+	) {
3314
+		if (! empty($sub_query_params)) {
3315
+			$sub_query_params = (array)$sub_query_params;
3316
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3317
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3318
+				$this->_extract_related_model_info_from_query_param(
3319
+					$param,
3320
+					$model_query_info_carrier,
3321
+					$query_param_type
3322
+				);
3323
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3324
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3325
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3326
+				// of array('Registration.TXN_ID'=>23)
3327
+				$query_param_sans_stars =
3328
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3329
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3330
+					if (! is_array($possibly_array_of_params)) {
3331
+						throw new EE_Error(
3332
+							sprintf(
3333
+								esc_html__(
3334
+									"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'))",
3335
+									"event_espresso"
3336
+								),
3337
+								$param,
3338
+								$possibly_array_of_params
3339
+							)
3340
+						);
3341
+					}
3342
+					$this->_extract_related_models_from_sub_params_array_keys(
3343
+						$possibly_array_of_params,
3344
+						$model_query_info_carrier,
3345
+						$query_param_type
3346
+					);
3347
+				} elseif (
3348
+					$query_param_type === 0 // ie WHERE
3349
+					&& is_array($possibly_array_of_params)
3350
+					&& isset($possibly_array_of_params[2])
3351
+					&& $possibly_array_of_params[2] == true
3352
+				) {
3353
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3354
+					// indicating that $possible_array_of_params[1] is actually a field name,
3355
+					// from which we should extract query parameters!
3356
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3357
+						throw new EE_Error(
3358
+							sprintf(
3359
+								esc_html__(
3360
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3361
+									"event_espresso"
3362
+								),
3363
+								$query_param_type,
3364
+								implode(",", $possibly_array_of_params)
3365
+							)
3366
+						);
3367
+					}
3368
+					$this->_extract_related_model_info_from_query_param(
3369
+						$possibly_array_of_params[1],
3370
+						$model_query_info_carrier,
3371
+						$query_param_type
3372
+					);
3373
+				}
3374
+			}
3375
+		}
3376
+	}
3377
+
3378
+
3379
+	/**
3380
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3381
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3382
+	 *
3383
+	 * @param array                       $sub_query_params
3384
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3385
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3386
+	 * @throws EE_Error
3387
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3388
+	 */
3389
+	private function _extract_related_models_from_sub_params_array_values(
3390
+		$sub_query_params,
3391
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392
+		$query_param_type
3393
+	) {
3394
+		if (! empty($sub_query_params)) {
3395
+			if (! is_array($sub_query_params)) {
3396
+				throw new EE_Error(
3397
+					sprintf(
3398
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
+						$sub_query_params
3400
+					)
3401
+				);
3402
+			}
3403
+			foreach ($sub_query_params as $param) {
3404
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3405
+				$this->_extract_related_model_info_from_query_param(
3406
+					$param,
3407
+					$model_query_info_carrier,
3408
+					$query_param_type
3409
+				);
3410
+			}
3411
+		}
3412
+	}
3413
+
3414
+
3415
+	/**
3416
+	 * Extract all the query parts from  model query params
3417
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
+	 * but use them in a different order. Eg, we need to know what models we are querying
3420
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
+	 * other models before we can finalize the where clause SQL.
3422
+	 *
3423
+	 * @param array $query_params see github link below for more info
3424
+	 * @return EE_Model_Query_Info_Carrier
3425
+	 * @throws EE_Error
3426
+	 * @throws ModelConfigurationException
3427
+	 * @throws ReflectionException
3428
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3429
+	 */
3430
+	public function _create_model_query_info_carrier($query_params)
3431
+	{
3432
+		if (! is_array($query_params)) {
3433
+			EE_Error::doing_it_wrong(
3434
+				'EEM_Base::_create_model_query_info_carrier',
3435
+				sprintf(
3436
+					esc_html__(
3437
+						'$query_params should be an array, you passed a variable of type %s',
3438
+						'event_espresso'
3439
+					),
3440
+					gettype($query_params)
3441
+				),
3442
+				'4.6.0'
3443
+			);
3444
+			$query_params = [];
3445
+		}
3446
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3447
+		// first check if we should alter the query to account for caps or not
3448
+		// because the caps might require us to do extra joins
3449
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3450
+			$query_params[0] = array_replace_recursive(
3451
+				$query_params[0],
3452
+				$this->caps_where_conditions(
3453
+					$query_params['caps']
3454
+				)
3455
+			);
3456
+		}
3457
+
3458
+		// check if we should alter the query to remove data related to protected
3459
+		// custom post types
3460
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3461
+			$where_param_key_for_password = $this->modelChainAndPassword();
3462
+			// only include if related to a cpt where no password has been set
3463
+			$query_params[0]['OR*nopassword'] = [
3464
+				$where_param_key_for_password       => '',
3465
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3466
+			];
3467
+		}
3468
+		$query_object = $this->_extract_related_models_from_query($query_params);
3469
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
+		foreach ($query_params[0] as $key => $value) {
3471
+			if (is_int($key)) {
3472
+				throw new EE_Error(
3473
+					sprintf(
3474
+						esc_html__(
3475
+							"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.",
3476
+							"event_espresso"
3477
+						),
3478
+						$key,
3479
+						var_export($value, true),
3480
+						var_export($query_params, true),
3481
+						get_class($this)
3482
+					)
3483
+				);
3484
+			}
3485
+		}
3486
+		if (
3487
+			array_key_exists('default_where_conditions', $query_params)
3488
+			&& ! empty($query_params['default_where_conditions'])
3489
+		) {
3490
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3491
+		} else {
3492
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3493
+		}
3494
+		$query_params[0] = array_merge(
3495
+			$this->_get_default_where_conditions_for_models_in_query(
3496
+				$query_object,
3497
+				$use_default_where_conditions,
3498
+				$query_params[0]
3499
+			),
3500
+			$query_params[0]
3501
+		);
3502
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3503
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3504
+		// So we need to setup a subquery and use that for the main join.
3505
+		// Note for now this only works on the primary table for the model.
3506
+		// So for instance, you could set the limit array like this:
3507
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3508
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3509
+			$query_object->set_main_model_join_sql(
3510
+				$this->_construct_limit_join_select(
3511
+					$query_params['on_join_limit'][0],
3512
+					$query_params['on_join_limit'][1]
3513
+				)
3514
+			);
3515
+		}
3516
+		// set limit
3517
+		if (array_key_exists('limit', $query_params)) {
3518
+			if (is_array($query_params['limit'])) {
3519
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3520
+					$e = sprintf(
3521
+						esc_html__(
3522
+							"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)",
3523
+							"event_espresso"
3524
+						),
3525
+						http_build_query($query_params['limit'])
3526
+					);
3527
+					throw new EE_Error($e . "|" . $e);
3528
+				}
3529
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3530
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3531
+			} elseif (! empty($query_params['limit'])) {
3532
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3533
+			}
3534
+		}
3535
+		// set order by
3536
+		if (array_key_exists('order_by', $query_params)) {
3537
+			if (is_array($query_params['order_by'])) {
3538
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3539
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3540
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3541
+				if (array_key_exists('order', $query_params)) {
3542
+					throw new EE_Error(
3543
+						sprintf(
3544
+							esc_html__(
3545
+								"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 ",
3546
+								"event_espresso"
3547
+							),
3548
+							get_class($this),
3549
+							implode(", ", array_keys($query_params['order_by'])),
3550
+							implode(", ", $query_params['order_by']),
3551
+							$query_params['order']
3552
+						)
3553
+					);
3554
+				}
3555
+				$this->_extract_related_models_from_sub_params_array_keys(
3556
+					$query_params['order_by'],
3557
+					$query_object,
3558
+					'order_by'
3559
+				);
3560
+				// assume it's an array of fields to order by
3561
+				$order_array = [];
3562
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3563
+					$order         = $this->_extract_order($order);
3564
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3565
+				}
3566
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3567
+			} elseif (! empty($query_params['order_by'])) {
3568
+				$this->_extract_related_model_info_from_query_param(
3569
+					$query_params['order_by'],
3570
+					$query_object,
3571
+					'order',
3572
+					$query_params['order_by']
3573
+				);
3574
+				$order = isset($query_params['order'])
3575
+					? $this->_extract_order($query_params['order'])
3576
+					: 'DESC';
3577
+				$query_object->set_order_by_sql(
3578
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3579
+				);
3580
+			}
3581
+		}
3582
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3583
+		if (
3584
+			! array_key_exists('order_by', $query_params)
3585
+			&& array_key_exists('order', $query_params)
3586
+			&& ! empty($query_params['order'])
3587
+		) {
3588
+			$pk_field = $this->get_primary_key_field();
3589
+			$order    = $this->_extract_order($query_params['order']);
3590
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3591
+		}
3592
+		// set group by
3593
+		if (array_key_exists('group_by', $query_params)) {
3594
+			if (is_array($query_params['group_by'])) {
3595
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3596
+				$group_by_array = [];
3597
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3598
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3599
+				}
3600
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3601
+			} elseif (! empty($query_params['group_by'])) {
3602
+				$query_object->set_group_by_sql(
3603
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3604
+				);
3605
+			}
3606
+		}
3607
+		// set having
3608
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3609
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3610
+		}
3611
+		// now, just verify they didn't pass anything wack
3612
+		foreach ($query_params as $query_key => $query_value) {
3613
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3614
+				throw new EE_Error(
3615
+					sprintf(
3616
+						esc_html__(
3617
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3618
+							'event_espresso'
3619
+						),
3620
+						$query_key,
3621
+						get_class($this),
3622
+						//                      print_r( $this->_allowed_query_params, TRUE )
3623
+						implode(',', $this->_allowed_query_params)
3624
+					)
3625
+				);
3626
+			}
3627
+		}
3628
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3629
+		if (empty($main_model_join_sql)) {
3630
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3631
+		}
3632
+		return $query_object;
3633
+	}
3634
+
3635
+
3636
+	/**
3637
+	 * Gets the where conditions that should be imposed on the query based on the
3638
+	 * context (eg reading frontend, backend, edit or delete).
3639
+	 *
3640
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3641
+	 * @return array
3642
+	 * @throws EE_Error
3643
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3644
+	 */
3645
+	public function caps_where_conditions($context = self::caps_read)
3646
+	{
3647
+		EEM_Base::verify_is_valid_cap_context($context);
3648
+		$cap_where_conditions = [];
3649
+		$cap_restrictions     = $this->caps_missing($context);
3650
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3651
+			$cap_where_conditions = array_replace_recursive(
3652
+				$cap_where_conditions,
3653
+				$restriction_if_no_cap->get_default_where_conditions()
3654
+			);
3655
+		}
3656
+		return apply_filters(
3657
+			'FHEE__EEM_Base__caps_where_conditions__return',
3658
+			$cap_where_conditions,
3659
+			$this,
3660
+			$context,
3661
+			$cap_restrictions
3662
+		);
3663
+	}
3664
+
3665
+
3666
+	/**
3667
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3668
+	 * otherwise throws an exception
3669
+	 *
3670
+	 * @param string $should_be_order_string
3671
+	 * @return string either ASC, asc, DESC or desc
3672
+	 * @throws EE_Error
3673
+	 */
3674
+	private function _extract_order($should_be_order_string)
3675
+	{
3676
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3677
+			return $should_be_order_string;
3678
+		}
3679
+		throw new EE_Error(
3680
+			sprintf(
3681
+				esc_html__(
3682
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3683
+					"event_espresso"
3684
+				),
3685
+				get_class($this),
3686
+				$should_be_order_string
3687
+			)
3688
+		);
3689
+	}
3690
+
3691
+
3692
+	/**
3693
+	 * Looks at all the models which are included in this query, and asks each
3694
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3695
+	 * so they can be merged
3696
+	 *
3697
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3698
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3699
+	 *                                                                  'none' means NO default where conditions will
3700
+	 *                                                                  be used AT ALL during this query.
3701
+	 *                                                                  'other_models_only' means default where
3702
+	 *                                                                  conditions from other models will be used, but
3703
+	 *                                                                  not for this primary model. 'all', the default,
3704
+	 *                                                                  means default where conditions will apply as
3705
+	 *                                                                  normal
3706
+	 * @param array                       $where_query_params
3707
+	 * @return array
3708
+	 * @throws EE_Error
3709
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3710
+	 */
3711
+	private function _get_default_where_conditions_for_models_in_query(
3712
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3713
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3714
+		$where_query_params = []
3715
+	) {
3716
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3717
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3718
+			throw new EE_Error(
3719
+				sprintf(
3720
+					esc_html__(
3721
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3722
+						"event_espresso"
3723
+					),
3724
+					$use_default_where_conditions,
3725
+					implode(", ", $allowed_used_default_where_conditions_values)
3726
+				)
3727
+			);
3728
+		}
3729
+		$universal_query_params = [];
3730
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3731
+			$universal_query_params = $this->_get_default_where_conditions();
3732
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3733
+			$universal_query_params = $this->_get_minimum_where_conditions();
3734
+		}
3735
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
+			$related_model = $this->get_related_model_obj($model_name);
3737
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
+				$related_model_universal_where_params =
3739
+					$related_model->_get_default_where_conditions($model_relation_path);
3740
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3741
+				$related_model_universal_where_params =
3742
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3743
+			} else {
3744
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3745
+				continue;
3746
+			}
3747
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3748
+				$related_model_universal_where_params,
3749
+				$where_query_params,
3750
+				$related_model,
3751
+				$model_relation_path
3752
+			);
3753
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3754
+				$universal_query_params,
3755
+				$overrides
3756
+			);
3757
+		}
3758
+		return $universal_query_params;
3759
+	}
3760
+
3761
+
3762
+	/**
3763
+	 * Determines whether or not we should use default where conditions for the model in question
3764
+	 * (this model, or other related models).
3765
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3766
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3767
+	 * We should use default where conditions on related models when they requested to use default where conditions
3768
+	 * on all models, or specifically just on other related models
3769
+	 *
3770
+	 * @param      $default_where_conditions_value
3771
+	 * @param bool $for_this_model false means this is for OTHER related models
3772
+	 * @return bool
3773
+	 */
3774
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3775
+	{
3776
+		return (
3777
+				   $for_this_model
3778
+				   && in_array(
3779
+					   $default_where_conditions_value,
3780
+					   [
3781
+						   EEM_Base::default_where_conditions_all,
3782
+						   EEM_Base::default_where_conditions_this_only,
3783
+						   EEM_Base::default_where_conditions_minimum_others,
3784
+					   ],
3785
+					   true
3786
+				   )
3787
+			   )
3788
+			   || (
3789
+				   ! $for_this_model
3790
+				   && in_array(
3791
+					   $default_where_conditions_value,
3792
+					   [
3793
+						   EEM_Base::default_where_conditions_all,
3794
+						   EEM_Base::default_where_conditions_others_only,
3795
+					   ],
3796
+					   true
3797
+				   )
3798
+			   );
3799
+	}
3800
+
3801
+
3802
+	/**
3803
+	 * Determines whether or not we should use default minimum conditions for the model in question
3804
+	 * (this model, or other related models).
3805
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3806
+	 * where conditions.
3807
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3808
+	 * on this model or others
3809
+	 *
3810
+	 * @param      $default_where_conditions_value
3811
+	 * @param bool $for_this_model false means this is for OTHER related models
3812
+	 * @return bool
3813
+	 */
3814
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3815
+	{
3816
+		return (
3817
+				   $for_this_model
3818
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3819
+			   )
3820
+			   || (
3821
+				   ! $for_this_model
3822
+				   && in_array(
3823
+					   $default_where_conditions_value,
3824
+					   [
3825
+						   EEM_Base::default_where_conditions_minimum_others,
3826
+						   EEM_Base::default_where_conditions_minimum_all,
3827
+					   ],
3828
+					   true
3829
+				   )
3830
+			   );
3831
+	}
3832
+
3833
+
3834
+	/**
3835
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3836
+	 * then we also add a special where condition which allows for that model's primary key
3837
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3838
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3839
+	 *
3840
+	 * @param array    $default_where_conditions
3841
+	 * @param array    $provided_where_conditions
3842
+	 * @param EEM_Base $model
3843
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3844
+	 * @return array
3845
+	 * @throws EE_Error
3846
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3847
+	 */
3848
+	private function _override_defaults_or_make_null_friendly(
3849
+		$default_where_conditions,
3850
+		$provided_where_conditions,
3851
+		$model,
3852
+		$model_relation_path
3853
+	) {
3854
+		$null_friendly_where_conditions = [];
3855
+		$none_overridden                = true;
3856
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3857
+		foreach ($default_where_conditions as $key => $val) {
3858
+			if (isset($provided_where_conditions[ $key ])) {
3859
+				$none_overridden = false;
3860
+			} else {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3862
+			}
3863
+		}
3864
+		if ($none_overridden && $default_where_conditions) {
3865
+			if ($model->has_primary_key_field()) {
3866
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3867
+																				   . "."
3868
+																				   . $model->primary_key_name() ] =
3869
+					['IS NULL'];
3870
+			}/*else{
3871 3871
                 //@todo NO PK, use other defaults
3872 3872
             }*/
3873
-        }
3874
-        return $null_friendly_where_conditions;
3875
-    }
3876
-
3877
-
3878
-    /**
3879
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3880
-     * default where conditions on all get_all, update, and delete queries done by this model.
3881
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3882
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3883
-     *
3884
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3885
-     * @return array
3886
-     * @throws EE_Error
3887
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3888
-     */
3889
-    private function _get_default_where_conditions($model_relation_path = '')
3890
-    {
3891
-        if ($this->_ignore_where_strategy) {
3892
-            return [];
3893
-        }
3894
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3895
-    }
3896
-
3897
-
3898
-    /**
3899
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3900
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3901
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3902
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3903
-     * Similar to _get_default_where_conditions
3904
-     *
3905
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3906
-     * @return array
3907
-     * @throws EE_Error
3908
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3909
-     */
3910
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3911
-    {
3912
-        if ($this->_ignore_where_strategy) {
3913
-            return [];
3914
-        }
3915
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3916
-    }
3917
-
3918
-
3919
-    /**
3920
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3921
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3922
-     *
3923
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3924
-     * @return string
3925
-     * @throws EE_Error
3926
-     */
3927
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3928
-    {
3929
-        $selects = $this->_get_columns_to_select_for_this_model();
3930
-        foreach (
3931
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3932
-        ) {
3933
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3934
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3935
-            foreach ($other_model_selects as $value) {
3936
-                $selects[] = $value;
3937
-            }
3938
-        }
3939
-        return implode(", ", $selects);
3940
-    }
3941
-
3942
-
3943
-    /**
3944
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3945
-     * So that's going to be the columns for all the fields on the model
3946
-     *
3947
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3948
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3949
-     */
3950
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3951
-    {
3952
-        $fields                                       = $this->field_settings();
3953
-        $selects                                      = [];
3954
-        $table_alias_with_model_relation_chain_prefix =
3955
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3956
-                $model_relation_chain,
3957
-                $this->get_this_model_name()
3958
-            );
3959
-        foreach ($fields as $field_obj) {
3960
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3961
-                         . $field_obj->get_table_alias()
3962
-                         . "."
3963
-                         . $field_obj->get_table_column()
3964
-                         . " AS '"
3965
-                         . $table_alias_with_model_relation_chain_prefix
3966
-                         . $field_obj->get_table_alias()
3967
-                         . "."
3968
-                         . $field_obj->get_table_column()
3969
-                         . "'";
3970
-        }
3971
-        // make sure we are also getting the PKs of each table
3972
-        $tables = $this->get_tables();
3973
-        if (count($tables) > 1) {
3974
-            foreach ($tables as $table_obj) {
3975
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3976
-                                       . $table_obj->get_fully_qualified_pk_column();
3977
-                if (! in_array($qualified_pk_column, $selects)) {
3978
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3979
-                }
3980
-            }
3981
-        }
3982
-        return $selects;
3983
-    }
3984
-
3985
-
3986
-    /**
3987
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3988
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3989
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3990
-     * SQL for joining, and the data types
3991
-     *
3992
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3993
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3994
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3995
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3996
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3997
-     *                                                          or 'Registration's
3998
-     * @param string|null                 $original_query_param what it originally was (eg
3999
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4000
-     *                                                          matches $query_param
4001
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4002
-     * @throws EE_Error
4003
-     */
4004
-    private function _extract_related_model_info_from_query_param(
4005
-        $query_param,
4006
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4007
-        $query_param_type,
4008
-        $original_query_param = null
4009
-    ) {
4010
-        if ($original_query_param === null) {
4011
-            $original_query_param = $query_param;
4012
-        }
4013
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4014
-        // whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4015
-        $allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4016
-        $allow_fields             = in_array(
4017
-            $query_param_type,
4018
-            ['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4019
-            true
4020
-        );
4021
-        // check to see if we have a field on this model
4022
-        $this_model_fields = $this->field_settings(true);
4023
-        if (array_key_exists($query_param, $this_model_fields)) {
4024
-            if ($allow_fields) {
4025
-                return;
4026
-            }
4027
-            throw new EE_Error(
4028
-                sprintf(
4029
-                    esc_html__(
4030
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4031
-                        "event_espresso"
4032
-                    ),
4033
-                    $query_param,
4034
-                    get_class($this),
4035
-                    $query_param_type,
4036
-                    $original_query_param
4037
-                )
4038
-            );
4039
-        }
4040
-        // check if this is a special logic query param
4041
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4042
-            if ($allow_logic_query_params) {
4043
-                return;
4044
-            }
4045
-            throw new EE_Error(
4046
-                sprintf(
4047
-                    esc_html__(
4048
-                        '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',
4049
-                        'event_espresso'
4050
-                    ),
4051
-                    implode('", "', $this->_logic_query_param_keys),
4052
-                    $query_param,
4053
-                    get_class($this),
4054
-                    '<br />',
4055
-                    "\t"
4056
-                    . ' $passed_in_query_info = <pre>'
4057
-                    . print_r($passed_in_query_info, true)
4058
-                    . '</pre>'
4059
-                    . "\n\t"
4060
-                    . ' $query_param_type = '
4061
-                    . $query_param_type
4062
-                    . "\n\t"
4063
-                    . ' $original_query_param = '
4064
-                    . $original_query_param
4065
-                )
4066
-            );
4067
-        }
4068
-        // check if it's a custom selection
4069
-        if (
4070
-            $this->_custom_selections instanceof CustomSelects
4071
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4072
-        ) {
4073
-            return;
4074
-        }
4075
-        // check if has a model name at the beginning
4076
-        // and
4077
-        // check if it's a field on a related model
4078
-        if (
4079
-        $this->extractJoinModelFromQueryParams(
4080
-            $passed_in_query_info,
4081
-            $query_param,
4082
-            $original_query_param,
4083
-            $query_param_type
4084
-        )
4085
-        ) {
4086
-            return;
4087
-        }
4088
-
4089
-        // ok so $query_param didn't start with a model name
4090
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4091
-        // it's wack, that's what it is
4092
-        throw new EE_Error(
4093
-            sprintf(
4094
-                esc_html__(
4095
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4096
-                    "event_espresso"
4097
-                ),
4098
-                $query_param,
4099
-                get_class($this),
4100
-                $query_param_type,
4101
-                $original_query_param
4102
-            )
4103
-        );
4104
-    }
4105
-
4106
-
4107
-    /**
4108
-     * Extracts any possible join model information from the provided possible_join_string.
4109
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4110
-     * join
4111
-     * parts that should be added to the query.
4112
-     *
4113
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4115
-     * @param null|string                 $original_query_param
4116
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4117
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4118
-     *                                                           etc.)
4119
-     * @return bool  returns true if a join was added and false if not.
4120
-     * @throws EE_Error
4121
-     */
4122
-    private function extractJoinModelFromQueryParams(
4123
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4124
-        $possible_join_string,
4125
-        $original_query_param,
4126
-        $query_parameter_type
4127
-    ) {
4128
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4129
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4130
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4131
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4132
-                if ($possible_join_string === '') {
4133
-                    // nothing left to $query_param
4134
-                    // we should actually end in a field name, not a model like this!
4135
-                    throw new EE_Error(
4136
-                        sprintf(
4137
-                            esc_html__(
4138
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4139
-                                "event_espresso"
4140
-                            ),
4141
-                            $possible_join_string,
4142
-                            $query_parameter_type,
4143
-                            get_class($this),
4144
-                            $valid_related_model_name
4145
-                        )
4146
-                    );
4147
-                }
4148
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4149
-                $related_model_obj->_extract_related_model_info_from_query_param(
4150
-                    $possible_join_string,
4151
-                    $query_info_carrier,
4152
-                    $query_parameter_type,
4153
-                    $original_query_param
4154
-                );
4155
-                return true;
4156
-            }
4157
-            if ($possible_join_string === $valid_related_model_name) {
4158
-                $this->_add_join_to_model(
4159
-                    $valid_related_model_name,
4160
-                    $query_info_carrier,
4161
-                    $original_query_param
4162
-                );
4163
-                return true;
4164
-            }
4165
-        }
4166
-        return false;
4167
-    }
4168
-
4169
-
4170
-    /**
4171
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4172
-     *
4173
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4174
-     * @throws EE_Error
4175
-     */
4176
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4177
-    {
4178
-        if (
4179
-            $this->_custom_selections instanceof CustomSelects
4180
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4181
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4182
-            )
4183
-        ) {
4184
-            $original_selects = $this->_custom_selections->originalSelects();
4185
-            foreach ($original_selects as $select_configuration) {
4186
-                $this->extractJoinModelFromQueryParams(
4187
-                    $query_info_carrier,
4188
-                    $select_configuration[0],
4189
-                    $select_configuration[0],
4190
-                    'custom_selects'
4191
-                );
4192
-            }
4193
-        }
4194
-    }
4195
-
4196
-
4197
-    /**
4198
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4199
-     * and store it on $passed_in_query_info
4200
-     *
4201
-     * @param string                      $model_name
4202
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4203
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4204
-     *                                                          model and $model_name. Eg, if we are querying Event,
4205
-     *                                                          and are adding a join to 'Payment' with the original
4206
-     *                                                          query param key
4207
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4208
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4209
-     *                                                          Payment wants to add default query params so that it
4210
-     *                                                          will know what models to prepend onto its default query
4211
-     *                                                          params or in case it wants to rename tables (in case
4212
-     *                                                          there are multiple joins to the same table)
4213
-     * @return void
4214
-     * @throws EE_Error
4215
-     */
4216
-    private function _add_join_to_model(
4217
-        $model_name,
4218
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4219
-        $original_query_param
4220
-    ) {
4221
-        $relation_obj         = $this->related_settings_for($model_name);
4222
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4223
-        // check if the relation is HABTM, because then we're essentially doing two joins
4224
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4225
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4226
-            $join_model_obj = $relation_obj->get_join_model();
4227
-            // replace the model specified with the join model for this relation chain, whi
4228
-            $relation_chain_to_join_model =
4229
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4230
-                    $model_name,
4231
-                    $join_model_obj->get_this_model_name(),
4232
-                    $model_relation_chain
4233
-                );
4234
-            $passed_in_query_info->merge(
4235
-                new EE_Model_Query_Info_Carrier(
4236
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4237
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4238
-                )
4239
-            );
4240
-        }
4241
-        // now just join to the other table pointed to by the relation object, and add its data types
4242
-        $passed_in_query_info->merge(
4243
-            new EE_Model_Query_Info_Carrier(
4244
-                [$model_relation_chain => $model_name],
4245
-                $relation_obj->get_join_statement($model_relation_chain)
4246
-            )
4247
-        );
4248
-    }
4249
-
4250
-
4251
-    /**
4252
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4253
-     *
4254
-     * @param array $where_params
4255
-     * @return string of SQL
4256
-     * @throws EE_Error
4257
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4258
-     */
4259
-    private function _construct_where_clause($where_params)
4260
-    {
4261
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4262
-        if ($SQL) {
4263
-            return " WHERE " . $SQL;
4264
-        }
4265
-        return '';
4266
-    }
4267
-
4268
-
4269
-    /**
4270
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4271
-     * and should be passed HAVING parameters, not WHERE parameters
4272
-     *
4273
-     * @param array $having_params
4274
-     * @return string
4275
-     * @throws EE_Error
4276
-     */
4277
-    private function _construct_having_clause($having_params)
4278
-    {
4279
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4280
-        if ($SQL) {
4281
-            return " HAVING " . $SQL;
4282
-        }
4283
-        return '';
4284
-    }
4285
-
4286
-
4287
-    /**
4288
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4289
-     * Event_Meta.meta_value = 'foo'))"
4290
-     *
4291
-     * @param array  $where_params
4292
-     * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4293
-     * @return string of SQL
4294
-     * @throws EE_Error
4295
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4296
-     */
4297
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4298
-    {
4299
-        $where_clauses = [];
4300
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4301
-            $query_param =
4302
-                $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4303
-                    $query_param
4304
-                );// str_replace("*",'',$query_param);
4305
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4306
-                switch ($query_param) {
4307
-                    case 'not':
4308
-                    case 'NOT':
4309
-                        $where_clauses[] = "! ("
4310
-                                           . $this->_construct_condition_clause_recursive(
4311
-                                $op_and_value_or_sub_condition,
4312
-                                $glue
4313
-                            )
4314
-                                           . ")";
4315
-                        break;
4316
-                    case 'and':
4317
-                    case 'AND':
4318
-                        $where_clauses[] = " ("
4319
-                                           . $this->_construct_condition_clause_recursive(
4320
-                                $op_and_value_or_sub_condition,
4321
-                                ' AND '
4322
-                            )
4323
-                                           . ")";
4324
-                        break;
4325
-                    case 'or':
4326
-                    case 'OR':
4327
-                        $where_clauses[] = " ("
4328
-                                           . $this->_construct_condition_clause_recursive(
4329
-                                $op_and_value_or_sub_condition,
4330
-                                ' OR '
4331
-                            )
4332
-                                           . ")";
4333
-                        break;
4334
-                }
4335
-            } else {
4336
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4337
-                // if it's not a normal field, maybe it's a custom selection?
4338
-                if (! $field_obj) {
4339
-                    if ($this->_custom_selections instanceof CustomSelects) {
4340
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4341
-                    } else {
4342
-                        throw new EE_Error(
4343
-                            sprintf(
4344
-                                esc_html__(
4345
-                                    "%s is neither a valid model field name, nor a custom selection",
4346
-                                    "event_espresso"
4347
-                                ),
4348
-                                $query_param
4349
-                            )
4350
-                        );
4351
-                    }
4352
-                }
4353
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4354
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4355
-            }
4356
-        }
4357
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4358
-    }
4359
-
4360
-
4361
-    /**
4362
-     * Takes the input parameter and extract the table name (alias) and column name
4363
-     *
4364
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4365
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4366
-     * @throws EE_Error
4367
-     */
4368
-    private function _deduce_column_name_from_query_param($query_param)
4369
-    {
4370
-        $field = $this->_deduce_field_from_query_param($query_param);
4371
-        if ($field) {
4372
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4373
-                $field->get_model_name(),
4374
-                $query_param
4375
-            );
4376
-            return $table_alias_prefix . $field->get_qualified_column();
4377
-        }
4378
-        if (
4379
-            $this->_custom_selections instanceof CustomSelects
4380
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4381
-        ) {
4382
-            // maybe it's custom selection item?
4383
-            // if so, just use it as the "column name"
4384
-            return $query_param;
4385
-        }
4386
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4387
-            ? implode(',', $this->_custom_selections->columnAliases())
4388
-            : '';
4389
-        throw new EE_Error(
4390
-            sprintf(
4391
-                esc_html__(
4392
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4393
-                    "event_espresso"
4394
-                ),
4395
-                $query_param,
4396
-                $custom_select_aliases
4397
-            )
4398
-        );
4399
-    }
4400
-
4401
-
4402
-    /**
4403
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4404
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4405
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4406
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4407
-     *
4408
-     * @param string $condition_query_param_key
4409
-     * @return string
4410
-     */
4411
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4412
-    {
4413
-        $pos_of_star = strpos($condition_query_param_key, '*');
4414
-        if ($pos_of_star === false) {
4415
-            return $condition_query_param_key;
4416
-        }
4417
-        return substr($condition_query_param_key, 0, $pos_of_star);
4418
-    }
4419
-
4420
-
4421
-    /**
4422
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4423
-     *
4424
-     * @param mixed      array | string    $op_and_value
4425
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4426
-     * @return string
4427
-     * @throws EE_Error
4428
-     */
4429
-    private function _construct_op_and_value($op_and_value, $field_obj)
4430
-    {
4431
-        if (is_array($op_and_value)) {
4432
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4433
-            if (! $operator) {
4434
-                $php_array_like_string = [];
4435
-                foreach ($op_and_value as $key => $value) {
4436
-                    $php_array_like_string[] = "$key=>$value";
4437
-                }
4438
-                throw new EE_Error(
4439
-                    sprintf(
4440
-                        esc_html__(
4441
-                            "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))",
4442
-                            "event_espresso"
4443
-                        ),
4444
-                        implode(",", $php_array_like_string)
4445
-                    )
4446
-                );
4447
-            }
4448
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4449
-        } else {
4450
-            $operator = '=';
4451
-            $value    = $op_and_value;
4452
-        }
4453
-        // check to see if the value is actually another field
4454
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4455
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4456
-        }
4457
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4458
-            // in this case, the value should be an array, or at least a comma-separated list
4459
-            // it will need to handle a little differently
4460
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4461
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4462
-            return $operator . SP . $cleaned_value;
4463
-        }
4464
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4465
-            // the value should be an array with count of two.
4466
-            if (count($value) !== 2) {
4467
-                throw new EE_Error(
4468
-                    sprintf(
4469
-                        esc_html__(
4470
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4471
-                            'event_espresso'
4472
-                        ),
4473
-                        "BETWEEN"
4474
-                    )
4475
-                );
4476
-            }
4477
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4478
-            return $operator . SP . $cleaned_value;
4479
-        }
4480
-        if (in_array($operator, $this->valid_null_style_operators())) {
4481
-            if ($value !== null) {
4482
-                throw new EE_Error(
4483
-                    sprintf(
4484
-                        esc_html__(
4485
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4486
-                            "event_espresso"
4487
-                        ),
4488
-                        $value,
4489
-                        $operator
4490
-                    )
4491
-                );
4492
-            }
4493
-            return $operator;
4494
-        }
4495
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4496
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4497
-            // remove other junk. So just treat it as a string.
4498
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4499
-        }
4500
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4502
-        }
4503
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4504
-            throw new EE_Error(
4505
-                sprintf(
4506
-                    esc_html__(
4507
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4508
-                        'event_espresso'
4509
-                    ),
4510
-                    $operator,
4511
-                    $operator
4512
-                )
4513
-            );
4514
-        }
4515
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4516
-            throw new EE_Error(
4517
-                sprintf(
4518
-                    esc_html__(
4519
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4520
-                        'event_espresso'
4521
-                    ),
4522
-                    $operator,
4523
-                    $operator
4524
-                )
4525
-            );
4526
-        }
4527
-        throw new EE_Error(
4528
-            sprintf(
4529
-                esc_html__(
4530
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4531
-                    "event_espresso"
4532
-                ),
4533
-                http_build_query($op_and_value)
4534
-            )
4535
-        );
4536
-    }
4537
-
4538
-
4539
-    /**
4540
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4541
-     *
4542
-     * @param array                      $values
4543
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4544
-     *                                              '%s'
4545
-     * @return string
4546
-     * @throws EE_Error
4547
-     */
4548
-    public function _construct_between_value($values, $field_obj)
4549
-    {
4550
-        $cleaned_values = [];
4551
-        foreach ($values as $value) {
4552
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4553
-        }
4554
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4555
-    }
4556
-
4557
-
4558
-    /**
4559
-     * Takes an array or a comma-separated list of $values and cleans them
4560
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4561
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4562
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4563
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4564
-     *
4565
-     * @param mixed                      $values    array or comma-separated string
4566
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4567
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4568
-     * @throws EE_Error
4569
-     */
4570
-    public function _construct_in_value($values, $field_obj)
4571
-    {
4572
-        // check if the value is a CSV list
4573
-        if (is_string($values)) {
4574
-            // in which case, turn it into an array
4575
-            $values = explode(",", $values);
4576
-        }
4577
-        $cleaned_values = [];
4578
-        foreach ($values as $value) {
4579
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4580
-        }
4581
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4582
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4583
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4584
-        if (empty($cleaned_values)) {
4585
-            $all_fields       = $this->field_settings();
4586
-            $a_field          = array_shift($all_fields);
4587
-            $main_table       = $this->_get_main_table();
4588
-            $cleaned_values[] = "SELECT "
4589
-                                . $a_field->get_table_column()
4590
-                                . " FROM "
4591
-                                . $main_table->get_table_name()
4592
-                                . " WHERE FALSE";
4593
-        }
4594
-        return "(" . implode(",", $cleaned_values) . ")";
4595
-    }
4596
-
4597
-
4598
-    /**
4599
-     * @param mixed                      $value
4600
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4601
-     * @return string
4602
-     * @throws EE_Error
4603
-     */
4604
-    private function _wpdb_prepare_using_field($value, $field_obj)
4605
-    {
4606
-        global $wpdb;
4607
-        if ($field_obj instanceof EE_Model_Field_Base) {
4608
-            return $wpdb->prepare(
4609
-                $field_obj->get_wpdb_data_type(),
4610
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4611
-            );
4612
-        } //$field_obj should really just be a data type
4613
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4614
-            throw new EE_Error(
4615
-                sprintf(
4616
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4617
-                    $field_obj,
4618
-                    implode(",", $this->_valid_wpdb_data_types)
4619
-                )
4620
-            );
4621
-        }
4622
-        return $wpdb->prepare($field_obj, $value);
4623
-    }
4624
-
4625
-
4626
-    /**
4627
-     * Takes the input parameter and finds the model field that it indicates.
4628
-     *
4629
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4630
-     * @return EE_Model_Field_Base
4631
-     * @throws EE_Error
4632
-     */
4633
-    protected function _deduce_field_from_query_param($query_param_name)
4634
-    {
4635
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4636
-        // which will help us find the database table and column
4637
-        $query_param_parts = explode(".", $query_param_name);
4638
-        if (empty($query_param_parts)) {
4639
-            throw new EE_Error(
4640
-                sprintf(
4641
-                    esc_html__(
4642
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4643
-                        'event_espresso'
4644
-                    ),
4645
-                    $query_param_name
4646
-                )
4647
-            );
4648
-        }
4649
-        $number_of_parts       = count($query_param_parts);
4650
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4651
-        $field_name = $last_query_param_part;
4652
-        $model_obj  = $number_of_parts === 1
4653
-            ? $this
4654
-            // $number_of_parts >= 2, the last part is the column name, and there are only 2parts. therefore...
4655
-            : $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4656
-        try {
4657
-            return $model_obj->field_settings_for($field_name);
4658
-        } catch (EE_Error $e) {
4659
-            return null;
4660
-        }
4661
-    }
4662
-
4663
-
4664
-    /**
4665
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4666
-     * alias and column which corresponds to it
4667
-     *
4668
-     * @param string $field_name
4669
-     * @return string
4670
-     * @throws EE_Error
4671
-     */
4672
-    public function _get_qualified_column_for_field($field_name)
4673
-    {
4674
-        $all_fields = $this->field_settings();
4675
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4676
-        if ($field) {
4677
-            return $field->get_qualified_column();
4678
-        }
4679
-        throw new EE_Error(
4680
-            sprintf(
4681
-                esc_html__(
4682
-                    "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.",
4683
-                    'event_espresso'
4684
-                ),
4685
-                $field_name,
4686
-                get_class($this)
4687
-            )
4688
-        );
4689
-    }
4690
-
4691
-
4692
-    /**
4693
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4694
-     * Example usage:
4695
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4696
-     *      array(),
4697
-     *      ARRAY_A,
4698
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4699
-     *  );
4700
-     * is equivalent to
4701
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4702
-     * and
4703
-     *  EEM_Event::instance()->get_all_wpdb_results(
4704
-     *      array(
4705
-     *          array(
4706
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4707
-     *          ),
4708
-     *          ARRAY_A,
4709
-     *          implode(
4710
-     *              ', ',
4711
-     *              array_merge(
4712
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4713
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4714
-     *              )
4715
-     *          )
4716
-     *      )
4717
-     *  );
4718
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4719
-     *
4720
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4721
-     *                                            and the one whose fields you are selecting for example: when querying
4722
-     *                                            tickets model and selecting fields from the tickets model you would
4723
-     *                                            leave this parameter empty, because no models are needed to join
4724
-     *                                            between the queried model and the selected one. Likewise when
4725
-     *                                            querying the datetime model and selecting fields from the tickets
4726
-     *                                            model, it would also be left empty, because there is a direct
4727
-     *                                            relation from datetimes to tickets, so no model is needed to join
4728
-     *                                            them together. However, when querying from the event model and
4729
-     *                                            selecting fields from the ticket model, you should provide the string
4730
-     *                                            'Datetime', indicating that the event model must first join to the
4731
-     *                                            datetime model in order to find its relation to ticket model.
4732
-     *                                            Also, when querying from the venue model and selecting fields from
4733
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4734
-     *                                            indicating you need to join the venue model to the event model,
4735
-     *                                            to the datetime model, in order to find its relation to the ticket
4736
-     *                                            model. This string is used to deduce the prefix that gets added onto
4737
-     *                                            the models' tables qualified columns
4738
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4739
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4740
-     *                                            qualified column names
4741
-     * @return array|string
4742
-     */
4743
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4744
-    {
4745
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4746
-        $qualified_columns = [];
4747
-        foreach ($this->field_settings() as $field) {
4748
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4749
-        }
4750
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4751
-    }
4752
-
4753
-
4754
-    /**
4755
-     * constructs the select use on special limit joins
4756
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4757
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4758
-     * (as that is typically where the limits would be set).
4759
-     *
4760
-     * @param string       $table_alias The table the select is being built for
4761
-     * @param mixed|string $limit       The limit for this select
4762
-     * @return string                The final select join element for the query.
4763
-     * @throws EE_Error
4764
-     */
4765
-    public function _construct_limit_join_select($table_alias, $limit)
4766
-    {
4767
-        $SQL = '';
4768
-        foreach ($this->_tables as $table_obj) {
4769
-            if ($table_obj instanceof EE_Primary_Table) {
4770
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4771
-                    ? $table_obj->get_select_join_limit($limit)
4772
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4773
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4774
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4775
-                    ? $table_obj->get_select_join_limit_join($limit)
4776
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4777
-            }
4778
-        }
4779
-        return $SQL;
4780
-    }
4781
-
4782
-
4783
-    /**
4784
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4785
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4786
-     *
4787
-     * @return string SQL
4788
-     * @throws EE_Error
4789
-     */
4790
-    public function _construct_internal_join()
4791
-    {
4792
-        $SQL = $this->_get_main_table()->get_table_sql();
4793
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4794
-        return $SQL;
4795
-    }
4796
-
4797
-
4798
-    /**
4799
-     * Constructs the SQL for joining all the tables on this model.
4800
-     * Normally $alias should be the primary table's alias, but in cases where
4801
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4802
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4803
-     * alias, this will construct SQL like:
4804
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4805
-     * With $alias being a secondary table's alias, this will construct SQL like:
4806
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4807
-     *
4808
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4809
-     * @return string
4810
-     * @throws EE_Error
4811
-     */
4812
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4813
-    {
4814
-        $SQL               = '';
4815
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4816
-        foreach ($this->_tables as $table_obj) {
4817
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4818
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4819
-                    // so we're joining to this table, meaning the table is already in
4820
-                    // the FROM statement, BUT the primary table isn't. So we want
4821
-                    // to add the inverse join sql
4822
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4823
-                } else {
4824
-                    // just add a regular JOIN to this table from the primary table
4825
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4826
-                }
4827
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4828
-        }
4829
-        return $SQL;
4830
-    }
4831
-
4832
-
4833
-    /**
4834
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4835
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4836
-     * their data type (eg, '%s', '%d', etc)
4837
-     *
4838
-     * @return array
4839
-     */
4840
-    public function _get_data_types()
4841
-    {
4842
-        $data_types = [];
4843
-        foreach ($this->field_settings() as $field_obj) {
4844
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4845
-            /** @var $field_obj EE_Model_Field_Base */
4846
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4847
-        }
4848
-        return $data_types;
4849
-    }
4850
-
4851
-
4852
-    /**
4853
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4854
-     *
4855
-     * @param string $model_name
4856
-     * @return EEM_Base
4857
-     * @throws EE_Error
4858
-     */
4859
-    public function get_related_model_obj($model_name)
4860
-    {
4861
-        $model_classname = "EEM_" . $model_name;
4862
-        if (! class_exists($model_classname)) {
4863
-            throw new EE_Error(
4864
-                sprintf(
4865
-                    esc_html__(
4866
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4867
-                        'event_espresso'
4868
-                    ),
4869
-                    $model_name,
4870
-                    $model_classname
4871
-                )
4872
-            );
4873
-        }
4874
-        return call_user_func($model_classname . "::instance");
4875
-    }
4876
-
4877
-
4878
-    /**
4879
-     * Returns the array of EE_ModelRelations for this model.
4880
-     *
4881
-     * @return EE_Model_Relation_Base[]
4882
-     */
4883
-    public function relation_settings()
4884
-    {
4885
-        return $this->_model_relations;
4886
-    }
4887
-
4888
-
4889
-    /**
4890
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4891
-     * because without THOSE models, this model probably doesn't have much purpose.
4892
-     * (Eg, without an event, datetimes have little purpose.)
4893
-     *
4894
-     * @return EE_Belongs_To_Relation[]
4895
-     */
4896
-    public function belongs_to_relations()
4897
-    {
4898
-        $belongs_to_relations = [];
4899
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4900
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4901
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4902
-            }
4903
-        }
4904
-        return $belongs_to_relations;
4905
-    }
4906
-
4907
-
4908
-    /**
4909
-     * Returns the specified EE_Model_Relation, or throws an exception
4910
-     *
4911
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4912
-     * @return EE_Model_Relation_Base
4913
-     * @throws EE_Error
4914
-     */
4915
-    public function related_settings_for($relation_name)
4916
-    {
4917
-        $relatedModels = $this->relation_settings();
4918
-        if (! array_key_exists($relation_name, $relatedModels)) {
4919
-            throw new EE_Error(
4920
-                sprintf(
4921
-                    esc_html__(
4922
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4923
-                        'event_espresso'
4924
-                    ),
4925
-                    $relation_name,
4926
-                    $this->_get_class_name(),
4927
-                    implode(', ', array_keys($relatedModels))
4928
-                )
4929
-            );
4930
-        }
4931
-        return $relatedModels[ $relation_name ];
4932
-    }
4933
-
4934
-
4935
-    /**
4936
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4937
-     * fields
4938
-     *
4939
-     * @param string  $fieldName
4940
-     * @param boolean $include_db_only_fields
4941
-     * @return EE_Model_Field_Base
4942
-     * @throws EE_Error
4943
-     */
4944
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4945
-    {
4946
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4947
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4948
-            throw new EE_Error(
4949
-                sprintf(
4950
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4951
-                    $fieldName,
4952
-                    get_class($this)
4953
-                )
4954
-            );
4955
-        }
4956
-        return $fieldSettings[ $fieldName ];
4957
-    }
4958
-
4959
-
4960
-    /**
4961
-     * Checks if this field exists on this model
4962
-     *
4963
-     * @param string $fieldName a key in the model's _field_settings array
4964
-     * @return boolean
4965
-     */
4966
-    public function has_field($fieldName)
4967
-    {
4968
-        $fieldSettings = $this->field_settings(true);
4969
-        if (isset($fieldSettings[ $fieldName ])) {
4970
-            return true;
4971
-        }
4972
-        return false;
4973
-    }
4974
-
4975
-
4976
-    /**
4977
-     * Returns whether or not this model has a relation to the specified model
4978
-     *
4979
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4980
-     * @return boolean
4981
-     */
4982
-    public function has_relation($relation_name)
4983
-    {
4984
-        $relations = $this->relation_settings();
4985
-        if (isset($relations[ $relation_name ])) {
4986
-            return true;
4987
-        }
4988
-        return false;
4989
-    }
4990
-
4991
-
4992
-    /**
4993
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4994
-     * Eg, on EE_Answer that would be ANS_ID field object
4995
-     *
4996
-     * @param $field_obj
4997
-     * @return boolean
4998
-     */
4999
-    public function is_primary_key_field($field_obj)
5000
-    {
5001
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5002
-    }
5003
-
5004
-
5005
-    /**
5006
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5007
-     * Eg, on EE_Answer that would be ANS_ID field object
5008
-     *
5009
-     * @return EE_Model_Field_Base
5010
-     * @throws EE_Error
5011
-     */
5012
-    public function get_primary_key_field()
5013
-    {
5014
-        if ($this->_primary_key_field === null) {
5015
-            foreach ($this->field_settings(true) as $field_obj) {
5016
-                if ($this->is_primary_key_field($field_obj)) {
5017
-                    $this->_primary_key_field = $field_obj;
5018
-                    break;
5019
-                }
5020
-            }
5021
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5022
-                throw new EE_Error(
5023
-                    sprintf(
5024
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5025
-                        get_class($this)
5026
-                    )
5027
-                );
5028
-            }
5029
-        }
5030
-        return $this->_primary_key_field;
5031
-    }
5032
-
5033
-
5034
-    /**
5035
-     * Returns whether or not not there is a primary key on this model.
5036
-     * Internally does some caching.
5037
-     *
5038
-     * @return boolean
5039
-     */
5040
-    public function has_primary_key_field()
5041
-    {
5042
-        if ($this->_has_primary_key_field === null) {
5043
-            try {
5044
-                $this->get_primary_key_field();
5045
-                $this->_has_primary_key_field = true;
5046
-            } catch (EE_Error $e) {
5047
-                $this->_has_primary_key_field = false;
5048
-            }
5049
-        }
5050
-        return $this->_has_primary_key_field;
5051
-    }
5052
-
5053
-
5054
-    /**
5055
-     * Finds the first field of type $field_class_name.
5056
-     *
5057
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5058
-     *                                 EE_Foreign_Key_Field, etc
5059
-     * @return EE_Model_Field_Base or null if none is found
5060
-     */
5061
-    public function get_a_field_of_type($field_class_name)
5062
-    {
5063
-        foreach ($this->field_settings() as $field) {
5064
-            if ($field instanceof $field_class_name) {
5065
-                return $field;
5066
-            }
5067
-        }
5068
-        return null;
5069
-    }
5070
-
5071
-
5072
-    /**
5073
-     * Gets a foreign key field pointing to model.
5074
-     *
5075
-     * @param string $model_name eg Event, Registration, not EEM_Event
5076
-     * @return EE_Foreign_Key_Field_Base
5077
-     * @throws EE_Error
5078
-     */
5079
-    public function get_foreign_key_to($model_name)
5080
-    {
5081
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
-            foreach ($this->field_settings() as $field) {
5083
-                if (
5084
-                    $field instanceof EE_Foreign_Key_Field_Base
5085
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5086
-                ) {
5087
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5088
-                    break;
5089
-                }
5090
-            }
5091
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5092
-                throw new EE_Error(
5093
-                    sprintf(
5094
-                        esc_html__(
5095
-                            "There is no foreign key field pointing to model %s on model %s",
5096
-                            'event_espresso'
5097
-                        ),
5098
-                        $model_name,
5099
-                        get_class($this)
5100
-                    )
5101
-                );
5102
-            }
5103
-        }
5104
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5105
-    }
5106
-
5107
-
5108
-    /**
5109
-     * Gets the table name (including $wpdb->prefix) for the table alias
5110
-     *
5111
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5112
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5113
-     *                            Either one works
5114
-     * @return string
5115
-     */
5116
-    public function get_table_for_alias($table_alias)
5117
-    {
5118
-        $table_alias_sans_model_relation_chain_prefix =
5119
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5120
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5121
-    }
5122
-
5123
-
5124
-    /**
5125
-     * Returns a flat array of all field son this model, instead of organizing them
5126
-     * by table_alias as they are in the constructor.
5127
-     *
5128
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5129
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5130
-     */
5131
-    public function field_settings($include_db_only_fields = false)
5132
-    {
5133
-        if ($include_db_only_fields) {
5134
-            if ($this->_cached_fields === null) {
5135
-                $this->_cached_fields = [];
5136
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5137
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5139
-                    }
5140
-                }
5141
-            }
5142
-            return $this->_cached_fields;
5143
-        }
5144
-        if ($this->_cached_fields_non_db_only === null) {
5145
-            $this->_cached_fields_non_db_only = [];
5146
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5147
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148
-                    /** @var $field_obj EE_Model_Field_Base */
5149
-                    if (! $field_obj->is_db_only_field()) {
5150
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5151
-                    }
5152
-                }
5153
-            }
5154
-        }
5155
-        return $this->_cached_fields_non_db_only;
5156
-    }
5157
-
5158
-
5159
-    /**
5160
-     *        cycle though array of attendees and create objects out of each item
5161
-     *
5162
-     * @access        private
5163
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5164
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5165
-     *                           numerically indexed)
5166
-     * @throws EE_Error
5167
-     * @throws ReflectionException
5168
-     */
5169
-    protected function _create_objects($rows = [])
5170
-    {
5171
-        $array_of_objects = [];
5172
-        if (empty($rows)) {
5173
-            return [];
5174
-        }
5175
-        $count_if_model_has_no_primary_key = 0;
5176
-        $has_primary_key                   = $this->has_primary_key_field();
5177
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5178
-        foreach ((array)$rows as $row) {
5179
-            if (empty($row)) {
5180
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5181
-                return [];
5182
-            }
5183
-            // check if we've already set this object in the results array,
5184
-            // in which case there's no need to process it further (again)
5185
-            if ($has_primary_key) {
5186
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5187
-                    $row,
5188
-                    $primary_key_field->get_qualified_column(),
5189
-                    $primary_key_field->get_table_column()
5190
-                );
5191
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5192
-                    continue;
5193
-                }
5194
-            }
5195
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5196
-            if (! $classInstance) {
5197
-                throw new EE_Error(
5198
-                    sprintf(
5199
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5200
-                        $this->get_this_model_name(),
5201
-                        http_build_query($row)
5202
-                    )
5203
-                );
5204
-            }
5205
-            // set the timezone on the instantiated objects
5206
-            $classInstance->set_timezone($this->get_timezone(), true);
5207
-            // make sure if there is any timezone setting present that we set the timezone for the object
5208
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5209
-            $array_of_objects[ $key ] = $classInstance;
5210
-            // also, for all the relations of type BelongsTo, see if we can cache
5211
-            // those related models
5212
-            // (we could do this for other relations too, but if there are conditions
5213
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5214
-            // so it requires a little more thought than just caching them immediately...)
5215
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5216
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5217
-                    // check if this model's INFO is present. If so, cache it on the model
5218
-                    $other_model           = $relation_obj->get_other_model();
5219
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5220
-                    // if we managed to make a model object from the results, cache it on the main model object
5221
-                    if ($other_model_obj_maybe) {
5222
-                        // set timezone on these other model objects if they are present
5223
-                        $other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5224
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5225
-                    }
5226
-                }
5227
-            }
5228
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5229
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5230
-            // the field in the CustomSelects object
5231
-            if ($this->_custom_selections instanceof CustomSelects) {
5232
-                $classInstance->setCustomSelectsValues(
5233
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5234
-                );
5235
-            }
5236
-        }
5237
-        return $array_of_objects;
5238
-    }
5239
-
5240
-
5241
-    /**
5242
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5243
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5244
-     *
5245
-     * @param array $db_results_row
5246
-     * @return array
5247
-     */
5248
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5249
-    {
5250
-        $results = [];
5251
-        if ($this->_custom_selections instanceof CustomSelects) {
5252
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5253
-                if (isset($db_results_row[ $alias ])) {
5254
-                    $results[ $alias ] = $this->convertValueToDataType(
5255
-                        $db_results_row[ $alias ],
5256
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5257
-                    );
5258
-                }
5259
-            }
5260
-        }
5261
-        return $results;
5262
-    }
5263
-
5264
-
5265
-    /**
5266
-     * This will set the value for the given alias
5267
-     *
5268
-     * @param string $value
5269
-     * @param string $datatype (one of %d, %s, %f)
5270
-     * @return int|string|float (int for %d, string for %s, float for %f)
5271
-     */
5272
-    protected function convertValueToDataType($value, $datatype)
5273
-    {
5274
-        switch ($datatype) {
5275
-            case '%f':
5276
-                return (float)$value;
5277
-            case '%d':
5278
-                return (int)$value;
5279
-            default:
5280
-                return (string)$value;
5281
-        }
5282
-    }
5283
-
5284
-
5285
-    /**
5286
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5287
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5288
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5289
-     * object (as set in the model_field!).
5290
-     *
5291
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5292
-     * @throws EE_Error
5293
-     * @throws ReflectionException
5294
-     */
5295
-    public function create_default_object()
5296
-    {
5297
-        $this_model_fields_and_values = [];
5298
-        // setup the row using default values;
5299
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5300
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5301
-        }
5302
-        $className = $this->_get_class_name();
5303
-        return EE_Registry::instance()->load_class(
5304
-            $className,
5305
-            [$this_model_fields_and_values],
5306
-            false,
5307
-            false
5308
-        );
5309
-    }
5310
-
5311
-
5312
-    /**
5313
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5314
-     *                             or an stdClass where each property is the name of a column,
5315
-     * @return EE_Base_Class
5316
-     * @throws EE_Error
5317
-     * @throws ReflectionException
5318
-     */
5319
-    public function instantiate_class_from_array_or_object($cols_n_values)
5320
-    {
5321
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5322
-            $cols_n_values = get_object_vars($cols_n_values);
5323
-        }
5324
-        $primary_key = null;
5325
-        // make sure the array only has keys that are fields/columns on this model
5326
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5327
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5328
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5329
-        }
5330
-        $className = $this->_get_class_name();
5331
-        // check we actually found results that we can use to build our model object
5332
-        // if not, return null
5333
-        if ($this->has_primary_key_field()) {
5334
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5335
-                return null;
5336
-            }
5337
-        } elseif ($this->unique_indexes()) {
5338
-            $first_column = reset($this_model_fields_n_values);
5339
-            if (empty($first_column)) {
5340
-                return null;
5341
-            }
5342
-        }
5343
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5344
-        if ($primary_key) {
5345
-            $classInstance = $this->get_from_entity_map($primary_key);
5346
-            if (! $classInstance) {
5347
-                $classInstance = EE_Registry::instance()->load_class(
5348
-                    $className,
5349
-                    [$this_model_fields_n_values, $this->get_timezone()],
5350
-                    true,
5351
-                    false
5352
-                );
5353
-                // add this new object to the entity map
5354
-                $classInstance = $this->add_to_entity_map($classInstance);
5355
-            }
5356
-        } else {
5357
-            $classInstance = EE_Registry::instance()->load_class(
5358
-                $className,
5359
-                [$this_model_fields_n_values, $this->get_timezone()],
5360
-                true,
5361
-                false
5362
-            );
5363
-        }
5364
-        return $classInstance;
5365
-    }
5366
-
5367
-
5368
-    /**
5369
-     * Gets the model object from the  entity map if it exists
5370
-     *
5371
-     * @param int|string $id the ID of the model object
5372
-     * @return EE_Base_Class
5373
-     */
5374
-    public function get_from_entity_map($id)
5375
-    {
5376
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5377
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5378
-            : null;
5379
-    }
5380
-
5381
-
5382
-    /**
5383
-     * add_to_entity_map
5384
-     * Adds the object to the model's entity mappings
5385
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5386
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5387
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5388
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5389
-     *        then this method should be called immediately after the update query
5390
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5391
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5392
-     *
5393
-     * @param EE_Base_Class $object
5394
-     * @return EE_Base_Class
5395
-     * @throws EE_Error
5396
-     */
5397
-    public function add_to_entity_map(EE_Base_Class $object)
5398
-    {
5399
-        $className = $this->_get_class_name();
5400
-        if (! $object instanceof $className) {
5401
-            throw new EE_Error(
5402
-                sprintf(
5403
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5404
-                    is_object($object) ? get_class($object) : $object,
5405
-                    $className
5406
-                )
5407
-            );
5408
-        }
5409
-        if (! $object->ID()) {
5410
-            throw new DomainException(
5411
-                sprintf(
5412
-                    esc_html__(
5413
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5414
-                        "event_espresso"
5415
-                    ),
5416
-                    get_class($this)
5417
-                )
5418
-            );
5419
-        }
5420
-        // double check it's not already there
5421
-        $classInstance = $this->get_from_entity_map($object->ID());
5422
-        if ($classInstance) {
5423
-            return $classInstance;
5424
-        }
5425
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5426
-        return $object;
5427
-    }
5428
-
5429
-
5430
-    /**
5431
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5432
-     * if no identifier is provided, then the entire entity map is emptied
5433
-     *
5434
-     * @param int|string $id the ID of the model object
5435
-     * @return boolean
5436
-     */
5437
-    public function clear_entity_map($id = null)
5438
-    {
5439
-        if (empty($id)) {
5440
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5441
-            return true;
5442
-        }
5443
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5444
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5445
-            return true;
5446
-        }
5447
-        return false;
5448
-    }
5449
-
5450
-
5451
-    /**
5452
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5453
-     * Given an array where keys are column (or column alias) names and values,
5454
-     * returns an array of their corresponding field names and database values
5455
-     *
5456
-     * @param array $cols_n_values
5457
-     * @return array
5458
-     * @throws EE_Error
5459
-     * @throws ReflectionException
5460
-     */
5461
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5462
-    {
5463
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5464
-    }
5465
-
5466
-
5467
-    /**
5468
-     * _deduce_fields_n_values_from_cols_n_values
5469
-     * Given an array where keys are column (or column alias) names and values,
5470
-     * returns an array of their corresponding field names and database values
5471
-     *
5472
-     * @param array $cols_n_values
5473
-     * @return array
5474
-     * @throws EE_Error
5475
-     * @throws ReflectionException
5476
-     */
5477
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5478
-    {
5479
-        $this_model_fields_n_values = [];
5480
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5481
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5482
-                $cols_n_values,
5483
-                $table_obj->get_fully_qualified_pk_column(),
5484
-                $table_obj->get_pk_column()
5485
-            );
5486
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5487
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5488
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5489
-                    if (! $field_obj->is_db_only_field()) {
5490
-                        // prepare field as if its coming from db
5491
-                        $prepared_value                            =
5492
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5493
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5494
-                    }
5495
-                }
5496
-            } else {
5497
-                // the table's rows existed. Use their values
5498
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5499
-                    if (! $field_obj->is_db_only_field()) {
5500
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5501
-                            $cols_n_values,
5502
-                            $field_obj->get_qualified_column(),
5503
-                            $field_obj->get_table_column()
5504
-                        );
5505
-                    }
5506
-                }
5507
-            }
5508
-        }
5509
-        return $this_model_fields_n_values;
5510
-    }
5511
-
5512
-
5513
-    /**
5514
-     * @param array  $cols_n_values
5515
-     * @param string $qualified_column
5516
-     * @param string $regular_column
5517
-     * @return null
5518
-     * @throws EE_Error
5519
-     * @throws ReflectionException
5520
-     */
5521
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5522
-    {
5523
-        $value = null;
5524
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5525
-        // does the field on the model relate to this column retrieved from the db?
5526
-        // or is it a db-only field? (not relating to the model)
5527
-        if (isset($cols_n_values[ $qualified_column ])) {
5528
-            $value = $cols_n_values[ $qualified_column ];
5529
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5530
-            $value = $cols_n_values[ $regular_column ];
5531
-        } elseif (! empty($this->foreign_key_aliases)) {
5532
-            // no PK?  ok check if there is a foreign key alias set for this table
5533
-            // then check if that alias exists in the incoming data
5534
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5535
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5536
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5537
-                    $value = $cols_n_values[ $FK_alias ];
5538
-                    [$pk_class] = explode('.', $PK_column);
5539
-                    $pk_model_name = "EEM_{$pk_class}";
5540
-                    /** @var EEM_Base $pk_model */
5541
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5542
-                    if ($pk_model instanceof EEM_Base) {
5543
-                        // make sure object is pulled from db and added to entity map
5544
-                        $pk_model->get_one_by_ID($value);
5545
-                    }
5546
-                    break;
5547
-                }
5548
-            }
5549
-        }
5550
-        return $value;
5551
-    }
5552
-
5553
-
5554
-    /**
5555
-     * refresh_entity_map_from_db
5556
-     * Makes sure the model object in the entity map at $id assumes the values
5557
-     * of the database (opposite of EE_base_Class::save())
5558
-     *
5559
-     * @param int|string $id
5560
-     * @return EE_Base_Class
5561
-     * @throws EE_Error
5562
-     * @throws ReflectionException
5563
-     */
5564
-    public function refresh_entity_map_from_db($id)
5565
-    {
5566
-        $obj_in_map = $this->get_from_entity_map($id);
5567
-        if ($obj_in_map) {
5568
-            $wpdb_results = $this->_get_all_wpdb_results(
5569
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5570
-            );
5571
-            if ($wpdb_results && is_array($wpdb_results)) {
5572
-                $one_row = reset($wpdb_results);
5573
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5574
-                    $obj_in_map->set_from_db($field_name, $db_value);
5575
-                }
5576
-                // clear the cache of related model objects
5577
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5578
-                    $obj_in_map->clear_cache($relation_name, null, true);
5579
-                }
5580
-            }
5581
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5582
-            return $obj_in_map;
5583
-        }
5584
-        return $this->get_one_by_ID($id);
5585
-    }
5586
-
5587
-
5588
-    /**
5589
-     * refresh_entity_map_with
5590
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5591
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5592
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5593
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5594
-     *
5595
-     * @param int|string    $id
5596
-     * @param EE_Base_Class $replacing_model_obj
5597
-     * @return EE_Base_Class
5598
-     * @throws EE_Error
5599
-     * @throws ReflectionException
5600
-     */
5601
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5602
-    {
5603
-        $obj_in_map = $this->get_from_entity_map($id);
5604
-        if ($obj_in_map) {
5605
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5606
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5607
-                    $obj_in_map->set($field_name, $value);
5608
-                }
5609
-                // make the model object in the entity map's cache match the $replacing_model_obj
5610
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5611
-                    $obj_in_map->clear_cache($relation_name, null, true);
5612
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5613
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5614
-                    }
5615
-                }
5616
-            }
5617
-            return $obj_in_map;
5618
-        }
5619
-        $this->add_to_entity_map($replacing_model_obj);
5620
-        return $replacing_model_obj;
5621
-    }
5622
-
5623
-
5624
-    /**
5625
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5626
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5627
-     * require_once($this->_getClassName().".class.php");
5628
-     *
5629
-     * @return string
5630
-     */
5631
-    private function _get_class_name()
5632
-    {
5633
-        return "EE_" . $this->get_this_model_name();
5634
-    }
5635
-
5636
-
5637
-    /**
5638
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5639
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5640
-     * it would be 'Events'.
5641
-     *
5642
-     * @param int $quantity
5643
-     * @return string
5644
-     */
5645
-    public function item_name($quantity = 1)
5646
-    {
5647
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5648
-    }
5649
-
5650
-
5651
-    /**
5652
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5653
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5654
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5655
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5656
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5657
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5658
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5659
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5660
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5661
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5662
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5663
-     *        return $previousReturnValue.$returnString;
5664
-     * }
5665
-     * require('EEM_Answer.model.php');
5666
-     * $answer=EEM_Answer::instance();
5667
-     * echo $answer->my_callback('monkeys',100);
5668
-     * //will output "you called my_callback! and passed args:monkeys,100"
5669
-     *
5670
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5671
-     * @param array  $args       array of original arguments passed to the function
5672
-     * @return mixed whatever the plugin which calls add_filter decides
5673
-     * @throws EE_Error
5674
-     */
5675
-    public function __call($methodName, $args)
5676
-    {
5677
-        $className = get_class($this);
5678
-        $tagName   = "FHEE__{$className}__{$methodName}";
5679
-        if (! has_filter($tagName)) {
5680
-            throw new EE_Error(
5681
-                sprintf(
5682
-                    esc_html__(
5683
-                        '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 );',
5684
-                        'event_espresso'
5685
-                    ),
5686
-                    $methodName,
5687
-                    $className,
5688
-                    $tagName,
5689
-                    '<br />'
5690
-                )
5691
-            );
5692
-        }
5693
-        return apply_filters($tagName, null, $this, $args);
5694
-    }
5695
-
5696
-
5697
-    /**
5698
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5699
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5700
-     *
5701
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5702
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5703
-     *                                                       the object's class name
5704
-     *                                                       or object's ID
5705
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5706
-     *                                                       exists in the database. If it does not, we add it
5707
-     * @return EE_Base_Class
5708
-     * @throws EE_Error
5709
-     * @throws ReflectionException
5710
-     */
5711
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5712
-    {
5713
-        $className = $this->_get_class_name();
5714
-        if ($base_class_obj_or_id instanceof $className) {
5715
-            $model_object = $base_class_obj_or_id;
5716
-        } else {
5717
-            $primary_key_field = $this->get_primary_key_field();
5718
-            if (
5719
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5720
-                && (
5721
-                    is_int($base_class_obj_or_id)
5722
-                    || is_string($base_class_obj_or_id)
5723
-                )
5724
-            ) {
5725
-                // assume it's an ID.
5726
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5727
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5728
-            } elseif (
5729
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5730
-                && is_string($base_class_obj_or_id)
5731
-            ) {
5732
-                // assume its a string representation of the object
5733
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5734
-            } else {
5735
-                throw new EE_Error(
5736
-                    sprintf(
5737
-                        esc_html__(
5738
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5739
-                            'event_espresso'
5740
-                        ),
5741
-                        $base_class_obj_or_id,
5742
-                        $this->_get_class_name(),
5743
-                        print_r($base_class_obj_or_id, true)
5744
-                    )
5745
-                );
5746
-            }
5747
-        }
5748
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5749
-            $model_object->save();
5750
-        }
5751
-        return $model_object;
5752
-    }
5753
-
5754
-
5755
-    /**
5756
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5757
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5758
-     * returns it ID.
5759
-     *
5760
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5761
-     * @return int|string depending on the type of this model object's ID
5762
-     * @throws EE_Error
5763
-     */
5764
-    public function ensure_is_ID($base_class_obj_or_id)
5765
-    {
5766
-        $className = $this->_get_class_name();
5767
-        if ($base_class_obj_or_id instanceof $className) {
5768
-            $id = $base_class_obj_or_id->ID();
5769
-        } elseif (is_int($base_class_obj_or_id)) {
5770
-            // assume it's an ID
5771
-            $id = $base_class_obj_or_id;
5772
-        } elseif (is_string($base_class_obj_or_id)) {
5773
-            // assume its a string representation of the object
5774
-            $id = $base_class_obj_or_id;
5775
-        } else {
5776
-            throw new EE_Error(
5777
-                sprintf(
5778
-                    esc_html__(
5779
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5780
-                        'event_espresso'
5781
-                    ),
5782
-                    $base_class_obj_or_id,
5783
-                    $this->_get_class_name(),
5784
-                    print_r($base_class_obj_or_id, true)
5785
-                )
5786
-            );
5787
-        }
5788
-        return $id;
5789
-    }
5790
-
5791
-
5792
-    /**
5793
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5794
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5795
-     * been sanitized and converted into the appropriate domain.
5796
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5797
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5798
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5799
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5800
-     * $EVT = EEM_Event::instance(); $old_setting =
5801
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5802
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5803
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5804
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5805
-     *
5806
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5807
-     * @return void
5808
-     */
5809
-    public function assume_values_already_prepared_by_model_object(
5810
-        $values_already_prepared = self::not_prepared_by_model_object
5811
-    ) {
5812
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5813
-    }
5814
-
5815
-
5816
-    /**
5817
-     * Read comments for assume_values_already_prepared_by_model_object()
5818
-     *
5819
-     * @return int
5820
-     */
5821
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5822
-    {
5823
-        return $this->_values_already_prepared_by_model_object;
5824
-    }
5825
-
5826
-
5827
-    /**
5828
-     * Gets all the indexes on this model
5829
-     *
5830
-     * @return EE_Index[]
5831
-     */
5832
-    public function indexes()
5833
-    {
5834
-        return $this->_indexes;
5835
-    }
5836
-
5837
-
5838
-    /**
5839
-     * Gets all the Unique Indexes on this model
5840
-     *
5841
-     * @return EE_Unique_Index[]
5842
-     */
5843
-    public function unique_indexes()
5844
-    {
5845
-        $unique_indexes = [];
5846
-        foreach ($this->_indexes as $name => $index) {
5847
-            if ($index instanceof EE_Unique_Index) {
5848
-                $unique_indexes [ $name ] = $index;
5849
-            }
5850
-        }
5851
-        return $unique_indexes;
5852
-    }
5853
-
5854
-
5855
-    /**
5856
-     * Gets all the fields which, when combined, make the primary key.
5857
-     * This is usually just an array with 1 element (the primary key), but in cases
5858
-     * where there is no primary key, it's a combination of fields as defined
5859
-     * on a primary index
5860
-     *
5861
-     * @return EE_Model_Field_Base[] indexed by the field's name
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function get_combined_primary_key_fields()
5865
-    {
5866
-        foreach ($this->indexes() as $index) {
5867
-            if ($index instanceof EE_Primary_Key_Index) {
5868
-                return $index->fields();
5869
-            }
5870
-        }
5871
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5872
-    }
5873
-
5874
-
5875
-    /**
5876
-     * Used to build a primary key string (when the model has no primary key),
5877
-     * which can be used a unique string to identify this model object.
5878
-     *
5879
-     * @param array $fields_n_values keys are field names, values are their values.
5880
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5881
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5882
-     *                               before passing it to this function (that will convert it from columns-n-values
5883
-     *                               to field-names-n-values).
5884
-     * @return string
5885
-     * @throws EE_Error
5886
-     */
5887
-    public function get_index_primary_key_string($fields_n_values)
5888
-    {
5889
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5890
-            $fields_n_values,
5891
-            $this->get_combined_primary_key_fields()
5892
-        );
5893
-        return http_build_query($cols_n_values_for_primary_key_index);
5894
-    }
5895
-
5896
-
5897
-    /**
5898
-     * Gets the field values from the primary key string
5899
-     *
5900
-     * @param string $index_primary_key_string
5901
-     * @return null|array
5902
-     * @throws EE_Error
5903
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5904
-     */
5905
-    public function parse_index_primary_key_string($index_primary_key_string)
5906
-    {
5907
-        $key_fields = $this->get_combined_primary_key_fields();
5908
-        // check all of them are in the $id
5909
-        $key_values_in_combined_pk = [];
5910
-        parse_str($index_primary_key_string, $key_values_in_combined_pk);
5911
-        foreach ($key_fields as $key_field_name => $field_obj) {
5912
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5913
-                return null;
5914
-            }
5915
-        }
5916
-        return $key_values_in_combined_pk;
5917
-    }
5918
-
5919
-
5920
-    /**
5921
-     * verifies that an array of key-value pairs for model fields has a key
5922
-     * for each field comprising the primary key index
5923
-     *
5924
-     * @param array $key_values
5925
-     * @return boolean
5926
-     * @throws EE_Error
5927
-     */
5928
-    public function has_all_combined_primary_key_fields($key_values)
5929
-    {
5930
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5931
-        foreach ($keys_it_should_have as $key) {
5932
-            if (! isset($key_values[ $key ])) {
5933
-                return false;
5934
-            }
5935
-        }
5936
-        return true;
5937
-    }
5938
-
5939
-
5940
-    /**
5941
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5942
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5943
-     *
5944
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5945
-     * @param array               $query_params                     see github link below for more info
5946
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5947
-     * @throws EE_Error
5948
-     * @throws ReflectionException
5949
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5950
-     *                                                              indexed)
5951
-     */
5952
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5953
-    {
5954
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5955
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5956
-        } elseif (is_array($model_object_or_attributes_array)) {
5957
-            $attributes_array = $model_object_or_attributes_array;
5958
-        } else {
5959
-            throw new EE_Error(
5960
-                sprintf(
5961
-                    esc_html__(
5962
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5963
-                        "event_espresso"
5964
-                    ),
5965
-                    $model_object_or_attributes_array
5966
-                )
5967
-            );
5968
-        }
5969
-        // even copies obviously won't have the same ID, so remove the primary key
5970
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5971
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5972
-            unset($attributes_array[ $this->primary_key_name() ]);
5973
-        }
5974
-        if (isset($query_params[0])) {
5975
-            $query_params[0] = array_merge($attributes_array, $query_params);
5976
-        } else {
5977
-            $query_params[0] = $attributes_array;
5978
-        }
5979
-        return $this->get_all($query_params);
5980
-    }
5981
-
5982
-
5983
-    /**
5984
-     * Gets the first copy we find. See get_all_copies for more details
5985
-     *
5986
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5987
-     * @param array $query_params
5988
-     * @return EE_Base_Class
5989
-     * @throws EE_Error
5990
-     * @throws ReflectionException
5991
-     */
5992
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5993
-    {
5994
-        if (! is_array($query_params)) {
5995
-            EE_Error::doing_it_wrong(
5996
-                'EEM_Base::get_one_copy',
5997
-                sprintf(
5998
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5999
-                    gettype($query_params)
6000
-                ),
6001
-                '4.6.0'
6002
-            );
6003
-            $query_params = [];
6004
-        }
6005
-        $query_params['limit'] = 1;
6006
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6007
-        if (is_array($copies)) {
6008
-            return array_shift($copies);
6009
-        }
6010
-        return null;
6011
-    }
6012
-
6013
-
6014
-    /**
6015
-     * Updates the item with the specified id. Ignores default query parameters because
6016
-     * we have specified the ID, and its assumed we KNOW what we're doing
6017
-     *
6018
-     * @param array      $fields_n_values keys are field names, values are their new values
6019
-     * @param int|string $id              the value of the primary key to update
6020
-     * @return int number of rows updated
6021
-     * @throws EE_Error
6022
-     * @throws ReflectionException
6023
-     */
6024
-    public function update_by_ID($fields_n_values, $id)
6025
-    {
6026
-        $query_params = [
6027
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6028
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6029
-        ];
6030
-        return $this->update($fields_n_values, $query_params);
6031
-    }
6032
-
6033
-
6034
-    /**
6035
-     * Changes an operator which was supplied to the models into one usable in SQL
6036
-     *
6037
-     * @param string $operator_supplied
6038
-     * @return string an operator which can be used in SQL
6039
-     * @throws EE_Error
6040
-     */
6041
-    private function _prepare_operator_for_sql($operator_supplied)
6042
-    {
6043
-        $sql_operator =
6044
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6045
-                : null;
6046
-        if ($sql_operator) {
6047
-            return $sql_operator;
6048
-        }
6049
-        throw new EE_Error(
6050
-            sprintf(
6051
-                esc_html__(
6052
-                    "The operator '%s' is not in the list of valid operators: %s",
6053
-                    "event_espresso"
6054
-                ),
6055
-                $operator_supplied,
6056
-                implode(",", array_keys($this->_valid_operators))
6057
-            )
6058
-        );
6059
-    }
6060
-
6061
-
6062
-    /**
6063
-     * Gets the valid operators
6064
-     *
6065
-     * @return array keys are accepted strings, values are the SQL they are converted to
6066
-     */
6067
-    public function valid_operators()
6068
-    {
6069
-        return $this->_valid_operators;
6070
-    }
6071
-
6072
-
6073
-    /**
6074
-     * Gets the between-style operators (take 2 arguments).
6075
-     *
6076
-     * @return array keys are accepted strings, values are the SQL they are converted to
6077
-     */
6078
-    public function valid_between_style_operators()
6079
-    {
6080
-        return array_intersect(
6081
-            $this->valid_operators(),
6082
-            $this->_between_style_operators
6083
-        );
6084
-    }
6085
-
6086
-
6087
-    /**
6088
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6089
-     *
6090
-     * @return array keys are accepted strings, values are the SQL they are converted to
6091
-     */
6092
-    public function valid_like_style_operators()
6093
-    {
6094
-        return array_intersect(
6095
-            $this->valid_operators(),
6096
-            $this->_like_style_operators
6097
-        );
6098
-    }
6099
-
6100
-
6101
-    /**
6102
-     * Gets the "in"-style operators
6103
-     *
6104
-     * @return array keys are accepted strings, values are the SQL they are converted to
6105
-     */
6106
-    public function valid_in_style_operators()
6107
-    {
6108
-        return array_intersect(
6109
-            $this->valid_operators(),
6110
-            $this->_in_style_operators
6111
-        );
6112
-    }
6113
-
6114
-
6115
-    /**
6116
-     * Gets the "null"-style operators (accept no arguments)
6117
-     *
6118
-     * @return array keys are accepted strings, values are the SQL they are converted to
6119
-     */
6120
-    public function valid_null_style_operators()
6121
-    {
6122
-        return array_intersect(
6123
-            $this->valid_operators(),
6124
-            $this->_null_style_operators
6125
-        );
6126
-    }
6127
-
6128
-
6129
-    /**
6130
-     * Gets an array where keys are the primary keys and values are their 'names'
6131
-     * (as determined by the model object's name() function, which is often overridden)
6132
-     *
6133
-     * @param array $query_params like get_all's
6134
-     * @return string[]
6135
-     * @throws EE_Error
6136
-     * @throws ReflectionException
6137
-     */
6138
-    public function get_all_names($query_params = [])
6139
-    {
6140
-        $objs  = $this->get_all($query_params);
6141
-        $names = [];
6142
-        foreach ($objs as $obj) {
6143
-            $names[ $obj->ID() ] = $obj->name();
6144
-        }
6145
-        return $names;
6146
-    }
6147
-
6148
-
6149
-    /**
6150
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6151
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6152
-     * this is duplicated effort and reduces efficiency) you would be better to use
6153
-     * array_keys() on $model_objects.
6154
-     *
6155
-     * @param EE_Base_Class[] $model_objects
6156
-     * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6157
-     *                                               in the returned array
6158
-     * @return array
6159
-     * @throws EE_Error
6160
-     */
6161
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6162
-    {
6163
-        if (! $this->has_primary_key_field()) {
6164
-            if (WP_DEBUG) {
6165
-                EE_Error::add_error(
6166
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6167
-                    __FILE__,
6168
-                    __FUNCTION__,
6169
-                    __LINE__
6170
-                );
6171
-            }
6172
-        }
6173
-        $IDs = [];
6174
-        foreach ($model_objects as $model_object) {
6175
-            $id = $model_object->ID();
6176
-            if (! $id) {
6177
-                if ($filter_out_empty_ids) {
6178
-                    continue;
6179
-                }
6180
-                if (WP_DEBUG) {
6181
-                    EE_Error::add_error(
6182
-                        esc_html__(
6183
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6184
-                            'event_espresso'
6185
-                        ),
6186
-                        __FILE__,
6187
-                        __FUNCTION__,
6188
-                        __LINE__
6189
-                    );
6190
-                }
6191
-            }
6192
-            $IDs[] = $id;
6193
-        }
6194
-        return $IDs;
6195
-    }
6196
-
6197
-
6198
-    /**
6199
-     * Returns the string used in capabilities relating to this model. If there
6200
-     * are no capabilities that relate to this model returns false
6201
-     *
6202
-     * @return string|false
6203
-     */
6204
-    public function cap_slug()
6205
-    {
6206
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6207
-    }
6208
-
6209
-
6210
-    /**
6211
-     * Returns the capability-restrictions array (@param string $context
6212
-     *
6213
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6214
-     * @throws EE_Error
6215
-     * @see EEM_Base::_cap_restrictions).
6216
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6217
-     *      only returns the cap restrictions array in that context (ie, the array
6218
-     *      at that key)
6219
-     *
6220
-     */
6221
-    public function cap_restrictions($context = EEM_Base::caps_read)
6222
-    {
6223
-        EEM_Base::verify_is_valid_cap_context($context);
6224
-        // check if we ought to run the restriction generator first
6225
-        if (
6226
-            isset($this->_cap_restriction_generators[ $context ])
6227
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6228
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6229
-        ) {
6230
-            $this->_cap_restrictions[ $context ] = array_merge(
6231
-                $this->_cap_restrictions[ $context ],
6232
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6233
-            );
6234
-        }
6235
-        // and make sure we've finalized the construction of each restriction
6236
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6237
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6238
-                $where_conditions_obj->_finalize_construct($this);
6239
-            }
6240
-        }
6241
-        return $this->_cap_restrictions[ $context ];
6242
-    }
6243
-
6244
-
6245
-    /**
6246
-     * Indicating whether or not this model thinks its a wp core model
6247
-     *
6248
-     * @return boolean
6249
-     */
6250
-    public function is_wp_core_model()
6251
-    {
6252
-        return $this->_wp_core_model;
6253
-    }
6254
-
6255
-
6256
-    /**
6257
-     * Gets all the caps that are missing which impose a restriction on
6258
-     * queries made in this context
6259
-     *
6260
-     * @param string $context one of EEM_Base::caps_ constants
6261
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6262
-     * @throws EE_Error
6263
-     */
6264
-    public function caps_missing($context = EEM_Base::caps_read)
6265
-    {
6266
-        $missing_caps     = [];
6267
-        $cap_restrictions = $this->cap_restrictions($context);
6268
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6269
-            if (
6270
-            ! EE_Capabilities::instance()
6271
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6272
-            ) {
6273
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6274
-            }
6275
-        }
6276
-        return $missing_caps;
6277
-    }
6278
-
6279
-
6280
-    /**
6281
-     * Gets the mapping from capability contexts to action strings used in capability names
6282
-     *
6283
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6284
-     * one of 'read', 'edit', or 'delete'
6285
-     */
6286
-    public function cap_contexts_to_cap_action_map()
6287
-    {
6288
-        return apply_filters(
6289
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6290
-            $this->_cap_contexts_to_cap_action_map,
6291
-            $this
6292
-        );
6293
-    }
6294
-
6295
-
6296
-    /**
6297
-     * Gets the action string for the specified capability context
6298
-     *
6299
-     * @param string $context
6300
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6301
-     * @throws EE_Error
6302
-     */
6303
-    public function cap_action_for_context($context)
6304
-    {
6305
-        $mapping = $this->cap_contexts_to_cap_action_map();
6306
-        if (isset($mapping[ $context ])) {
6307
-            return $mapping[ $context ];
6308
-        }
6309
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6310
-            return $action;
6311
-        }
6312
-        throw new EE_Error(
6313
-            sprintf(
6314
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6315
-                $context,
6316
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6317
-            )
6318
-        );
6319
-    }
6320
-
6321
-
6322
-    /**
6323
-     * Returns all the capability contexts which are valid when querying models
6324
-     *
6325
-     * @return array
6326
-     */
6327
-    public static function valid_cap_contexts()
6328
-    {
6329
-        return apply_filters(
6330
-            'FHEE__EEM_Base__valid_cap_contexts',
6331
-            [
6332
-                self::caps_read,
6333
-                self::caps_read_admin,
6334
-                self::caps_edit,
6335
-                self::caps_delete,
6336
-            ]
6337
-        );
6338
-    }
6339
-
6340
-
6341
-    /**
6342
-     * Returns all valid options for 'default_where_conditions'
6343
-     *
6344
-     * @return array
6345
-     */
6346
-    public static function valid_default_where_conditions()
6347
-    {
6348
-        return [
6349
-            EEM_Base::default_where_conditions_all,
6350
-            EEM_Base::default_where_conditions_this_only,
6351
-            EEM_Base::default_where_conditions_others_only,
6352
-            EEM_Base::default_where_conditions_minimum_all,
6353
-            EEM_Base::default_where_conditions_minimum_others,
6354
-            EEM_Base::default_where_conditions_none,
6355
-        ];
6356
-    }
6357
-
6358
-    // public static function default_where_conditions_full
6359
-
6360
-
6361
-    /**
6362
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6363
-     *
6364
-     * @param string $context
6365
-     * @return bool
6366
-     * @throws EE_Error
6367
-     */
6368
-    public static function verify_is_valid_cap_context($context)
6369
-    {
6370
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6371
-        if (in_array($context, $valid_cap_contexts)) {
6372
-            return true;
6373
-        }
6374
-        throw new EE_Error(
6375
-            sprintf(
6376
-                esc_html__(
6377
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6378
-                    'event_espresso'
6379
-                ),
6380
-                $context,
6381
-                'EEM_Base',
6382
-                implode(',', $valid_cap_contexts)
6383
-            )
6384
-        );
6385
-    }
6386
-
6387
-
6388
-    /**
6389
-     * Clears all the models field caches. This is only useful when a sub-class
6390
-     * might have added a field or something and these caches might be invalidated
6391
-     */
6392
-    protected function _invalidate_field_caches()
6393
-    {
6394
-        $this->_cache_foreign_key_to_fields = [];
6395
-        $this->_cached_fields               = null;
6396
-        $this->_cached_fields_non_db_only   = null;
6397
-    }
6398
-
6399
-
6400
-    /**
6401
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6402
-     * (eg "and", "or", "not").
6403
-     *
6404
-     * @return array
6405
-     */
6406
-    public function logic_query_param_keys()
6407
-    {
6408
-        return $this->_logic_query_param_keys;
6409
-    }
6410
-
6411
-
6412
-    /**
6413
-     * Determines whether or not the where query param array key is for a logic query param.
6414
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6415
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6416
-     *
6417
-     * @param $query_param_key
6418
-     * @return bool
6419
-     */
6420
-    public function is_logic_query_param_key($query_param_key)
6421
-    {
6422
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6423
-            if (
6424
-                $query_param_key === $logic_query_param_key
6425
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6426
-            ) {
6427
-                return true;
6428
-            }
6429
-        }
6430
-        return false;
6431
-    }
6432
-
6433
-
6434
-    /**
6435
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6436
-     *
6437
-     * @return boolean
6438
-     * @since 4.9.74.p
6439
-     */
6440
-    public function hasPassword()
6441
-    {
6442
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6443
-        if ($this->has_password_field === null) {
6444
-            $password_field           = $this->getPasswordField();
6445
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6446
-        }
6447
-        return $this->has_password_field;
6448
-    }
6449
-
6450
-
6451
-    /**
6452
-     * Returns the password field on this model, if there is one
6453
-     *
6454
-     * @return EE_Password_Field|null
6455
-     * @since 4.9.74.p
6456
-     */
6457
-    public function getPasswordField()
6458
-    {
6459
-        // if we definitely already know there is a password field or not (because has_password_field is true or false)
6460
-        // there's no need to search for it. If we don't know yet, then find out
6461
-        if ($this->has_password_field === null && $this->password_field === null) {
6462
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6463
-        }
6464
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6465
-        return $this->password_field;
6466
-    }
6467
-
6468
-
6469
-    /**
6470
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6471
-     *
6472
-     * @return EE_Model_Field_Base[]
6473
-     * @throws EE_Error
6474
-     * @since 4.9.74.p
6475
-     */
6476
-    public function getPasswordProtectedFields()
6477
-    {
6478
-        $password_field = $this->getPasswordField();
6479
-        $fields         = [];
6480
-        if ($password_field instanceof EE_Password_Field) {
6481
-            $field_names = $password_field->protectedFields();
6482
-            foreach ($field_names as $field_name) {
6483
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6484
-            }
6485
-        }
6486
-        return $fields;
6487
-    }
6488
-
6489
-
6490
-    /**
6491
-     * Checks if the current user can perform the requested action on this model
6492
-     *
6493
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6494
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6495
-     * @return bool
6496
-     * @throws EE_Error
6497
-     * @throws InvalidArgumentException
6498
-     * @throws InvalidDataTypeException
6499
-     * @throws InvalidInterfaceException
6500
-     * @throws ReflectionException
6501
-     * @throws UnexpectedEntityException
6502
-     * @since 4.9.74.p
6503
-     */
6504
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6505
-    {
6506
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6507
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6508
-        }
6509
-        if (! is_array($model_obj_or_fields_n_values)) {
6510
-            throw new UnexpectedEntityException(
6511
-                $model_obj_or_fields_n_values,
6512
-                'EE_Base_Class',
6513
-                sprintf(
6514
-                    esc_html__(
6515
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6516
-                        'event_espresso'
6517
-                    ),
6518
-                    __FUNCTION__
6519
-                )
6520
-            );
6521
-        }
6522
-        return $this->exists(
6523
-            $this->alter_query_params_to_restrict_by_ID(
6524
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6525
-                [
6526
-                    'default_where_conditions' => 'none',
6527
-                    'caps'                     => $cap_to_check,
6528
-                ]
6529
-            )
6530
-        );
6531
-    }
6532
-
6533
-
6534
-    /**
6535
-     * Returns the query param where conditions key to the password affecting this model.
6536
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6537
-     *
6538
-     * @return null|string
6539
-     * @throws EE_Error
6540
-     * @throws InvalidArgumentException
6541
-     * @throws InvalidDataTypeException
6542
-     * @throws InvalidInterfaceException
6543
-     * @throws ModelConfigurationException
6544
-     * @throws ReflectionException
6545
-     * @since 4.9.74.p
6546
-     */
6547
-    public function modelChainAndPassword()
6548
-    {
6549
-        if ($this->model_chain_to_password === null) {
6550
-            throw new ModelConfigurationException(
6551
-                $this,
6552
-                esc_html_x(
6553
-                // @codingStandardsIgnoreStart
6554
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6555
-                    // @codingStandardsIgnoreEnd
6556
-                    '1: model name',
6557
-                    'event_espresso'
6558
-                )
6559
-            );
6560
-        }
6561
-        if ($this->model_chain_to_password === '') {
6562
-            $model_with_password = $this;
6563
-        } else {
6564
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6565
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6566
-            } else {
6567
-                $last_model_in_chain = $this->model_chain_to_password;
6568
-            }
6569
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6570
-        }
6571
-
6572
-        $password_field = $model_with_password->getPasswordField();
6573
-        if ($password_field instanceof EE_Password_Field) {
6574
-            $password_field_name = $password_field->get_name();
6575
-        } else {
6576
-            throw new ModelConfigurationException(
6577
-                $this,
6578
-                sprintf(
6579
-                    esc_html_x(
6580
-                        '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"',
6581
-                        '1: model name, 2: special string',
6582
-                        'event_espresso'
6583
-                    ),
6584
-                    $model_with_password->get_this_model_name(),
6585
-                    $this->model_chain_to_password
6586
-                )
6587
-            );
6588
-        }
6589
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6590
-    }
6591
-
6592
-
6593
-    /**
6594
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6595
-     * or if this model itself has a password affecting access to some of its other fields.
6596
-     *
6597
-     * @return boolean
6598
-     * @since 4.9.74.p
6599
-     */
6600
-    public function restrictedByRelatedModelPassword()
6601
-    {
6602
-        return $this->model_chain_to_password !== null;
6603
-    }
3873
+		}
3874
+		return $null_friendly_where_conditions;
3875
+	}
3876
+
3877
+
3878
+	/**
3879
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3880
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3881
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3882
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3883
+	 *
3884
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3885
+	 * @return array
3886
+	 * @throws EE_Error
3887
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3888
+	 */
3889
+	private function _get_default_where_conditions($model_relation_path = '')
3890
+	{
3891
+		if ($this->_ignore_where_strategy) {
3892
+			return [];
3893
+		}
3894
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3895
+	}
3896
+
3897
+
3898
+	/**
3899
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3900
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3901
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3902
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3903
+	 * Similar to _get_default_where_conditions
3904
+	 *
3905
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3906
+	 * @return array
3907
+	 * @throws EE_Error
3908
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3909
+	 */
3910
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3911
+	{
3912
+		if ($this->_ignore_where_strategy) {
3913
+			return [];
3914
+		}
3915
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3916
+	}
3917
+
3918
+
3919
+	/**
3920
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3921
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3922
+	 *
3923
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3924
+	 * @return string
3925
+	 * @throws EE_Error
3926
+	 */
3927
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3928
+	{
3929
+		$selects = $this->_get_columns_to_select_for_this_model();
3930
+		foreach (
3931
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3932
+		) {
3933
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3934
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3935
+			foreach ($other_model_selects as $value) {
3936
+				$selects[] = $value;
3937
+			}
3938
+		}
3939
+		return implode(", ", $selects);
3940
+	}
3941
+
3942
+
3943
+	/**
3944
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3945
+	 * So that's going to be the columns for all the fields on the model
3946
+	 *
3947
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3948
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3949
+	 */
3950
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3951
+	{
3952
+		$fields                                       = $this->field_settings();
3953
+		$selects                                      = [];
3954
+		$table_alias_with_model_relation_chain_prefix =
3955
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3956
+				$model_relation_chain,
3957
+				$this->get_this_model_name()
3958
+			);
3959
+		foreach ($fields as $field_obj) {
3960
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3961
+						 . $field_obj->get_table_alias()
3962
+						 . "."
3963
+						 . $field_obj->get_table_column()
3964
+						 . " AS '"
3965
+						 . $table_alias_with_model_relation_chain_prefix
3966
+						 . $field_obj->get_table_alias()
3967
+						 . "."
3968
+						 . $field_obj->get_table_column()
3969
+						 . "'";
3970
+		}
3971
+		// make sure we are also getting the PKs of each table
3972
+		$tables = $this->get_tables();
3973
+		if (count($tables) > 1) {
3974
+			foreach ($tables as $table_obj) {
3975
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3976
+									   . $table_obj->get_fully_qualified_pk_column();
3977
+				if (! in_array($qualified_pk_column, $selects)) {
3978
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3979
+				}
3980
+			}
3981
+		}
3982
+		return $selects;
3983
+	}
3984
+
3985
+
3986
+	/**
3987
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3988
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3989
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3990
+	 * SQL for joining, and the data types
3991
+	 *
3992
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3993
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3994
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3995
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3996
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3997
+	 *                                                          or 'Registration's
3998
+	 * @param string|null                 $original_query_param what it originally was (eg
3999
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4000
+	 *                                                          matches $query_param
4001
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4002
+	 * @throws EE_Error
4003
+	 */
4004
+	private function _extract_related_model_info_from_query_param(
4005
+		$query_param,
4006
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4007
+		$query_param_type,
4008
+		$original_query_param = null
4009
+	) {
4010
+		if ($original_query_param === null) {
4011
+			$original_query_param = $query_param;
4012
+		}
4013
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4014
+		// whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4015
+		$allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4016
+		$allow_fields             = in_array(
4017
+			$query_param_type,
4018
+			['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4019
+			true
4020
+		);
4021
+		// check to see if we have a field on this model
4022
+		$this_model_fields = $this->field_settings(true);
4023
+		if (array_key_exists($query_param, $this_model_fields)) {
4024
+			if ($allow_fields) {
4025
+				return;
4026
+			}
4027
+			throw new EE_Error(
4028
+				sprintf(
4029
+					esc_html__(
4030
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4031
+						"event_espresso"
4032
+					),
4033
+					$query_param,
4034
+					get_class($this),
4035
+					$query_param_type,
4036
+					$original_query_param
4037
+				)
4038
+			);
4039
+		}
4040
+		// check if this is a special logic query param
4041
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4042
+			if ($allow_logic_query_params) {
4043
+				return;
4044
+			}
4045
+			throw new EE_Error(
4046
+				sprintf(
4047
+					esc_html__(
4048
+						'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',
4049
+						'event_espresso'
4050
+					),
4051
+					implode('", "', $this->_logic_query_param_keys),
4052
+					$query_param,
4053
+					get_class($this),
4054
+					'<br />',
4055
+					"\t"
4056
+					. ' $passed_in_query_info = <pre>'
4057
+					. print_r($passed_in_query_info, true)
4058
+					. '</pre>'
4059
+					. "\n\t"
4060
+					. ' $query_param_type = '
4061
+					. $query_param_type
4062
+					. "\n\t"
4063
+					. ' $original_query_param = '
4064
+					. $original_query_param
4065
+				)
4066
+			);
4067
+		}
4068
+		// check if it's a custom selection
4069
+		if (
4070
+			$this->_custom_selections instanceof CustomSelects
4071
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4072
+		) {
4073
+			return;
4074
+		}
4075
+		// check if has a model name at the beginning
4076
+		// and
4077
+		// check if it's a field on a related model
4078
+		if (
4079
+		$this->extractJoinModelFromQueryParams(
4080
+			$passed_in_query_info,
4081
+			$query_param,
4082
+			$original_query_param,
4083
+			$query_param_type
4084
+		)
4085
+		) {
4086
+			return;
4087
+		}
4088
+
4089
+		// ok so $query_param didn't start with a model name
4090
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4091
+		// it's wack, that's what it is
4092
+		throw new EE_Error(
4093
+			sprintf(
4094
+				esc_html__(
4095
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4096
+					"event_espresso"
4097
+				),
4098
+				$query_param,
4099
+				get_class($this),
4100
+				$query_param_type,
4101
+				$original_query_param
4102
+			)
4103
+		);
4104
+	}
4105
+
4106
+
4107
+	/**
4108
+	 * Extracts any possible join model information from the provided possible_join_string.
4109
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4110
+	 * join
4111
+	 * parts that should be added to the query.
4112
+	 *
4113
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4115
+	 * @param null|string                 $original_query_param
4116
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4117
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4118
+	 *                                                           etc.)
4119
+	 * @return bool  returns true if a join was added and false if not.
4120
+	 * @throws EE_Error
4121
+	 */
4122
+	private function extractJoinModelFromQueryParams(
4123
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4124
+		$possible_join_string,
4125
+		$original_query_param,
4126
+		$query_parameter_type
4127
+	) {
4128
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4129
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4130
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4131
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4132
+				if ($possible_join_string === '') {
4133
+					// nothing left to $query_param
4134
+					// we should actually end in a field name, not a model like this!
4135
+					throw new EE_Error(
4136
+						sprintf(
4137
+							esc_html__(
4138
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4139
+								"event_espresso"
4140
+							),
4141
+							$possible_join_string,
4142
+							$query_parameter_type,
4143
+							get_class($this),
4144
+							$valid_related_model_name
4145
+						)
4146
+					);
4147
+				}
4148
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4149
+				$related_model_obj->_extract_related_model_info_from_query_param(
4150
+					$possible_join_string,
4151
+					$query_info_carrier,
4152
+					$query_parameter_type,
4153
+					$original_query_param
4154
+				);
4155
+				return true;
4156
+			}
4157
+			if ($possible_join_string === $valid_related_model_name) {
4158
+				$this->_add_join_to_model(
4159
+					$valid_related_model_name,
4160
+					$query_info_carrier,
4161
+					$original_query_param
4162
+				);
4163
+				return true;
4164
+			}
4165
+		}
4166
+		return false;
4167
+	}
4168
+
4169
+
4170
+	/**
4171
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4172
+	 *
4173
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4174
+	 * @throws EE_Error
4175
+	 */
4176
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4177
+	{
4178
+		if (
4179
+			$this->_custom_selections instanceof CustomSelects
4180
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4181
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4182
+			)
4183
+		) {
4184
+			$original_selects = $this->_custom_selections->originalSelects();
4185
+			foreach ($original_selects as $select_configuration) {
4186
+				$this->extractJoinModelFromQueryParams(
4187
+					$query_info_carrier,
4188
+					$select_configuration[0],
4189
+					$select_configuration[0],
4190
+					'custom_selects'
4191
+				);
4192
+			}
4193
+		}
4194
+	}
4195
+
4196
+
4197
+	/**
4198
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4199
+	 * and store it on $passed_in_query_info
4200
+	 *
4201
+	 * @param string                      $model_name
4202
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4203
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4204
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4205
+	 *                                                          and are adding a join to 'Payment' with the original
4206
+	 *                                                          query param key
4207
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4208
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4209
+	 *                                                          Payment wants to add default query params so that it
4210
+	 *                                                          will know what models to prepend onto its default query
4211
+	 *                                                          params or in case it wants to rename tables (in case
4212
+	 *                                                          there are multiple joins to the same table)
4213
+	 * @return void
4214
+	 * @throws EE_Error
4215
+	 */
4216
+	private function _add_join_to_model(
4217
+		$model_name,
4218
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4219
+		$original_query_param
4220
+	) {
4221
+		$relation_obj         = $this->related_settings_for($model_name);
4222
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4223
+		// check if the relation is HABTM, because then we're essentially doing two joins
4224
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4225
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4226
+			$join_model_obj = $relation_obj->get_join_model();
4227
+			// replace the model specified with the join model for this relation chain, whi
4228
+			$relation_chain_to_join_model =
4229
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4230
+					$model_name,
4231
+					$join_model_obj->get_this_model_name(),
4232
+					$model_relation_chain
4233
+				);
4234
+			$passed_in_query_info->merge(
4235
+				new EE_Model_Query_Info_Carrier(
4236
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4237
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4238
+				)
4239
+			);
4240
+		}
4241
+		// now just join to the other table pointed to by the relation object, and add its data types
4242
+		$passed_in_query_info->merge(
4243
+			new EE_Model_Query_Info_Carrier(
4244
+				[$model_relation_chain => $model_name],
4245
+				$relation_obj->get_join_statement($model_relation_chain)
4246
+			)
4247
+		);
4248
+	}
4249
+
4250
+
4251
+	/**
4252
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4253
+	 *
4254
+	 * @param array $where_params
4255
+	 * @return string of SQL
4256
+	 * @throws EE_Error
4257
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4258
+	 */
4259
+	private function _construct_where_clause($where_params)
4260
+	{
4261
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4262
+		if ($SQL) {
4263
+			return " WHERE " . $SQL;
4264
+		}
4265
+		return '';
4266
+	}
4267
+
4268
+
4269
+	/**
4270
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4271
+	 * and should be passed HAVING parameters, not WHERE parameters
4272
+	 *
4273
+	 * @param array $having_params
4274
+	 * @return string
4275
+	 * @throws EE_Error
4276
+	 */
4277
+	private function _construct_having_clause($having_params)
4278
+	{
4279
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4280
+		if ($SQL) {
4281
+			return " HAVING " . $SQL;
4282
+		}
4283
+		return '';
4284
+	}
4285
+
4286
+
4287
+	/**
4288
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4289
+	 * Event_Meta.meta_value = 'foo'))"
4290
+	 *
4291
+	 * @param array  $where_params
4292
+	 * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4293
+	 * @return string of SQL
4294
+	 * @throws EE_Error
4295
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4296
+	 */
4297
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4298
+	{
4299
+		$where_clauses = [];
4300
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4301
+			$query_param =
4302
+				$this->_remove_stars_and_anything_after_from_condition_query_param_key(
4303
+					$query_param
4304
+				);// str_replace("*",'',$query_param);
4305
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4306
+				switch ($query_param) {
4307
+					case 'not':
4308
+					case 'NOT':
4309
+						$where_clauses[] = "! ("
4310
+										   . $this->_construct_condition_clause_recursive(
4311
+								$op_and_value_or_sub_condition,
4312
+								$glue
4313
+							)
4314
+										   . ")";
4315
+						break;
4316
+					case 'and':
4317
+					case 'AND':
4318
+						$where_clauses[] = " ("
4319
+										   . $this->_construct_condition_clause_recursive(
4320
+								$op_and_value_or_sub_condition,
4321
+								' AND '
4322
+							)
4323
+										   . ")";
4324
+						break;
4325
+					case 'or':
4326
+					case 'OR':
4327
+						$where_clauses[] = " ("
4328
+										   . $this->_construct_condition_clause_recursive(
4329
+								$op_and_value_or_sub_condition,
4330
+								' OR '
4331
+							)
4332
+										   . ")";
4333
+						break;
4334
+				}
4335
+			} else {
4336
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4337
+				// if it's not a normal field, maybe it's a custom selection?
4338
+				if (! $field_obj) {
4339
+					if ($this->_custom_selections instanceof CustomSelects) {
4340
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4341
+					} else {
4342
+						throw new EE_Error(
4343
+							sprintf(
4344
+								esc_html__(
4345
+									"%s is neither a valid model field name, nor a custom selection",
4346
+									"event_espresso"
4347
+								),
4348
+								$query_param
4349
+							)
4350
+						);
4351
+					}
4352
+				}
4353
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4354
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4355
+			}
4356
+		}
4357
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4358
+	}
4359
+
4360
+
4361
+	/**
4362
+	 * Takes the input parameter and extract the table name (alias) and column name
4363
+	 *
4364
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4365
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4366
+	 * @throws EE_Error
4367
+	 */
4368
+	private function _deduce_column_name_from_query_param($query_param)
4369
+	{
4370
+		$field = $this->_deduce_field_from_query_param($query_param);
4371
+		if ($field) {
4372
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4373
+				$field->get_model_name(),
4374
+				$query_param
4375
+			);
4376
+			return $table_alias_prefix . $field->get_qualified_column();
4377
+		}
4378
+		if (
4379
+			$this->_custom_selections instanceof CustomSelects
4380
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4381
+		) {
4382
+			// maybe it's custom selection item?
4383
+			// if so, just use it as the "column name"
4384
+			return $query_param;
4385
+		}
4386
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4387
+			? implode(',', $this->_custom_selections->columnAliases())
4388
+			: '';
4389
+		throw new EE_Error(
4390
+			sprintf(
4391
+				esc_html__(
4392
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4393
+					"event_espresso"
4394
+				),
4395
+				$query_param,
4396
+				$custom_select_aliases
4397
+			)
4398
+		);
4399
+	}
4400
+
4401
+
4402
+	/**
4403
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4404
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4405
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4406
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4407
+	 *
4408
+	 * @param string $condition_query_param_key
4409
+	 * @return string
4410
+	 */
4411
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4412
+	{
4413
+		$pos_of_star = strpos($condition_query_param_key, '*');
4414
+		if ($pos_of_star === false) {
4415
+			return $condition_query_param_key;
4416
+		}
4417
+		return substr($condition_query_param_key, 0, $pos_of_star);
4418
+	}
4419
+
4420
+
4421
+	/**
4422
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4423
+	 *
4424
+	 * @param mixed      array | string    $op_and_value
4425
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4426
+	 * @return string
4427
+	 * @throws EE_Error
4428
+	 */
4429
+	private function _construct_op_and_value($op_and_value, $field_obj)
4430
+	{
4431
+		if (is_array($op_and_value)) {
4432
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4433
+			if (! $operator) {
4434
+				$php_array_like_string = [];
4435
+				foreach ($op_and_value as $key => $value) {
4436
+					$php_array_like_string[] = "$key=>$value";
4437
+				}
4438
+				throw new EE_Error(
4439
+					sprintf(
4440
+						esc_html__(
4441
+							"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))",
4442
+							"event_espresso"
4443
+						),
4444
+						implode(",", $php_array_like_string)
4445
+					)
4446
+				);
4447
+			}
4448
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4449
+		} else {
4450
+			$operator = '=';
4451
+			$value    = $op_and_value;
4452
+		}
4453
+		// check to see if the value is actually another field
4454
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4455
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4456
+		}
4457
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4458
+			// in this case, the value should be an array, or at least a comma-separated list
4459
+			// it will need to handle a little differently
4460
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4461
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4462
+			return $operator . SP . $cleaned_value;
4463
+		}
4464
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4465
+			// the value should be an array with count of two.
4466
+			if (count($value) !== 2) {
4467
+				throw new EE_Error(
4468
+					sprintf(
4469
+						esc_html__(
4470
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4471
+							'event_espresso'
4472
+						),
4473
+						"BETWEEN"
4474
+					)
4475
+				);
4476
+			}
4477
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4478
+			return $operator . SP . $cleaned_value;
4479
+		}
4480
+		if (in_array($operator, $this->valid_null_style_operators())) {
4481
+			if ($value !== null) {
4482
+				throw new EE_Error(
4483
+					sprintf(
4484
+						esc_html__(
4485
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4486
+							"event_espresso"
4487
+						),
4488
+						$value,
4489
+						$operator
4490
+					)
4491
+				);
4492
+			}
4493
+			return $operator;
4494
+		}
4495
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4496
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4497
+			// remove other junk. So just treat it as a string.
4498
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4499
+		}
4500
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4502
+		}
4503
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4504
+			throw new EE_Error(
4505
+				sprintf(
4506
+					esc_html__(
4507
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4508
+						'event_espresso'
4509
+					),
4510
+					$operator,
4511
+					$operator
4512
+				)
4513
+			);
4514
+		}
4515
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4516
+			throw new EE_Error(
4517
+				sprintf(
4518
+					esc_html__(
4519
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4520
+						'event_espresso'
4521
+					),
4522
+					$operator,
4523
+					$operator
4524
+				)
4525
+			);
4526
+		}
4527
+		throw new EE_Error(
4528
+			sprintf(
4529
+				esc_html__(
4530
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4531
+					"event_espresso"
4532
+				),
4533
+				http_build_query($op_and_value)
4534
+			)
4535
+		);
4536
+	}
4537
+
4538
+
4539
+	/**
4540
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4541
+	 *
4542
+	 * @param array                      $values
4543
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4544
+	 *                                              '%s'
4545
+	 * @return string
4546
+	 * @throws EE_Error
4547
+	 */
4548
+	public function _construct_between_value($values, $field_obj)
4549
+	{
4550
+		$cleaned_values = [];
4551
+		foreach ($values as $value) {
4552
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4553
+		}
4554
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4555
+	}
4556
+
4557
+
4558
+	/**
4559
+	 * Takes an array or a comma-separated list of $values and cleans them
4560
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4561
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4562
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4563
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4564
+	 *
4565
+	 * @param mixed                      $values    array or comma-separated string
4566
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4567
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4568
+	 * @throws EE_Error
4569
+	 */
4570
+	public function _construct_in_value($values, $field_obj)
4571
+	{
4572
+		// check if the value is a CSV list
4573
+		if (is_string($values)) {
4574
+			// in which case, turn it into an array
4575
+			$values = explode(",", $values);
4576
+		}
4577
+		$cleaned_values = [];
4578
+		foreach ($values as $value) {
4579
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4580
+		}
4581
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4582
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4583
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4584
+		if (empty($cleaned_values)) {
4585
+			$all_fields       = $this->field_settings();
4586
+			$a_field          = array_shift($all_fields);
4587
+			$main_table       = $this->_get_main_table();
4588
+			$cleaned_values[] = "SELECT "
4589
+								. $a_field->get_table_column()
4590
+								. " FROM "
4591
+								. $main_table->get_table_name()
4592
+								. " WHERE FALSE";
4593
+		}
4594
+		return "(" . implode(",", $cleaned_values) . ")";
4595
+	}
4596
+
4597
+
4598
+	/**
4599
+	 * @param mixed                      $value
4600
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4601
+	 * @return string
4602
+	 * @throws EE_Error
4603
+	 */
4604
+	private function _wpdb_prepare_using_field($value, $field_obj)
4605
+	{
4606
+		global $wpdb;
4607
+		if ($field_obj instanceof EE_Model_Field_Base) {
4608
+			return $wpdb->prepare(
4609
+				$field_obj->get_wpdb_data_type(),
4610
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4611
+			);
4612
+		} //$field_obj should really just be a data type
4613
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4614
+			throw new EE_Error(
4615
+				sprintf(
4616
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4617
+					$field_obj,
4618
+					implode(",", $this->_valid_wpdb_data_types)
4619
+				)
4620
+			);
4621
+		}
4622
+		return $wpdb->prepare($field_obj, $value);
4623
+	}
4624
+
4625
+
4626
+	/**
4627
+	 * Takes the input parameter and finds the model field that it indicates.
4628
+	 *
4629
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4630
+	 * @return EE_Model_Field_Base
4631
+	 * @throws EE_Error
4632
+	 */
4633
+	protected function _deduce_field_from_query_param($query_param_name)
4634
+	{
4635
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4636
+		// which will help us find the database table and column
4637
+		$query_param_parts = explode(".", $query_param_name);
4638
+		if (empty($query_param_parts)) {
4639
+			throw new EE_Error(
4640
+				sprintf(
4641
+					esc_html__(
4642
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4643
+						'event_espresso'
4644
+					),
4645
+					$query_param_name
4646
+				)
4647
+			);
4648
+		}
4649
+		$number_of_parts       = count($query_param_parts);
4650
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4651
+		$field_name = $last_query_param_part;
4652
+		$model_obj  = $number_of_parts === 1
4653
+			? $this
4654
+			// $number_of_parts >= 2, the last part is the column name, and there are only 2parts. therefore...
4655
+			: $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4656
+		try {
4657
+			return $model_obj->field_settings_for($field_name);
4658
+		} catch (EE_Error $e) {
4659
+			return null;
4660
+		}
4661
+	}
4662
+
4663
+
4664
+	/**
4665
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4666
+	 * alias and column which corresponds to it
4667
+	 *
4668
+	 * @param string $field_name
4669
+	 * @return string
4670
+	 * @throws EE_Error
4671
+	 */
4672
+	public function _get_qualified_column_for_field($field_name)
4673
+	{
4674
+		$all_fields = $this->field_settings();
4675
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4676
+		if ($field) {
4677
+			return $field->get_qualified_column();
4678
+		}
4679
+		throw new EE_Error(
4680
+			sprintf(
4681
+				esc_html__(
4682
+					"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.",
4683
+					'event_espresso'
4684
+				),
4685
+				$field_name,
4686
+				get_class($this)
4687
+			)
4688
+		);
4689
+	}
4690
+
4691
+
4692
+	/**
4693
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4694
+	 * Example usage:
4695
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4696
+	 *      array(),
4697
+	 *      ARRAY_A,
4698
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4699
+	 *  );
4700
+	 * is equivalent to
4701
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4702
+	 * and
4703
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4704
+	 *      array(
4705
+	 *          array(
4706
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4707
+	 *          ),
4708
+	 *          ARRAY_A,
4709
+	 *          implode(
4710
+	 *              ', ',
4711
+	 *              array_merge(
4712
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4713
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4714
+	 *              )
4715
+	 *          )
4716
+	 *      )
4717
+	 *  );
4718
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4719
+	 *
4720
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4721
+	 *                                            and the one whose fields you are selecting for example: when querying
4722
+	 *                                            tickets model and selecting fields from the tickets model you would
4723
+	 *                                            leave this parameter empty, because no models are needed to join
4724
+	 *                                            between the queried model and the selected one. Likewise when
4725
+	 *                                            querying the datetime model and selecting fields from the tickets
4726
+	 *                                            model, it would also be left empty, because there is a direct
4727
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4728
+	 *                                            them together. However, when querying from the event model and
4729
+	 *                                            selecting fields from the ticket model, you should provide the string
4730
+	 *                                            'Datetime', indicating that the event model must first join to the
4731
+	 *                                            datetime model in order to find its relation to ticket model.
4732
+	 *                                            Also, when querying from the venue model and selecting fields from
4733
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4734
+	 *                                            indicating you need to join the venue model to the event model,
4735
+	 *                                            to the datetime model, in order to find its relation to the ticket
4736
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4737
+	 *                                            the models' tables qualified columns
4738
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4739
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4740
+	 *                                            qualified column names
4741
+	 * @return array|string
4742
+	 */
4743
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4744
+	{
4745
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4746
+		$qualified_columns = [];
4747
+		foreach ($this->field_settings() as $field) {
4748
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4749
+		}
4750
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4751
+	}
4752
+
4753
+
4754
+	/**
4755
+	 * constructs the select use on special limit joins
4756
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4757
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4758
+	 * (as that is typically where the limits would be set).
4759
+	 *
4760
+	 * @param string       $table_alias The table the select is being built for
4761
+	 * @param mixed|string $limit       The limit for this select
4762
+	 * @return string                The final select join element for the query.
4763
+	 * @throws EE_Error
4764
+	 */
4765
+	public function _construct_limit_join_select($table_alias, $limit)
4766
+	{
4767
+		$SQL = '';
4768
+		foreach ($this->_tables as $table_obj) {
4769
+			if ($table_obj instanceof EE_Primary_Table) {
4770
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4771
+					? $table_obj->get_select_join_limit($limit)
4772
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4773
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4774
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4775
+					? $table_obj->get_select_join_limit_join($limit)
4776
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4777
+			}
4778
+		}
4779
+		return $SQL;
4780
+	}
4781
+
4782
+
4783
+	/**
4784
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4785
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4786
+	 *
4787
+	 * @return string SQL
4788
+	 * @throws EE_Error
4789
+	 */
4790
+	public function _construct_internal_join()
4791
+	{
4792
+		$SQL = $this->_get_main_table()->get_table_sql();
4793
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4794
+		return $SQL;
4795
+	}
4796
+
4797
+
4798
+	/**
4799
+	 * Constructs the SQL for joining all the tables on this model.
4800
+	 * Normally $alias should be the primary table's alias, but in cases where
4801
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4802
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4803
+	 * alias, this will construct SQL like:
4804
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4805
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4806
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4807
+	 *
4808
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4809
+	 * @return string
4810
+	 * @throws EE_Error
4811
+	 */
4812
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4813
+	{
4814
+		$SQL               = '';
4815
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4816
+		foreach ($this->_tables as $table_obj) {
4817
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4818
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4819
+					// so we're joining to this table, meaning the table is already in
4820
+					// the FROM statement, BUT the primary table isn't. So we want
4821
+					// to add the inverse join sql
4822
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4823
+				} else {
4824
+					// just add a regular JOIN to this table from the primary table
4825
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4826
+				}
4827
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4828
+		}
4829
+		return $SQL;
4830
+	}
4831
+
4832
+
4833
+	/**
4834
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4835
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4836
+	 * their data type (eg, '%s', '%d', etc)
4837
+	 *
4838
+	 * @return array
4839
+	 */
4840
+	public function _get_data_types()
4841
+	{
4842
+		$data_types = [];
4843
+		foreach ($this->field_settings() as $field_obj) {
4844
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4845
+			/** @var $field_obj EE_Model_Field_Base */
4846
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4847
+		}
4848
+		return $data_types;
4849
+	}
4850
+
4851
+
4852
+	/**
4853
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4854
+	 *
4855
+	 * @param string $model_name
4856
+	 * @return EEM_Base
4857
+	 * @throws EE_Error
4858
+	 */
4859
+	public function get_related_model_obj($model_name)
4860
+	{
4861
+		$model_classname = "EEM_" . $model_name;
4862
+		if (! class_exists($model_classname)) {
4863
+			throw new EE_Error(
4864
+				sprintf(
4865
+					esc_html__(
4866
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4867
+						'event_espresso'
4868
+					),
4869
+					$model_name,
4870
+					$model_classname
4871
+				)
4872
+			);
4873
+		}
4874
+		return call_user_func($model_classname . "::instance");
4875
+	}
4876
+
4877
+
4878
+	/**
4879
+	 * Returns the array of EE_ModelRelations for this model.
4880
+	 *
4881
+	 * @return EE_Model_Relation_Base[]
4882
+	 */
4883
+	public function relation_settings()
4884
+	{
4885
+		return $this->_model_relations;
4886
+	}
4887
+
4888
+
4889
+	/**
4890
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4891
+	 * because without THOSE models, this model probably doesn't have much purpose.
4892
+	 * (Eg, without an event, datetimes have little purpose.)
4893
+	 *
4894
+	 * @return EE_Belongs_To_Relation[]
4895
+	 */
4896
+	public function belongs_to_relations()
4897
+	{
4898
+		$belongs_to_relations = [];
4899
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4900
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4901
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4902
+			}
4903
+		}
4904
+		return $belongs_to_relations;
4905
+	}
4906
+
4907
+
4908
+	/**
4909
+	 * Returns the specified EE_Model_Relation, or throws an exception
4910
+	 *
4911
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4912
+	 * @return EE_Model_Relation_Base
4913
+	 * @throws EE_Error
4914
+	 */
4915
+	public function related_settings_for($relation_name)
4916
+	{
4917
+		$relatedModels = $this->relation_settings();
4918
+		if (! array_key_exists($relation_name, $relatedModels)) {
4919
+			throw new EE_Error(
4920
+				sprintf(
4921
+					esc_html__(
4922
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4923
+						'event_espresso'
4924
+					),
4925
+					$relation_name,
4926
+					$this->_get_class_name(),
4927
+					implode(', ', array_keys($relatedModels))
4928
+				)
4929
+			);
4930
+		}
4931
+		return $relatedModels[ $relation_name ];
4932
+	}
4933
+
4934
+
4935
+	/**
4936
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4937
+	 * fields
4938
+	 *
4939
+	 * @param string  $fieldName
4940
+	 * @param boolean $include_db_only_fields
4941
+	 * @return EE_Model_Field_Base
4942
+	 * @throws EE_Error
4943
+	 */
4944
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4945
+	{
4946
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4947
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4948
+			throw new EE_Error(
4949
+				sprintf(
4950
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4951
+					$fieldName,
4952
+					get_class($this)
4953
+				)
4954
+			);
4955
+		}
4956
+		return $fieldSettings[ $fieldName ];
4957
+	}
4958
+
4959
+
4960
+	/**
4961
+	 * Checks if this field exists on this model
4962
+	 *
4963
+	 * @param string $fieldName a key in the model's _field_settings array
4964
+	 * @return boolean
4965
+	 */
4966
+	public function has_field($fieldName)
4967
+	{
4968
+		$fieldSettings = $this->field_settings(true);
4969
+		if (isset($fieldSettings[ $fieldName ])) {
4970
+			return true;
4971
+		}
4972
+		return false;
4973
+	}
4974
+
4975
+
4976
+	/**
4977
+	 * Returns whether or not this model has a relation to the specified model
4978
+	 *
4979
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4980
+	 * @return boolean
4981
+	 */
4982
+	public function has_relation($relation_name)
4983
+	{
4984
+		$relations = $this->relation_settings();
4985
+		if (isset($relations[ $relation_name ])) {
4986
+			return true;
4987
+		}
4988
+		return false;
4989
+	}
4990
+
4991
+
4992
+	/**
4993
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4994
+	 * Eg, on EE_Answer that would be ANS_ID field object
4995
+	 *
4996
+	 * @param $field_obj
4997
+	 * @return boolean
4998
+	 */
4999
+	public function is_primary_key_field($field_obj)
5000
+	{
5001
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5002
+	}
5003
+
5004
+
5005
+	/**
5006
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5007
+	 * Eg, on EE_Answer that would be ANS_ID field object
5008
+	 *
5009
+	 * @return EE_Model_Field_Base
5010
+	 * @throws EE_Error
5011
+	 */
5012
+	public function get_primary_key_field()
5013
+	{
5014
+		if ($this->_primary_key_field === null) {
5015
+			foreach ($this->field_settings(true) as $field_obj) {
5016
+				if ($this->is_primary_key_field($field_obj)) {
5017
+					$this->_primary_key_field = $field_obj;
5018
+					break;
5019
+				}
5020
+			}
5021
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5022
+				throw new EE_Error(
5023
+					sprintf(
5024
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5025
+						get_class($this)
5026
+					)
5027
+				);
5028
+			}
5029
+		}
5030
+		return $this->_primary_key_field;
5031
+	}
5032
+
5033
+
5034
+	/**
5035
+	 * Returns whether or not not there is a primary key on this model.
5036
+	 * Internally does some caching.
5037
+	 *
5038
+	 * @return boolean
5039
+	 */
5040
+	public function has_primary_key_field()
5041
+	{
5042
+		if ($this->_has_primary_key_field === null) {
5043
+			try {
5044
+				$this->get_primary_key_field();
5045
+				$this->_has_primary_key_field = true;
5046
+			} catch (EE_Error $e) {
5047
+				$this->_has_primary_key_field = false;
5048
+			}
5049
+		}
5050
+		return $this->_has_primary_key_field;
5051
+	}
5052
+
5053
+
5054
+	/**
5055
+	 * Finds the first field of type $field_class_name.
5056
+	 *
5057
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5058
+	 *                                 EE_Foreign_Key_Field, etc
5059
+	 * @return EE_Model_Field_Base or null if none is found
5060
+	 */
5061
+	public function get_a_field_of_type($field_class_name)
5062
+	{
5063
+		foreach ($this->field_settings() as $field) {
5064
+			if ($field instanceof $field_class_name) {
5065
+				return $field;
5066
+			}
5067
+		}
5068
+		return null;
5069
+	}
5070
+
5071
+
5072
+	/**
5073
+	 * Gets a foreign key field pointing to model.
5074
+	 *
5075
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5076
+	 * @return EE_Foreign_Key_Field_Base
5077
+	 * @throws EE_Error
5078
+	 */
5079
+	public function get_foreign_key_to($model_name)
5080
+	{
5081
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
+			foreach ($this->field_settings() as $field) {
5083
+				if (
5084
+					$field instanceof EE_Foreign_Key_Field_Base
5085
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5086
+				) {
5087
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5088
+					break;
5089
+				}
5090
+			}
5091
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5092
+				throw new EE_Error(
5093
+					sprintf(
5094
+						esc_html__(
5095
+							"There is no foreign key field pointing to model %s on model %s",
5096
+							'event_espresso'
5097
+						),
5098
+						$model_name,
5099
+						get_class($this)
5100
+					)
5101
+				);
5102
+			}
5103
+		}
5104
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5105
+	}
5106
+
5107
+
5108
+	/**
5109
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5110
+	 *
5111
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5112
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5113
+	 *                            Either one works
5114
+	 * @return string
5115
+	 */
5116
+	public function get_table_for_alias($table_alias)
5117
+	{
5118
+		$table_alias_sans_model_relation_chain_prefix =
5119
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5120
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5121
+	}
5122
+
5123
+
5124
+	/**
5125
+	 * Returns a flat array of all field son this model, instead of organizing them
5126
+	 * by table_alias as they are in the constructor.
5127
+	 *
5128
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5129
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5130
+	 */
5131
+	public function field_settings($include_db_only_fields = false)
5132
+	{
5133
+		if ($include_db_only_fields) {
5134
+			if ($this->_cached_fields === null) {
5135
+				$this->_cached_fields = [];
5136
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5137
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
+						$this->_cached_fields[ $field_name ] = $field_obj;
5139
+					}
5140
+				}
5141
+			}
5142
+			return $this->_cached_fields;
5143
+		}
5144
+		if ($this->_cached_fields_non_db_only === null) {
5145
+			$this->_cached_fields_non_db_only = [];
5146
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5147
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148
+					/** @var $field_obj EE_Model_Field_Base */
5149
+					if (! $field_obj->is_db_only_field()) {
5150
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5151
+					}
5152
+				}
5153
+			}
5154
+		}
5155
+		return $this->_cached_fields_non_db_only;
5156
+	}
5157
+
5158
+
5159
+	/**
5160
+	 *        cycle though array of attendees and create objects out of each item
5161
+	 *
5162
+	 * @access        private
5163
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5164
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5165
+	 *                           numerically indexed)
5166
+	 * @throws EE_Error
5167
+	 * @throws ReflectionException
5168
+	 */
5169
+	protected function _create_objects($rows = [])
5170
+	{
5171
+		$array_of_objects = [];
5172
+		if (empty($rows)) {
5173
+			return [];
5174
+		}
5175
+		$count_if_model_has_no_primary_key = 0;
5176
+		$has_primary_key                   = $this->has_primary_key_field();
5177
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5178
+		foreach ((array)$rows as $row) {
5179
+			if (empty($row)) {
5180
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5181
+				return [];
5182
+			}
5183
+			// check if we've already set this object in the results array,
5184
+			// in which case there's no need to process it further (again)
5185
+			if ($has_primary_key) {
5186
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5187
+					$row,
5188
+					$primary_key_field->get_qualified_column(),
5189
+					$primary_key_field->get_table_column()
5190
+				);
5191
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5192
+					continue;
5193
+				}
5194
+			}
5195
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5196
+			if (! $classInstance) {
5197
+				throw new EE_Error(
5198
+					sprintf(
5199
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5200
+						$this->get_this_model_name(),
5201
+						http_build_query($row)
5202
+					)
5203
+				);
5204
+			}
5205
+			// set the timezone on the instantiated objects
5206
+			$classInstance->set_timezone($this->get_timezone(), true);
5207
+			// make sure if there is any timezone setting present that we set the timezone for the object
5208
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5209
+			$array_of_objects[ $key ] = $classInstance;
5210
+			// also, for all the relations of type BelongsTo, see if we can cache
5211
+			// those related models
5212
+			// (we could do this for other relations too, but if there are conditions
5213
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5214
+			// so it requires a little more thought than just caching them immediately...)
5215
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5216
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5217
+					// check if this model's INFO is present. If so, cache it on the model
5218
+					$other_model           = $relation_obj->get_other_model();
5219
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5220
+					// if we managed to make a model object from the results, cache it on the main model object
5221
+					if ($other_model_obj_maybe) {
5222
+						// set timezone on these other model objects if they are present
5223
+						$other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5224
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5225
+					}
5226
+				}
5227
+			}
5228
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5229
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5230
+			// the field in the CustomSelects object
5231
+			if ($this->_custom_selections instanceof CustomSelects) {
5232
+				$classInstance->setCustomSelectsValues(
5233
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5234
+				);
5235
+			}
5236
+		}
5237
+		return $array_of_objects;
5238
+	}
5239
+
5240
+
5241
+	/**
5242
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5243
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5244
+	 *
5245
+	 * @param array $db_results_row
5246
+	 * @return array
5247
+	 */
5248
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5249
+	{
5250
+		$results = [];
5251
+		if ($this->_custom_selections instanceof CustomSelects) {
5252
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5253
+				if (isset($db_results_row[ $alias ])) {
5254
+					$results[ $alias ] = $this->convertValueToDataType(
5255
+						$db_results_row[ $alias ],
5256
+						$this->_custom_selections->getDataTypeForAlias($alias)
5257
+					);
5258
+				}
5259
+			}
5260
+		}
5261
+		return $results;
5262
+	}
5263
+
5264
+
5265
+	/**
5266
+	 * This will set the value for the given alias
5267
+	 *
5268
+	 * @param string $value
5269
+	 * @param string $datatype (one of %d, %s, %f)
5270
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5271
+	 */
5272
+	protected function convertValueToDataType($value, $datatype)
5273
+	{
5274
+		switch ($datatype) {
5275
+			case '%f':
5276
+				return (float)$value;
5277
+			case '%d':
5278
+				return (int)$value;
5279
+			default:
5280
+				return (string)$value;
5281
+		}
5282
+	}
5283
+
5284
+
5285
+	/**
5286
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5287
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5288
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5289
+	 * object (as set in the model_field!).
5290
+	 *
5291
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5292
+	 * @throws EE_Error
5293
+	 * @throws ReflectionException
5294
+	 */
5295
+	public function create_default_object()
5296
+	{
5297
+		$this_model_fields_and_values = [];
5298
+		// setup the row using default values;
5299
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5300
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5301
+		}
5302
+		$className = $this->_get_class_name();
5303
+		return EE_Registry::instance()->load_class(
5304
+			$className,
5305
+			[$this_model_fields_and_values],
5306
+			false,
5307
+			false
5308
+		);
5309
+	}
5310
+
5311
+
5312
+	/**
5313
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5314
+	 *                             or an stdClass where each property is the name of a column,
5315
+	 * @return EE_Base_Class
5316
+	 * @throws EE_Error
5317
+	 * @throws ReflectionException
5318
+	 */
5319
+	public function instantiate_class_from_array_or_object($cols_n_values)
5320
+	{
5321
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5322
+			$cols_n_values = get_object_vars($cols_n_values);
5323
+		}
5324
+		$primary_key = null;
5325
+		// make sure the array only has keys that are fields/columns on this model
5326
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5327
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5328
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5329
+		}
5330
+		$className = $this->_get_class_name();
5331
+		// check we actually found results that we can use to build our model object
5332
+		// if not, return null
5333
+		if ($this->has_primary_key_field()) {
5334
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5335
+				return null;
5336
+			}
5337
+		} elseif ($this->unique_indexes()) {
5338
+			$first_column = reset($this_model_fields_n_values);
5339
+			if (empty($first_column)) {
5340
+				return null;
5341
+			}
5342
+		}
5343
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5344
+		if ($primary_key) {
5345
+			$classInstance = $this->get_from_entity_map($primary_key);
5346
+			if (! $classInstance) {
5347
+				$classInstance = EE_Registry::instance()->load_class(
5348
+					$className,
5349
+					[$this_model_fields_n_values, $this->get_timezone()],
5350
+					true,
5351
+					false
5352
+				);
5353
+				// add this new object to the entity map
5354
+				$classInstance = $this->add_to_entity_map($classInstance);
5355
+			}
5356
+		} else {
5357
+			$classInstance = EE_Registry::instance()->load_class(
5358
+				$className,
5359
+				[$this_model_fields_n_values, $this->get_timezone()],
5360
+				true,
5361
+				false
5362
+			);
5363
+		}
5364
+		return $classInstance;
5365
+	}
5366
+
5367
+
5368
+	/**
5369
+	 * Gets the model object from the  entity map if it exists
5370
+	 *
5371
+	 * @param int|string $id the ID of the model object
5372
+	 * @return EE_Base_Class
5373
+	 */
5374
+	public function get_from_entity_map($id)
5375
+	{
5376
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5377
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5378
+			: null;
5379
+	}
5380
+
5381
+
5382
+	/**
5383
+	 * add_to_entity_map
5384
+	 * Adds the object to the model's entity mappings
5385
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5386
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5387
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5388
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5389
+	 *        then this method should be called immediately after the update query
5390
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5391
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5392
+	 *
5393
+	 * @param EE_Base_Class $object
5394
+	 * @return EE_Base_Class
5395
+	 * @throws EE_Error
5396
+	 */
5397
+	public function add_to_entity_map(EE_Base_Class $object)
5398
+	{
5399
+		$className = $this->_get_class_name();
5400
+		if (! $object instanceof $className) {
5401
+			throw new EE_Error(
5402
+				sprintf(
5403
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5404
+					is_object($object) ? get_class($object) : $object,
5405
+					$className
5406
+				)
5407
+			);
5408
+		}
5409
+		if (! $object->ID()) {
5410
+			throw new DomainException(
5411
+				sprintf(
5412
+					esc_html__(
5413
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5414
+						"event_espresso"
5415
+					),
5416
+					get_class($this)
5417
+				)
5418
+			);
5419
+		}
5420
+		// double check it's not already there
5421
+		$classInstance = $this->get_from_entity_map($object->ID());
5422
+		if ($classInstance) {
5423
+			return $classInstance;
5424
+		}
5425
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5426
+		return $object;
5427
+	}
5428
+
5429
+
5430
+	/**
5431
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5432
+	 * if no identifier is provided, then the entire entity map is emptied
5433
+	 *
5434
+	 * @param int|string $id the ID of the model object
5435
+	 * @return boolean
5436
+	 */
5437
+	public function clear_entity_map($id = null)
5438
+	{
5439
+		if (empty($id)) {
5440
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5441
+			return true;
5442
+		}
5443
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5444
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5445
+			return true;
5446
+		}
5447
+		return false;
5448
+	}
5449
+
5450
+
5451
+	/**
5452
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5453
+	 * Given an array where keys are column (or column alias) names and values,
5454
+	 * returns an array of their corresponding field names and database values
5455
+	 *
5456
+	 * @param array $cols_n_values
5457
+	 * @return array
5458
+	 * @throws EE_Error
5459
+	 * @throws ReflectionException
5460
+	 */
5461
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5462
+	{
5463
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5464
+	}
5465
+
5466
+
5467
+	/**
5468
+	 * _deduce_fields_n_values_from_cols_n_values
5469
+	 * Given an array where keys are column (or column alias) names and values,
5470
+	 * returns an array of their corresponding field names and database values
5471
+	 *
5472
+	 * @param array $cols_n_values
5473
+	 * @return array
5474
+	 * @throws EE_Error
5475
+	 * @throws ReflectionException
5476
+	 */
5477
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5478
+	{
5479
+		$this_model_fields_n_values = [];
5480
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5481
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5482
+				$cols_n_values,
5483
+				$table_obj->get_fully_qualified_pk_column(),
5484
+				$table_obj->get_pk_column()
5485
+			);
5486
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5487
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5488
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5489
+					if (! $field_obj->is_db_only_field()) {
5490
+						// prepare field as if its coming from db
5491
+						$prepared_value                            =
5492
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5493
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5494
+					}
5495
+				}
5496
+			} else {
5497
+				// the table's rows existed. Use their values
5498
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5499
+					if (! $field_obj->is_db_only_field()) {
5500
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5501
+							$cols_n_values,
5502
+							$field_obj->get_qualified_column(),
5503
+							$field_obj->get_table_column()
5504
+						);
5505
+					}
5506
+				}
5507
+			}
5508
+		}
5509
+		return $this_model_fields_n_values;
5510
+	}
5511
+
5512
+
5513
+	/**
5514
+	 * @param array  $cols_n_values
5515
+	 * @param string $qualified_column
5516
+	 * @param string $regular_column
5517
+	 * @return null
5518
+	 * @throws EE_Error
5519
+	 * @throws ReflectionException
5520
+	 */
5521
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5522
+	{
5523
+		$value = null;
5524
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5525
+		// does the field on the model relate to this column retrieved from the db?
5526
+		// or is it a db-only field? (not relating to the model)
5527
+		if (isset($cols_n_values[ $qualified_column ])) {
5528
+			$value = $cols_n_values[ $qualified_column ];
5529
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5530
+			$value = $cols_n_values[ $regular_column ];
5531
+		} elseif (! empty($this->foreign_key_aliases)) {
5532
+			// no PK?  ok check if there is a foreign key alias set for this table
5533
+			// then check if that alias exists in the incoming data
5534
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5535
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5536
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5537
+					$value = $cols_n_values[ $FK_alias ];
5538
+					[$pk_class] = explode('.', $PK_column);
5539
+					$pk_model_name = "EEM_{$pk_class}";
5540
+					/** @var EEM_Base $pk_model */
5541
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5542
+					if ($pk_model instanceof EEM_Base) {
5543
+						// make sure object is pulled from db and added to entity map
5544
+						$pk_model->get_one_by_ID($value);
5545
+					}
5546
+					break;
5547
+				}
5548
+			}
5549
+		}
5550
+		return $value;
5551
+	}
5552
+
5553
+
5554
+	/**
5555
+	 * refresh_entity_map_from_db
5556
+	 * Makes sure the model object in the entity map at $id assumes the values
5557
+	 * of the database (opposite of EE_base_Class::save())
5558
+	 *
5559
+	 * @param int|string $id
5560
+	 * @return EE_Base_Class
5561
+	 * @throws EE_Error
5562
+	 * @throws ReflectionException
5563
+	 */
5564
+	public function refresh_entity_map_from_db($id)
5565
+	{
5566
+		$obj_in_map = $this->get_from_entity_map($id);
5567
+		if ($obj_in_map) {
5568
+			$wpdb_results = $this->_get_all_wpdb_results(
5569
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5570
+			);
5571
+			if ($wpdb_results && is_array($wpdb_results)) {
5572
+				$one_row = reset($wpdb_results);
5573
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5574
+					$obj_in_map->set_from_db($field_name, $db_value);
5575
+				}
5576
+				// clear the cache of related model objects
5577
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5578
+					$obj_in_map->clear_cache($relation_name, null, true);
5579
+				}
5580
+			}
5581
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5582
+			return $obj_in_map;
5583
+		}
5584
+		return $this->get_one_by_ID($id);
5585
+	}
5586
+
5587
+
5588
+	/**
5589
+	 * refresh_entity_map_with
5590
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5591
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5592
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5593
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5594
+	 *
5595
+	 * @param int|string    $id
5596
+	 * @param EE_Base_Class $replacing_model_obj
5597
+	 * @return EE_Base_Class
5598
+	 * @throws EE_Error
5599
+	 * @throws ReflectionException
5600
+	 */
5601
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5602
+	{
5603
+		$obj_in_map = $this->get_from_entity_map($id);
5604
+		if ($obj_in_map) {
5605
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5606
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5607
+					$obj_in_map->set($field_name, $value);
5608
+				}
5609
+				// make the model object in the entity map's cache match the $replacing_model_obj
5610
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5611
+					$obj_in_map->clear_cache($relation_name, null, true);
5612
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5613
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5614
+					}
5615
+				}
5616
+			}
5617
+			return $obj_in_map;
5618
+		}
5619
+		$this->add_to_entity_map($replacing_model_obj);
5620
+		return $replacing_model_obj;
5621
+	}
5622
+
5623
+
5624
+	/**
5625
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5626
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5627
+	 * require_once($this->_getClassName().".class.php");
5628
+	 *
5629
+	 * @return string
5630
+	 */
5631
+	private function _get_class_name()
5632
+	{
5633
+		return "EE_" . $this->get_this_model_name();
5634
+	}
5635
+
5636
+
5637
+	/**
5638
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5639
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5640
+	 * it would be 'Events'.
5641
+	 *
5642
+	 * @param int $quantity
5643
+	 * @return string
5644
+	 */
5645
+	public function item_name($quantity = 1)
5646
+	{
5647
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5648
+	}
5649
+
5650
+
5651
+	/**
5652
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5653
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5654
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5655
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5656
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5657
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5658
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5659
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5660
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5661
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5662
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5663
+	 *        return $previousReturnValue.$returnString;
5664
+	 * }
5665
+	 * require('EEM_Answer.model.php');
5666
+	 * $answer=EEM_Answer::instance();
5667
+	 * echo $answer->my_callback('monkeys',100);
5668
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5669
+	 *
5670
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5671
+	 * @param array  $args       array of original arguments passed to the function
5672
+	 * @return mixed whatever the plugin which calls add_filter decides
5673
+	 * @throws EE_Error
5674
+	 */
5675
+	public function __call($methodName, $args)
5676
+	{
5677
+		$className = get_class($this);
5678
+		$tagName   = "FHEE__{$className}__{$methodName}";
5679
+		if (! has_filter($tagName)) {
5680
+			throw new EE_Error(
5681
+				sprintf(
5682
+					esc_html__(
5683
+						'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 );',
5684
+						'event_espresso'
5685
+					),
5686
+					$methodName,
5687
+					$className,
5688
+					$tagName,
5689
+					'<br />'
5690
+				)
5691
+			);
5692
+		}
5693
+		return apply_filters($tagName, null, $this, $args);
5694
+	}
5695
+
5696
+
5697
+	/**
5698
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5699
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5700
+	 *
5701
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5702
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5703
+	 *                                                       the object's class name
5704
+	 *                                                       or object's ID
5705
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5706
+	 *                                                       exists in the database. If it does not, we add it
5707
+	 * @return EE_Base_Class
5708
+	 * @throws EE_Error
5709
+	 * @throws ReflectionException
5710
+	 */
5711
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5712
+	{
5713
+		$className = $this->_get_class_name();
5714
+		if ($base_class_obj_or_id instanceof $className) {
5715
+			$model_object = $base_class_obj_or_id;
5716
+		} else {
5717
+			$primary_key_field = $this->get_primary_key_field();
5718
+			if (
5719
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5720
+				&& (
5721
+					is_int($base_class_obj_or_id)
5722
+					|| is_string($base_class_obj_or_id)
5723
+				)
5724
+			) {
5725
+				// assume it's an ID.
5726
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5727
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5728
+			} elseif (
5729
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5730
+				&& is_string($base_class_obj_or_id)
5731
+			) {
5732
+				// assume its a string representation of the object
5733
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5734
+			} else {
5735
+				throw new EE_Error(
5736
+					sprintf(
5737
+						esc_html__(
5738
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5739
+							'event_espresso'
5740
+						),
5741
+						$base_class_obj_or_id,
5742
+						$this->_get_class_name(),
5743
+						print_r($base_class_obj_or_id, true)
5744
+					)
5745
+				);
5746
+			}
5747
+		}
5748
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5749
+			$model_object->save();
5750
+		}
5751
+		return $model_object;
5752
+	}
5753
+
5754
+
5755
+	/**
5756
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5757
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5758
+	 * returns it ID.
5759
+	 *
5760
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5761
+	 * @return int|string depending on the type of this model object's ID
5762
+	 * @throws EE_Error
5763
+	 */
5764
+	public function ensure_is_ID($base_class_obj_or_id)
5765
+	{
5766
+		$className = $this->_get_class_name();
5767
+		if ($base_class_obj_or_id instanceof $className) {
5768
+			$id = $base_class_obj_or_id->ID();
5769
+		} elseif (is_int($base_class_obj_or_id)) {
5770
+			// assume it's an ID
5771
+			$id = $base_class_obj_or_id;
5772
+		} elseif (is_string($base_class_obj_or_id)) {
5773
+			// assume its a string representation of the object
5774
+			$id = $base_class_obj_or_id;
5775
+		} else {
5776
+			throw new EE_Error(
5777
+				sprintf(
5778
+					esc_html__(
5779
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5780
+						'event_espresso'
5781
+					),
5782
+					$base_class_obj_or_id,
5783
+					$this->_get_class_name(),
5784
+					print_r($base_class_obj_or_id, true)
5785
+				)
5786
+			);
5787
+		}
5788
+		return $id;
5789
+	}
5790
+
5791
+
5792
+	/**
5793
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5794
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5795
+	 * been sanitized and converted into the appropriate domain.
5796
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5797
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5798
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5799
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5800
+	 * $EVT = EEM_Event::instance(); $old_setting =
5801
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5802
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5803
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5804
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5805
+	 *
5806
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5807
+	 * @return void
5808
+	 */
5809
+	public function assume_values_already_prepared_by_model_object(
5810
+		$values_already_prepared = self::not_prepared_by_model_object
5811
+	) {
5812
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5813
+	}
5814
+
5815
+
5816
+	/**
5817
+	 * Read comments for assume_values_already_prepared_by_model_object()
5818
+	 *
5819
+	 * @return int
5820
+	 */
5821
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5822
+	{
5823
+		return $this->_values_already_prepared_by_model_object;
5824
+	}
5825
+
5826
+
5827
+	/**
5828
+	 * Gets all the indexes on this model
5829
+	 *
5830
+	 * @return EE_Index[]
5831
+	 */
5832
+	public function indexes()
5833
+	{
5834
+		return $this->_indexes;
5835
+	}
5836
+
5837
+
5838
+	/**
5839
+	 * Gets all the Unique Indexes on this model
5840
+	 *
5841
+	 * @return EE_Unique_Index[]
5842
+	 */
5843
+	public function unique_indexes()
5844
+	{
5845
+		$unique_indexes = [];
5846
+		foreach ($this->_indexes as $name => $index) {
5847
+			if ($index instanceof EE_Unique_Index) {
5848
+				$unique_indexes [ $name ] = $index;
5849
+			}
5850
+		}
5851
+		return $unique_indexes;
5852
+	}
5853
+
5854
+
5855
+	/**
5856
+	 * Gets all the fields which, when combined, make the primary key.
5857
+	 * This is usually just an array with 1 element (the primary key), but in cases
5858
+	 * where there is no primary key, it's a combination of fields as defined
5859
+	 * on a primary index
5860
+	 *
5861
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function get_combined_primary_key_fields()
5865
+	{
5866
+		foreach ($this->indexes() as $index) {
5867
+			if ($index instanceof EE_Primary_Key_Index) {
5868
+				return $index->fields();
5869
+			}
5870
+		}
5871
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5872
+	}
5873
+
5874
+
5875
+	/**
5876
+	 * Used to build a primary key string (when the model has no primary key),
5877
+	 * which can be used a unique string to identify this model object.
5878
+	 *
5879
+	 * @param array $fields_n_values keys are field names, values are their values.
5880
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5881
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5882
+	 *                               before passing it to this function (that will convert it from columns-n-values
5883
+	 *                               to field-names-n-values).
5884
+	 * @return string
5885
+	 * @throws EE_Error
5886
+	 */
5887
+	public function get_index_primary_key_string($fields_n_values)
5888
+	{
5889
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5890
+			$fields_n_values,
5891
+			$this->get_combined_primary_key_fields()
5892
+		);
5893
+		return http_build_query($cols_n_values_for_primary_key_index);
5894
+	}
5895
+
5896
+
5897
+	/**
5898
+	 * Gets the field values from the primary key string
5899
+	 *
5900
+	 * @param string $index_primary_key_string
5901
+	 * @return null|array
5902
+	 * @throws EE_Error
5903
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5904
+	 */
5905
+	public function parse_index_primary_key_string($index_primary_key_string)
5906
+	{
5907
+		$key_fields = $this->get_combined_primary_key_fields();
5908
+		// check all of them are in the $id
5909
+		$key_values_in_combined_pk = [];
5910
+		parse_str($index_primary_key_string, $key_values_in_combined_pk);
5911
+		foreach ($key_fields as $key_field_name => $field_obj) {
5912
+			if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5913
+				return null;
5914
+			}
5915
+		}
5916
+		return $key_values_in_combined_pk;
5917
+	}
5918
+
5919
+
5920
+	/**
5921
+	 * verifies that an array of key-value pairs for model fields has a key
5922
+	 * for each field comprising the primary key index
5923
+	 *
5924
+	 * @param array $key_values
5925
+	 * @return boolean
5926
+	 * @throws EE_Error
5927
+	 */
5928
+	public function has_all_combined_primary_key_fields($key_values)
5929
+	{
5930
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5931
+		foreach ($keys_it_should_have as $key) {
5932
+			if (! isset($key_values[ $key ])) {
5933
+				return false;
5934
+			}
5935
+		}
5936
+		return true;
5937
+	}
5938
+
5939
+
5940
+	/**
5941
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5942
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5943
+	 *
5944
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5945
+	 * @param array               $query_params                     see github link below for more info
5946
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5947
+	 * @throws EE_Error
5948
+	 * @throws ReflectionException
5949
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5950
+	 *                                                              indexed)
5951
+	 */
5952
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5953
+	{
5954
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5955
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5956
+		} elseif (is_array($model_object_or_attributes_array)) {
5957
+			$attributes_array = $model_object_or_attributes_array;
5958
+		} else {
5959
+			throw new EE_Error(
5960
+				sprintf(
5961
+					esc_html__(
5962
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5963
+						"event_espresso"
5964
+					),
5965
+					$model_object_or_attributes_array
5966
+				)
5967
+			);
5968
+		}
5969
+		// even copies obviously won't have the same ID, so remove the primary key
5970
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5971
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5972
+			unset($attributes_array[ $this->primary_key_name() ]);
5973
+		}
5974
+		if (isset($query_params[0])) {
5975
+			$query_params[0] = array_merge($attributes_array, $query_params);
5976
+		} else {
5977
+			$query_params[0] = $attributes_array;
5978
+		}
5979
+		return $this->get_all($query_params);
5980
+	}
5981
+
5982
+
5983
+	/**
5984
+	 * Gets the first copy we find. See get_all_copies for more details
5985
+	 *
5986
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5987
+	 * @param array $query_params
5988
+	 * @return EE_Base_Class
5989
+	 * @throws EE_Error
5990
+	 * @throws ReflectionException
5991
+	 */
5992
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5993
+	{
5994
+		if (! is_array($query_params)) {
5995
+			EE_Error::doing_it_wrong(
5996
+				'EEM_Base::get_one_copy',
5997
+				sprintf(
5998
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5999
+					gettype($query_params)
6000
+				),
6001
+				'4.6.0'
6002
+			);
6003
+			$query_params = [];
6004
+		}
6005
+		$query_params['limit'] = 1;
6006
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6007
+		if (is_array($copies)) {
6008
+			return array_shift($copies);
6009
+		}
6010
+		return null;
6011
+	}
6012
+
6013
+
6014
+	/**
6015
+	 * Updates the item with the specified id. Ignores default query parameters because
6016
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6017
+	 *
6018
+	 * @param array      $fields_n_values keys are field names, values are their new values
6019
+	 * @param int|string $id              the value of the primary key to update
6020
+	 * @return int number of rows updated
6021
+	 * @throws EE_Error
6022
+	 * @throws ReflectionException
6023
+	 */
6024
+	public function update_by_ID($fields_n_values, $id)
6025
+	{
6026
+		$query_params = [
6027
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6028
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6029
+		];
6030
+		return $this->update($fields_n_values, $query_params);
6031
+	}
6032
+
6033
+
6034
+	/**
6035
+	 * Changes an operator which was supplied to the models into one usable in SQL
6036
+	 *
6037
+	 * @param string $operator_supplied
6038
+	 * @return string an operator which can be used in SQL
6039
+	 * @throws EE_Error
6040
+	 */
6041
+	private function _prepare_operator_for_sql($operator_supplied)
6042
+	{
6043
+		$sql_operator =
6044
+			isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6045
+				: null;
6046
+		if ($sql_operator) {
6047
+			return $sql_operator;
6048
+		}
6049
+		throw new EE_Error(
6050
+			sprintf(
6051
+				esc_html__(
6052
+					"The operator '%s' is not in the list of valid operators: %s",
6053
+					"event_espresso"
6054
+				),
6055
+				$operator_supplied,
6056
+				implode(",", array_keys($this->_valid_operators))
6057
+			)
6058
+		);
6059
+	}
6060
+
6061
+
6062
+	/**
6063
+	 * Gets the valid operators
6064
+	 *
6065
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6066
+	 */
6067
+	public function valid_operators()
6068
+	{
6069
+		return $this->_valid_operators;
6070
+	}
6071
+
6072
+
6073
+	/**
6074
+	 * Gets the between-style operators (take 2 arguments).
6075
+	 *
6076
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6077
+	 */
6078
+	public function valid_between_style_operators()
6079
+	{
6080
+		return array_intersect(
6081
+			$this->valid_operators(),
6082
+			$this->_between_style_operators
6083
+		);
6084
+	}
6085
+
6086
+
6087
+	/**
6088
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6089
+	 *
6090
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6091
+	 */
6092
+	public function valid_like_style_operators()
6093
+	{
6094
+		return array_intersect(
6095
+			$this->valid_operators(),
6096
+			$this->_like_style_operators
6097
+		);
6098
+	}
6099
+
6100
+
6101
+	/**
6102
+	 * Gets the "in"-style operators
6103
+	 *
6104
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6105
+	 */
6106
+	public function valid_in_style_operators()
6107
+	{
6108
+		return array_intersect(
6109
+			$this->valid_operators(),
6110
+			$this->_in_style_operators
6111
+		);
6112
+	}
6113
+
6114
+
6115
+	/**
6116
+	 * Gets the "null"-style operators (accept no arguments)
6117
+	 *
6118
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6119
+	 */
6120
+	public function valid_null_style_operators()
6121
+	{
6122
+		return array_intersect(
6123
+			$this->valid_operators(),
6124
+			$this->_null_style_operators
6125
+		);
6126
+	}
6127
+
6128
+
6129
+	/**
6130
+	 * Gets an array where keys are the primary keys and values are their 'names'
6131
+	 * (as determined by the model object's name() function, which is often overridden)
6132
+	 *
6133
+	 * @param array $query_params like get_all's
6134
+	 * @return string[]
6135
+	 * @throws EE_Error
6136
+	 * @throws ReflectionException
6137
+	 */
6138
+	public function get_all_names($query_params = [])
6139
+	{
6140
+		$objs  = $this->get_all($query_params);
6141
+		$names = [];
6142
+		foreach ($objs as $obj) {
6143
+			$names[ $obj->ID() ] = $obj->name();
6144
+		}
6145
+		return $names;
6146
+	}
6147
+
6148
+
6149
+	/**
6150
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6151
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6152
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6153
+	 * array_keys() on $model_objects.
6154
+	 *
6155
+	 * @param EE_Base_Class[] $model_objects
6156
+	 * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6157
+	 *                                               in the returned array
6158
+	 * @return array
6159
+	 * @throws EE_Error
6160
+	 */
6161
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6162
+	{
6163
+		if (! $this->has_primary_key_field()) {
6164
+			if (WP_DEBUG) {
6165
+				EE_Error::add_error(
6166
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6167
+					__FILE__,
6168
+					__FUNCTION__,
6169
+					__LINE__
6170
+				);
6171
+			}
6172
+		}
6173
+		$IDs = [];
6174
+		foreach ($model_objects as $model_object) {
6175
+			$id = $model_object->ID();
6176
+			if (! $id) {
6177
+				if ($filter_out_empty_ids) {
6178
+					continue;
6179
+				}
6180
+				if (WP_DEBUG) {
6181
+					EE_Error::add_error(
6182
+						esc_html__(
6183
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6184
+							'event_espresso'
6185
+						),
6186
+						__FILE__,
6187
+						__FUNCTION__,
6188
+						__LINE__
6189
+					);
6190
+				}
6191
+			}
6192
+			$IDs[] = $id;
6193
+		}
6194
+		return $IDs;
6195
+	}
6196
+
6197
+
6198
+	/**
6199
+	 * Returns the string used in capabilities relating to this model. If there
6200
+	 * are no capabilities that relate to this model returns false
6201
+	 *
6202
+	 * @return string|false
6203
+	 */
6204
+	public function cap_slug()
6205
+	{
6206
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6207
+	}
6208
+
6209
+
6210
+	/**
6211
+	 * Returns the capability-restrictions array (@param string $context
6212
+	 *
6213
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6214
+	 * @throws EE_Error
6215
+	 * @see EEM_Base::_cap_restrictions).
6216
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6217
+	 *      only returns the cap restrictions array in that context (ie, the array
6218
+	 *      at that key)
6219
+	 *
6220
+	 */
6221
+	public function cap_restrictions($context = EEM_Base::caps_read)
6222
+	{
6223
+		EEM_Base::verify_is_valid_cap_context($context);
6224
+		// check if we ought to run the restriction generator first
6225
+		if (
6226
+			isset($this->_cap_restriction_generators[ $context ])
6227
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6228
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6229
+		) {
6230
+			$this->_cap_restrictions[ $context ] = array_merge(
6231
+				$this->_cap_restrictions[ $context ],
6232
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6233
+			);
6234
+		}
6235
+		// and make sure we've finalized the construction of each restriction
6236
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6237
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6238
+				$where_conditions_obj->_finalize_construct($this);
6239
+			}
6240
+		}
6241
+		return $this->_cap_restrictions[ $context ];
6242
+	}
6243
+
6244
+
6245
+	/**
6246
+	 * Indicating whether or not this model thinks its a wp core model
6247
+	 *
6248
+	 * @return boolean
6249
+	 */
6250
+	public function is_wp_core_model()
6251
+	{
6252
+		return $this->_wp_core_model;
6253
+	}
6254
+
6255
+
6256
+	/**
6257
+	 * Gets all the caps that are missing which impose a restriction on
6258
+	 * queries made in this context
6259
+	 *
6260
+	 * @param string $context one of EEM_Base::caps_ constants
6261
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6262
+	 * @throws EE_Error
6263
+	 */
6264
+	public function caps_missing($context = EEM_Base::caps_read)
6265
+	{
6266
+		$missing_caps     = [];
6267
+		$cap_restrictions = $this->cap_restrictions($context);
6268
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6269
+			if (
6270
+			! EE_Capabilities::instance()
6271
+							 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6272
+			) {
6273
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6274
+			}
6275
+		}
6276
+		return $missing_caps;
6277
+	}
6278
+
6279
+
6280
+	/**
6281
+	 * Gets the mapping from capability contexts to action strings used in capability names
6282
+	 *
6283
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6284
+	 * one of 'read', 'edit', or 'delete'
6285
+	 */
6286
+	public function cap_contexts_to_cap_action_map()
6287
+	{
6288
+		return apply_filters(
6289
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6290
+			$this->_cap_contexts_to_cap_action_map,
6291
+			$this
6292
+		);
6293
+	}
6294
+
6295
+
6296
+	/**
6297
+	 * Gets the action string for the specified capability context
6298
+	 *
6299
+	 * @param string $context
6300
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6301
+	 * @throws EE_Error
6302
+	 */
6303
+	public function cap_action_for_context($context)
6304
+	{
6305
+		$mapping = $this->cap_contexts_to_cap_action_map();
6306
+		if (isset($mapping[ $context ])) {
6307
+			return $mapping[ $context ];
6308
+		}
6309
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6310
+			return $action;
6311
+		}
6312
+		throw new EE_Error(
6313
+			sprintf(
6314
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6315
+				$context,
6316
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6317
+			)
6318
+		);
6319
+	}
6320
+
6321
+
6322
+	/**
6323
+	 * Returns all the capability contexts which are valid when querying models
6324
+	 *
6325
+	 * @return array
6326
+	 */
6327
+	public static function valid_cap_contexts()
6328
+	{
6329
+		return apply_filters(
6330
+			'FHEE__EEM_Base__valid_cap_contexts',
6331
+			[
6332
+				self::caps_read,
6333
+				self::caps_read_admin,
6334
+				self::caps_edit,
6335
+				self::caps_delete,
6336
+			]
6337
+		);
6338
+	}
6339
+
6340
+
6341
+	/**
6342
+	 * Returns all valid options for 'default_where_conditions'
6343
+	 *
6344
+	 * @return array
6345
+	 */
6346
+	public static function valid_default_where_conditions()
6347
+	{
6348
+		return [
6349
+			EEM_Base::default_where_conditions_all,
6350
+			EEM_Base::default_where_conditions_this_only,
6351
+			EEM_Base::default_where_conditions_others_only,
6352
+			EEM_Base::default_where_conditions_minimum_all,
6353
+			EEM_Base::default_where_conditions_minimum_others,
6354
+			EEM_Base::default_where_conditions_none,
6355
+		];
6356
+	}
6357
+
6358
+	// public static function default_where_conditions_full
6359
+
6360
+
6361
+	/**
6362
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6363
+	 *
6364
+	 * @param string $context
6365
+	 * @return bool
6366
+	 * @throws EE_Error
6367
+	 */
6368
+	public static function verify_is_valid_cap_context($context)
6369
+	{
6370
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6371
+		if (in_array($context, $valid_cap_contexts)) {
6372
+			return true;
6373
+		}
6374
+		throw new EE_Error(
6375
+			sprintf(
6376
+				esc_html__(
6377
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6378
+					'event_espresso'
6379
+				),
6380
+				$context,
6381
+				'EEM_Base',
6382
+				implode(',', $valid_cap_contexts)
6383
+			)
6384
+		);
6385
+	}
6386
+
6387
+
6388
+	/**
6389
+	 * Clears all the models field caches. This is only useful when a sub-class
6390
+	 * might have added a field or something and these caches might be invalidated
6391
+	 */
6392
+	protected function _invalidate_field_caches()
6393
+	{
6394
+		$this->_cache_foreign_key_to_fields = [];
6395
+		$this->_cached_fields               = null;
6396
+		$this->_cached_fields_non_db_only   = null;
6397
+	}
6398
+
6399
+
6400
+	/**
6401
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6402
+	 * (eg "and", "or", "not").
6403
+	 *
6404
+	 * @return array
6405
+	 */
6406
+	public function logic_query_param_keys()
6407
+	{
6408
+		return $this->_logic_query_param_keys;
6409
+	}
6410
+
6411
+
6412
+	/**
6413
+	 * Determines whether or not the where query param array key is for a logic query param.
6414
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6415
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6416
+	 *
6417
+	 * @param $query_param_key
6418
+	 * @return bool
6419
+	 */
6420
+	public function is_logic_query_param_key($query_param_key)
6421
+	{
6422
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6423
+			if (
6424
+				$query_param_key === $logic_query_param_key
6425
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6426
+			) {
6427
+				return true;
6428
+			}
6429
+		}
6430
+		return false;
6431
+	}
6432
+
6433
+
6434
+	/**
6435
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6436
+	 *
6437
+	 * @return boolean
6438
+	 * @since 4.9.74.p
6439
+	 */
6440
+	public function hasPassword()
6441
+	{
6442
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6443
+		if ($this->has_password_field === null) {
6444
+			$password_field           = $this->getPasswordField();
6445
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6446
+		}
6447
+		return $this->has_password_field;
6448
+	}
6449
+
6450
+
6451
+	/**
6452
+	 * Returns the password field on this model, if there is one
6453
+	 *
6454
+	 * @return EE_Password_Field|null
6455
+	 * @since 4.9.74.p
6456
+	 */
6457
+	public function getPasswordField()
6458
+	{
6459
+		// if we definitely already know there is a password field or not (because has_password_field is true or false)
6460
+		// there's no need to search for it. If we don't know yet, then find out
6461
+		if ($this->has_password_field === null && $this->password_field === null) {
6462
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6463
+		}
6464
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6465
+		return $this->password_field;
6466
+	}
6467
+
6468
+
6469
+	/**
6470
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6471
+	 *
6472
+	 * @return EE_Model_Field_Base[]
6473
+	 * @throws EE_Error
6474
+	 * @since 4.9.74.p
6475
+	 */
6476
+	public function getPasswordProtectedFields()
6477
+	{
6478
+		$password_field = $this->getPasswordField();
6479
+		$fields         = [];
6480
+		if ($password_field instanceof EE_Password_Field) {
6481
+			$field_names = $password_field->protectedFields();
6482
+			foreach ($field_names as $field_name) {
6483
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6484
+			}
6485
+		}
6486
+		return $fields;
6487
+	}
6488
+
6489
+
6490
+	/**
6491
+	 * Checks if the current user can perform the requested action on this model
6492
+	 *
6493
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6494
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6495
+	 * @return bool
6496
+	 * @throws EE_Error
6497
+	 * @throws InvalidArgumentException
6498
+	 * @throws InvalidDataTypeException
6499
+	 * @throws InvalidInterfaceException
6500
+	 * @throws ReflectionException
6501
+	 * @throws UnexpectedEntityException
6502
+	 * @since 4.9.74.p
6503
+	 */
6504
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6505
+	{
6506
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6507
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6508
+		}
6509
+		if (! is_array($model_obj_or_fields_n_values)) {
6510
+			throw new UnexpectedEntityException(
6511
+				$model_obj_or_fields_n_values,
6512
+				'EE_Base_Class',
6513
+				sprintf(
6514
+					esc_html__(
6515
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6516
+						'event_espresso'
6517
+					),
6518
+					__FUNCTION__
6519
+				)
6520
+			);
6521
+		}
6522
+		return $this->exists(
6523
+			$this->alter_query_params_to_restrict_by_ID(
6524
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6525
+				[
6526
+					'default_where_conditions' => 'none',
6527
+					'caps'                     => $cap_to_check,
6528
+				]
6529
+			)
6530
+		);
6531
+	}
6532
+
6533
+
6534
+	/**
6535
+	 * Returns the query param where conditions key to the password affecting this model.
6536
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6537
+	 *
6538
+	 * @return null|string
6539
+	 * @throws EE_Error
6540
+	 * @throws InvalidArgumentException
6541
+	 * @throws InvalidDataTypeException
6542
+	 * @throws InvalidInterfaceException
6543
+	 * @throws ModelConfigurationException
6544
+	 * @throws ReflectionException
6545
+	 * @since 4.9.74.p
6546
+	 */
6547
+	public function modelChainAndPassword()
6548
+	{
6549
+		if ($this->model_chain_to_password === null) {
6550
+			throw new ModelConfigurationException(
6551
+				$this,
6552
+				esc_html_x(
6553
+				// @codingStandardsIgnoreStart
6554
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6555
+					// @codingStandardsIgnoreEnd
6556
+					'1: model name',
6557
+					'event_espresso'
6558
+				)
6559
+			);
6560
+		}
6561
+		if ($this->model_chain_to_password === '') {
6562
+			$model_with_password = $this;
6563
+		} else {
6564
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6565
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6566
+			} else {
6567
+				$last_model_in_chain = $this->model_chain_to_password;
6568
+			}
6569
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6570
+		}
6571
+
6572
+		$password_field = $model_with_password->getPasswordField();
6573
+		if ($password_field instanceof EE_Password_Field) {
6574
+			$password_field_name = $password_field->get_name();
6575
+		} else {
6576
+			throw new ModelConfigurationException(
6577
+				$this,
6578
+				sprintf(
6579
+					esc_html_x(
6580
+						'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"',
6581
+						'1: model name, 2: special string',
6582
+						'event_espresso'
6583
+					),
6584
+					$model_with_password->get_this_model_name(),
6585
+					$this->model_chain_to_password
6586
+				)
6587
+			);
6588
+		}
6589
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6590
+	}
6591
+
6592
+
6593
+	/**
6594
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6595
+	 * or if this model itself has a password affecting access to some of its other fields.
6596
+	 *
6597
+	 * @return boolean
6598
+	 * @since 4.9.74.p
6599
+	 */
6600
+	public function restrictedByRelatedModelPassword()
6601
+	{
6602
+		return $this->model_chain_to_password !== null;
6603
+	}
6604 6604
 }
Please login to merge, or discard this patch.
Spacing   +248 added lines, -248 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = '')
568 568
     {
569 569
         // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
570
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
571 571
             throw new EE_Error(
572 572
                 sprintf(
573 573
                     esc_html__(
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          *
591 591
          * @var EE_Table_Base[] $_tables
592 592
          */
593
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
593
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
594 594
         foreach ($this->_tables as $table_alias => $table_obj) {
595 595
             /** @var $table_obj EE_Table_Base */
596 596
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -605,10 +605,10 @@  discard block
 block discarded – undo
605 605
          *
606 606
          * @param EE_Model_Field_Base[] $_fields
607 607
          */
608
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
609 609
         $this->_invalidate_field_caches();
610 610
         foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
612 612
                 throw new EE_Error(
613 613
                     sprintf(
614 614
                         esc_html__(
@@ -644,8 +644,8 @@  discard block
 block discarded – undo
644 644
          *
645 645
          * @param EE_Model_Relation_Base[] $_model_relations
646 646
          */
647
-        $this->_model_relations = (array)apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
647
+        $this->_model_relations = (array) apply_filters(
648
+            'FHEE__'.get_class($this).'__construct__model_relations',
649 649
             $this->_model_relations
650 650
         );
651 651
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -657,12 +657,12 @@  discard block
 block discarded – undo
657 657
         }
658 658
         $this->set_timezone($timezone);
659 659
         // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
660
+        if ( ! $this->_default_where_conditions_strategy) {
661 661
             // nothing was set during child constructor, so set default
662 662
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663 663
         }
664 664
         $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
665
+        if ( ! $this->_minimum_where_conditions_strategy) {
666 666
             // nothing was set during child constructor, so set default
667 667
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668 668
         }
@@ -673,10 +673,10 @@  discard block
 block discarded – undo
673 673
             $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674 674
         }
675 675
         // initialize the standard cap restriction generators if none were specified by the child constructor
676
-        if (! empty($this->_cap_restriction_generators)) {
676
+        if ( ! empty($this->_cap_restriction_generators)) {
677 677
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
678
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
679
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
680 680
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681 681
                         new EE_Restriction_Generator_Protected(),
682 682
                         $cap_context,
@@ -688,10 +688,10 @@  discard block
 block discarded – undo
688 688
         // if ($this->_cap_restriction_generators !== false) {
689 689
         // if there are cap restriction generators, use them to make the default cap restrictions
690 690
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
691
+                if ( ! $generator_object) {
692 692
                     continue;
693 693
                 }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
695 695
                     throw new EE_Error(
696 696
                         sprintf(
697 697
                             esc_html__(
@@ -704,12 +704,12 @@  discard block
 block discarded – undo
704 704
                     );
705 705
                 }
706 706
                 $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
707
+                if ( ! $generator_object->construction_finalized()) {
708 708
                     $generator_object->_construct_finalize($this, $action);
709 709
                 }
710 710
             }
711 711
         }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
+        do_action('AHEE__'.get_class($this).'__construct__end');
713 713
     }
714 714
 
715 715
 
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
      */
722 722
     public static function set_model_query_blog_id($blog_id = 0)
723 723
     {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
724
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
725 725
     }
726 726
 
727 727
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
     public static function instance($timezone = '')
754 754
     {
755 755
         // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
756
+        if ( ! static::$_instance instanceof static) {
757 757
             // instantiate Espresso_model
758 758
             static::$_instance = new static(
759 759
                 $timezone,
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
             foreach ($r->getDefaultProperties() as $property => $value) {
790 790
                 // don't set instance to null like it was originally,
791 791
                 // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
792
+                if ( ! isset($static_properties[$property])) {
793 793
                     static::$_instance->{$property} = $value;
794 794
                 }
795 795
             }
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
      */
814 814
     private static function getLoader()
815 815
     {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
816
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
817 817
             EEM_Base::$loader = LoaderFactory::getLoader();
818 818
         }
819 819
         return EEM_Base::$loader;
@@ -833,15 +833,15 @@  discard block
 block discarded – undo
833 833
      */
834 834
     public function status_array($translated = false)
835 835
     {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
836
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
837 837
             return [];
838 838
         }
839 839
         $model_name   = $this->get_this_model_name();
840 840
         $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
-        $statuses      = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
841
+        $statuses = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842 842
         $status_array = [];
843 843
         foreach ($statuses as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
844
+            $status_array[$status->ID()] = $status->get('STS_code');
845 845
         }
846 846
         return $translated
847 847
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
     {
905 905
         $wp_user_field_name = $this->wp_user_field_name();
906 906
         if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
907
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
908 908
         }
909 909
         return $query_params;
910 910
     }
@@ -922,17 +922,17 @@  discard block
 block discarded – undo
922 922
     public function wp_user_field_name()
923 923
     {
924 924
         try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
925
+            if ( ! empty($this->_model_chain_to_wp_user)) {
926 926
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927 927
                 $last_model_name              = end($models_to_follow_to_wp_users);
928 928
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
929
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
930 930
             } else {
931 931
                 $model_with_fk_to_wp_users = $this;
932 932
                 $model_chain_to_wp_user    = '';
933 933
             }
934 934
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
935
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
936 936
         } catch (EE_Error $e) {
937 937
             return false;
938 938
         }
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
         if ($this->_custom_selections instanceof CustomSelects) {
1009 1009
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010 1010
             $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1011
+                ? ', '.$custom_expressions
1012 1012
                 : $custom_expressions;
1013 1013
         }
1014 1014
 
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1015
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1016 1016
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017 1017
     }
1018 1018
 
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
      */
1030 1030
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031 1031
     {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1032
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033 1033
             return null;
1034 1034
         }
1035 1035
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
         if (is_array($columns_to_select)) {
1079 1079
             $select_sql_array = [];
1080 1080
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1081
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
                         )
1091 1091
                     );
1092 1092
                 }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1093
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094 1094
                     throw new EE_Error(
1095 1095
                         sprintf(
1096 1096
                             esc_html__(
@@ -1169,12 +1169,12 @@  discard block
 block discarded – undo
1169 1169
      */
1170 1170
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1171 1171
     {
1172
-        if (! isset($query_params[0])) {
1172
+        if ( ! isset($query_params[0])) {
1173 1173
             $query_params[0] = [];
1174 1174
         }
1175 1175
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1176 1176
         if ($conditions_from_id === null) {
1177
-            $query_params[0][ $this->primary_key_name() ] = $id;
1177
+            $query_params[0][$this->primary_key_name()] = $id;
1178 1178
         } else {
1179 1179
             // no primary key, so the $id must be from the get_index_primary_key_string()
1180 1180
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1194,7 +1194,7 @@  discard block
 block discarded – undo
1194 1194
      */
1195 1195
     public function get_one(array $query_params = [])
1196 1196
     {
1197
-        if (! is_array($query_params)) {
1197
+        if ( ! is_array($query_params)) {
1198 1198
             EE_Error::doing_it_wrong(
1199 1199
                 'EEM_Base::get_one',
1200 1200
                 sprintf(
@@ -1394,7 +1394,7 @@  discard block
 block discarded – undo
1394 1394
                 return [];
1395 1395
             }
1396 1396
         }
1397
-        if (! is_array($query_params)) {
1397
+        if ( ! is_array($query_params)) {
1398 1398
             EE_Error::doing_it_wrong(
1399 1399
                 'EEM_Base::_get_consecutive',
1400 1400
                 sprintf(
@@ -1406,10 +1406,10 @@  discard block
 block discarded – undo
1406 1406
             $query_params = [];
1407 1407
         }
1408 1408
         // let's add the where query param for consecutive look up.
1409
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1409
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1410 1410
         $query_params['limit']                 = $limit;
1411 1411
         // set direction
1412
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1412
+        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1413 1413
         $query_params['order_by'] = $operand === '>'
1414 1414
             ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1415 1415
             : [$field_to_order_by => 'DESC'] + $incoming_orderby;
@@ -1493,7 +1493,7 @@  discard block
 block discarded – undo
1493 1493
     {
1494 1494
         $field_settings = $this->field_settings_for($field_name);
1495 1495
         // if not a valid EE_Datetime_Field then throw error
1496
-        if (! $field_settings instanceof EE_Datetime_Field) {
1496
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1497 1497
             throw new EE_Error(
1498 1498
                 sprintf(
1499 1499
                     esc_html__(
@@ -1650,7 +1650,7 @@  discard block
 block discarded – undo
1650 1650
      */
1651 1651
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652 1652
     {
1653
-        if (! is_array($query_params)) {
1653
+        if ( ! is_array($query_params)) {
1654 1654
             EE_Error::doing_it_wrong(
1655 1655
                 'EEM_Base::update',
1656 1656
                 sprintf(
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
          * @param array    $query_params
1680 1680
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1681 1681
          */
1682
-        $fields_n_values = (array)apply_filters(
1682
+        $fields_n_values = (array) apply_filters(
1683 1683
             'FHEE__EEM_Base__update__fields_n_values',
1684 1684
             $fields_n_values,
1685 1685
             $this,
@@ -1697,10 +1697,10 @@  discard block
 block discarded – undo
1697 1697
         $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1698 1698
         foreach ($wpdb_select_results as $wpdb_result) {
1699 1699
             // type cast stdClass as array
1700
-            $wpdb_result = (array)$wpdb_result;
1700
+            $wpdb_result = (array) $wpdb_result;
1701 1701
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1702 1702
             if ($this->has_primary_key_field()) {
1703
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1703
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1704 1704
             } else {
1705 1705
                 // 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)
1706 1706
                 $main_table_pk_value = null;
@@ -1716,7 +1716,7 @@  discard block
 block discarded – undo
1716 1716
                     // in this table, right? so insert a row in the current table, using any fields available
1717 1717
                     if (
1718 1718
                     ! (array_key_exists($this_table_pk_column, $wpdb_result)
1719
-                       && $wpdb_result[ $this_table_pk_column ])
1719
+                       && $wpdb_result[$this_table_pk_column])
1720 1720
                     ) {
1721 1721
                         $success = $this->_insert_into_specific_table(
1722 1722
                             $table_obj,
@@ -1724,7 +1724,7 @@  discard block
 block discarded – undo
1724 1724
                             $main_table_pk_value
1725 1725
                         );
1726 1726
                         // if we died here, report the error
1727
-                        if (! $success) {
1727
+                        if ( ! $success) {
1728 1728
                             return false;
1729 1729
                         }
1730 1730
                     }
@@ -1746,10 +1746,10 @@  discard block
 block discarded – undo
1746 1746
                 $model_objs_affected_ids     = [];
1747 1747
                 foreach ($models_affected_key_columns as $row) {
1748 1748
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1749
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1749
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1750 1750
                 }
1751 1751
             }
1752
-            if (! $model_objs_affected_ids) {
1752
+            if ( ! $model_objs_affected_ids) {
1753 1753
                 // wait wait wait- if nothing was affected let's stop here
1754 1754
                 return 0;
1755 1755
             }
@@ -1772,11 +1772,11 @@  discard block
 block discarded – undo
1772 1772
             }
1773 1773
         }
1774 1774
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1776
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1775
+        $SQL              = "UPDATE ".$model_query_info->get_full_join_sql()
1776
+                            . " SET ".$this->_construct_update_sql($fields_n_values)
1777 1777
                             . $model_query_info->get_where_sql();
1778 1778
         // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1779
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1779
+        $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1780 1780
         /**
1781 1781
          * Action called after a model update call has been made.
1782 1782
          *
@@ -1787,7 +1787,7 @@  discard block
 block discarded – undo
1787 1787
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1788 1788
          */
1789 1789
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1790
-        return $rows_affected;// how many supposedly got updated
1790
+        return $rows_affected; // how many supposedly got updated
1791 1791
     }
1792 1792
 
1793 1793
 
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
         }
1818 1818
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1819 1819
         $select_expressions = $field->get_qualified_column();
1820
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1820
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1821 1821
         return $this->_do_wpdb_query('get_col', [$SQL]);
1822 1822
     }
1823 1823
 
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
     {
1838 1838
         $query_params['limit'] = 1;
1839 1839
         $col                   = $this->get_col($query_params, $field_to_select);
1840
-        if (! empty($col)) {
1840
+        if ( ! empty($col)) {
1841 1841
             return reset($col);
1842 1842
         }
1843 1843
         return null;
@@ -1867,7 +1867,7 @@  discard block
 block discarded – undo
1867 1867
             $value_sql       = $prepared_value === null
1868 1868
                 ? 'NULL'
1869 1869
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1870
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1870
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1871 1871
         }
1872 1872
         return implode(",", $cols_n_values);
1873 1873
     }
@@ -1997,9 +1997,9 @@  discard block
 block discarded – undo
1997 1997
         if ($deletion_where_query_part) {
1998 1998
             $model_query_info = $this->_create_model_query_info_carrier($query_params);
1999 1999
             $table_aliases    = implode(', ', array_keys($this->_tables));
2000
-            $SQL              = "DELETE " . $table_aliases
2001
-                                . " FROM " . $model_query_info->get_full_join_sql()
2002
-                                . " WHERE " . $deletion_where_query_part;
2000
+            $SQL              = "DELETE ".$table_aliases
2001
+                                . " FROM ".$model_query_info->get_full_join_sql()
2002
+                                . " WHERE ".$deletion_where_query_part;
2003 2003
             $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2004 2004
         } else {
2005 2005
             $rows_deleted = 0;
@@ -2010,12 +2010,12 @@  discard block
 block discarded – undo
2010 2010
         if (
2011 2011
             $this->has_primary_key_field()
2012 2012
             && $rows_deleted !== false
2013
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2013
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2014 2014
         ) {
2015
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2015
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2016 2016
             foreach ($ids_for_removal as $id) {
2017
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2018
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2017
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2018
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2019 2019
                 }
2020 2020
             }
2021 2021
 
@@ -2055,7 +2055,7 @@  discard block
 block discarded – undo
2055 2055
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2056 2056
          */
2057 2057
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;// how many supposedly got deleted
2058
+        return $rows_deleted; // how many supposedly got deleted
2059 2059
     }
2060 2060
 
2061 2061
 
@@ -2151,15 +2151,15 @@  discard block
 block discarded – undo
2151 2151
                 if (
2152 2152
                     $allow_blocking
2153 2153
                     && $this->delete_is_blocked_by_related_models(
2154
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2154
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2155 2155
                     )
2156 2156
                 ) {
2157 2157
                     continue;
2158 2158
                 }
2159 2159
                 // primary table deletes
2160
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2161
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2162
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2160
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2161
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2162
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2163 2163
                 }
2164 2164
             }
2165 2165
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2168,8 +2168,8 @@  discard block
 block discarded – undo
2168 2168
                 $ids_to_delete_indexed_by_column_for_row = [];
2169 2169
                 foreach ($fields as $cpk_field) {
2170 2170
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2171
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2172
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2171
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2172
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2173 2173
                     }
2174 2174
                 }
2175 2175
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2209,7 +2209,7 @@  discard block
 block discarded – undo
2209 2209
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210 2210
                 // make sure we have unique $ids
2211 2211
                 $ids     = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2212
+                $query[] = $column.' IN('.implode(',', $ids).')';
2213 2213
             }
2214 2214
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215 2215
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218 2218
                 $values_for_each_combined_primary_key_for_a_row = [];
2219 2219
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2220
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2221 2221
                 }
2222 2222
                 $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2223 2223
                 $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
@@ -2290,10 +2290,10 @@  discard block
 block discarded – undo
2290 2290
                 $column_to_count = '*';
2291 2291
             }
2292 2292
         }
2293
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2294 2294
         $SQL             =
2295
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2295
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2296
+        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2297 2297
     }
2298 2298
 
2299 2299
 
@@ -2316,7 +2316,7 @@  discard block
 block discarded – undo
2316 2316
             $field_obj = $this->get_primary_key_field();
2317 2317
         }
2318 2318
         $column_to_count = $field_obj->get_qualified_column();
2319
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2319
+        $SQL             = "SELECT SUM(".$column_to_count.")"
2320 2320
                            . $this->_construct_2nd_half_of_select_query($model_query_info);
2321 2321
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2322 2322
         // $data_type       = $field_obj->get_wpdb_data_type();
@@ -2324,7 +2324,7 @@  discard block
 block discarded – undo
2324 2324
         //     return (float)$return_value;
2325 2325
         // }
2326 2326
         // must be %f
2327
-        return (float)$return_value;
2327
+        return (float) $return_value;
2328 2328
     }
2329 2329
 
2330 2330
 
@@ -2344,7 +2344,7 @@  discard block
 block discarded – undo
2344 2344
         // if we're in maintenance mode level 2, DON'T run any queries
2345 2345
         // because level 2 indicates the database needs updating and
2346 2346
         // is probably out of sync with the code
2347
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2347
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2348 2348
             throw new EE_Error(
2349 2349
                 esc_html__(
2350 2350
                     '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.',
@@ -2353,7 +2353,7 @@  discard block
 block discarded – undo
2353 2353
             );
2354 2354
         }
2355 2355
         global $wpdb;
2356
-        if (! method_exists($wpdb, $wpdb_method)) {
2356
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2357 2357
             throw new EE_Error(
2358 2358
                 sprintf(
2359 2359
                     esc_html__(
@@ -2372,7 +2372,7 @@  discard block
 block discarded – undo
2372 2372
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2373 2373
         if (WP_DEBUG) {
2374 2374
             $wpdb->show_errors($old_show_errors_value);
2375
-            if (! empty($wpdb->last_error)) {
2375
+            if ( ! empty($wpdb->last_error)) {
2376 2376
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2377 2377
             }
2378 2378
             if ($result === false) {
@@ -2443,7 +2443,7 @@  discard block
 block discarded – undo
2443 2443
                     // ummmm... you in trouble
2444 2444
                     return $result;
2445 2445
             }
2446
-            if (! empty($error_message)) {
2446
+            if ( ! empty($error_message)) {
2447 2447
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2448 2448
                 trigger_error($error_message);
2449 2449
             }
@@ -2522,11 +2522,11 @@  discard block
 block discarded – undo
2522 2522
      */
2523 2523
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2524 2524
     {
2525
-        return " FROM " . $model_query_info->get_full_join_sql() .
2526
-               $model_query_info->get_where_sql() .
2527
-               $model_query_info->get_group_by_sql() .
2528
-               $model_query_info->get_having_sql() .
2529
-               $model_query_info->get_order_by_sql() .
2525
+        return " FROM ".$model_query_info->get_full_join_sql().
2526
+               $model_query_info->get_where_sql().
2527
+               $model_query_info->get_group_by_sql().
2528
+               $model_query_info->get_having_sql().
2529
+               $model_query_info->get_order_by_sql().
2530 2530
                $model_query_info->get_limit_sql();
2531 2531
     }
2532 2532
 
@@ -2719,12 +2719,12 @@  discard block
 block discarded – undo
2719 2719
         $related_model = $this->get_related_model_obj($model_name);
2720 2720
         // we're just going to use the query params on the related model's normal get_all query,
2721 2721
         // except add a condition to say to match the current mod
2722
-        if (! isset($query_params['default_where_conditions'])) {
2722
+        if ( ! isset($query_params['default_where_conditions'])) {
2723 2723
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2724 2724
         }
2725 2725
         $this_model_name                                                 = $this->get_this_model_name();
2726 2726
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2727
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2727
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2728 2728
         return $related_model->count($query_params, $field_to_count, $distinct);
2729 2729
     }
2730 2730
 
@@ -2745,7 +2745,7 @@  discard block
 block discarded – undo
2745 2745
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2746 2746
     {
2747 2747
         $related_model = $this->get_related_model_obj($model_name);
2748
-        if (! is_array($query_params)) {
2748
+        if ( ! is_array($query_params)) {
2749 2749
             EE_Error::doing_it_wrong(
2750 2750
                 'EEM_Base::sum_related',
2751 2751
                 sprintf(
@@ -2758,12 +2758,12 @@  discard block
 block discarded – undo
2758 2758
         }
2759 2759
         // we're just going to use the query params on the related model's normal get_all query,
2760 2760
         // except add a condition to say to match the current mod
2761
-        if (! isset($query_params['default_where_conditions'])) {
2761
+        if ( ! isset($query_params['default_where_conditions'])) {
2762 2762
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2763 2763
         }
2764 2764
         $this_model_name                                                 = $this->get_this_model_name();
2765 2765
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2766
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2766
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2767 2767
         return $related_model->sum($query_params, $field_to_sum);
2768 2768
     }
2769 2769
 
@@ -2815,7 +2815,7 @@  discard block
 block discarded – undo
2815 2815
                 $field_with_model_name = $field;
2816 2816
             }
2817 2817
         }
2818
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2818
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2819 2819
             throw new EE_Error(
2820 2820
                 sprintf(
2821 2821
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2852,7 +2852,7 @@  discard block
 block discarded – undo
2852 2852
          * @param array    $fields_n_values keys are the fields and values are their new values
2853 2853
          * @param EEM_Base $model           the model used
2854 2854
          */
2855
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2855
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2856 2856
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2857 2857
             $main_table = $this->_get_main_table();
2858 2858
             $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2954,14 +2954,14 @@  discard block
 block discarded – undo
2954 2954
                 || $this->get_primary_key_field()
2955 2955
                    instanceof
2956 2956
                    EE_Primary_Key_String_Field)
2957
-            && isset($fields_n_values[ $this->primary_key_name() ])
2957
+            && isset($fields_n_values[$this->primary_key_name()])
2958 2958
         ) {
2959
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2959
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2960 2960
         }
2961 2961
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2962 2962
             $uniqueness_where_params                              =
2963 2963
                 array_intersect_key($fields_n_values, $unique_index->fields());
2964
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2964
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2965 2965
         }
2966 2966
         // if there is nothing to base this search on, then we shouldn't find anything
2967 2967
         if (empty($query_params)) {
@@ -3039,16 +3039,16 @@  discard block
 block discarded – undo
3039 3039
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3040 3040
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3041 3041
             if ($prepared_value !== null) {
3042
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3042
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3043 3043
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3044 3044
             }
3045 3045
         }
3046 3046
         if ($table instanceof EE_Secondary_Table && $new_id) {
3047 3047
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3048 3048
             // so add the fk to the main table as a column
3049
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3049
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3050 3050
             $format_for_insertion[]                              =
3051
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3051
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3052 3052
         }
3053 3053
         // insert the new entry
3054 3054
         $result = $this->_do_wpdb_query(
@@ -3065,7 +3065,7 @@  discard block
 block discarded – undo
3065 3065
             }
3066 3066
             // it's not an auto-increment primary key, so
3067 3067
             // it must have been supplied
3068
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3068
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3069 3069
         }
3070 3070
         // we can't return a  primary key because there is none. instead return
3071 3071
         // a unique string indicating this model
@@ -3089,14 +3089,14 @@  discard block
 block discarded – undo
3089 3089
         if (
3090 3090
             ! $field_obj->is_nullable()
3091 3091
             && (
3092
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3093
-                || $fields_n_values[ $field_obj->get_name() ] === null
3092
+                ! isset($fields_n_values[$field_obj->get_name()])
3093
+                || $fields_n_values[$field_obj->get_name()] === null
3094 3094
             )
3095 3095
         ) {
3096
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3096
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3097 3097
         }
3098
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3099
-            ? $fields_n_values[ $field_obj->get_name() ]
3098
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3099
+            ? $fields_n_values[$field_obj->get_name()]
3100 3100
             : null;
3101 3101
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3102 3102
     }
@@ -3197,7 +3197,7 @@  discard block
 block discarded – undo
3197 3197
      */
3198 3198
     public function get_table_obj_by_alias($table_alias = '')
3199 3199
     {
3200
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3200
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3201 3201
     }
3202 3202
 
3203 3203
 
@@ -3211,7 +3211,7 @@  discard block
 block discarded – undo
3211 3211
         $other_tables = [];
3212 3212
         foreach ($this->_tables as $table_alias => $table) {
3213 3213
             if ($table instanceof EE_Secondary_Table) {
3214
-                $other_tables[ $table_alias ] = $table;
3214
+                $other_tables[$table_alias] = $table;
3215 3215
             }
3216 3216
         }
3217 3217
         return $other_tables;
@@ -3226,7 +3226,7 @@  discard block
 block discarded – undo
3226 3226
      */
3227 3227
     public function _get_fields_for_table($table_alias)
3228 3228
     {
3229
-        return $this->_fields[ $table_alias ];
3229
+        return $this->_fields[$table_alias];
3230 3230
     }
3231 3231
 
3232 3232
 
@@ -3255,7 +3255,7 @@  discard block
 block discarded – undo
3255 3255
                     $query_info_carrier,
3256 3256
                     'group_by'
3257 3257
                 );
3258
-            } elseif (! empty($query_params['group_by'])) {
3258
+            } elseif ( ! empty($query_params['group_by'])) {
3259 3259
                 $this->_extract_related_model_info_from_query_param(
3260 3260
                     $query_params['group_by'],
3261 3261
                     $query_info_carrier,
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
                     $query_info_carrier,
3278 3278
                     'order_by'
3279 3279
                 );
3280
-            } elseif (! empty($query_params['order_by'])) {
3280
+            } elseif ( ! empty($query_params['order_by'])) {
3281 3281
                 $this->_extract_related_model_info_from_query_param(
3282 3282
                     $query_params['order_by'],
3283 3283
                     $query_info_carrier,
@@ -3311,8 +3311,8 @@  discard block
 block discarded – undo
3311 3311
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312 3312
         $query_param_type
3313 3313
     ) {
3314
-        if (! empty($sub_query_params)) {
3315
-            $sub_query_params = (array)$sub_query_params;
3314
+        if ( ! empty($sub_query_params)) {
3315
+            $sub_query_params = (array) $sub_query_params;
3316 3316
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3317 3317
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3318 3318
                 $this->_extract_related_model_info_from_query_param(
@@ -3327,7 +3327,7 @@  discard block
 block discarded – undo
3327 3327
                 $query_param_sans_stars =
3328 3328
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3329 3329
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3330
-                    if (! is_array($possibly_array_of_params)) {
3330
+                    if ( ! is_array($possibly_array_of_params)) {
3331 3331
                         throw new EE_Error(
3332 3332
                             sprintf(
3333 3333
                                 esc_html__(
@@ -3353,7 +3353,7 @@  discard block
 block discarded – undo
3353 3353
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3354 3354
                     // indicating that $possible_array_of_params[1] is actually a field name,
3355 3355
                     // from which we should extract query parameters!
3356
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3356
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3357 3357
                         throw new EE_Error(
3358 3358
                             sprintf(
3359 3359
                                 esc_html__(
@@ -3391,8 +3391,8 @@  discard block
 block discarded – undo
3391 3391
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392 3392
         $query_param_type
3393 3393
     ) {
3394
-        if (! empty($sub_query_params)) {
3395
-            if (! is_array($sub_query_params)) {
3394
+        if ( ! empty($sub_query_params)) {
3395
+            if ( ! is_array($sub_query_params)) {
3396 3396
                 throw new EE_Error(
3397 3397
                     sprintf(
3398 3398
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3429,7 +3429,7 @@  discard block
 block discarded – undo
3429 3429
      */
3430 3430
     public function _create_model_query_info_carrier($query_params)
3431 3431
     {
3432
-        if (! is_array($query_params)) {
3432
+        if ( ! is_array($query_params)) {
3433 3433
             EE_Error::doing_it_wrong(
3434 3434
                 'EEM_Base::_create_model_query_info_carrier',
3435 3435
                 sprintf(
@@ -3462,7 +3462,7 @@  discard block
 block discarded – undo
3462 3462
             // only include if related to a cpt where no password has been set
3463 3463
             $query_params[0]['OR*nopassword'] = [
3464 3464
                 $where_param_key_for_password       => '',
3465
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3465
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3466 3466
             ];
3467 3467
         }
3468 3468
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3516,7 +3516,7 @@  discard block
 block discarded – undo
3516 3516
         // set limit
3517 3517
         if (array_key_exists('limit', $query_params)) {
3518 3518
             if (is_array($query_params['limit'])) {
3519
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3520 3520
                     $e = sprintf(
3521 3521
                         esc_html__(
3522 3522
                             "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)",
@@ -3524,12 +3524,12 @@  discard block
 block discarded – undo
3524 3524
                         ),
3525 3525
                         http_build_query($query_params['limit'])
3526 3526
                     );
3527
-                    throw new EE_Error($e . "|" . $e);
3527
+                    throw new EE_Error($e."|".$e);
3528 3528
                 }
3529 3529
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3531
-            } elseif (! empty($query_params['limit'])) {
3532
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3530
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3531
+            } elseif ( ! empty($query_params['limit'])) {
3532
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3533 3533
             }
3534 3534
         }
3535 3535
         // set order by
@@ -3561,10 +3561,10 @@  discard block
 block discarded – undo
3561 3561
                 $order_array = [];
3562 3562
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3563 3563
                     $order         = $this->_extract_order($order);
3564
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3564
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3565 3565
                 }
3566
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3567
-            } elseif (! empty($query_params['order_by'])) {
3566
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3567
+            } elseif ( ! empty($query_params['order_by'])) {
3568 3568
                 $this->_extract_related_model_info_from_query_param(
3569 3569
                     $query_params['order_by'],
3570 3570
                     $query_object,
@@ -3575,7 +3575,7 @@  discard block
 block discarded – undo
3575 3575
                     ? $this->_extract_order($query_params['order'])
3576 3576
                     : 'DESC';
3577 3577
                 $query_object->set_order_by_sql(
3578
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3578
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3579 3579
                 );
3580 3580
             }
3581 3581
         }
@@ -3587,7 +3587,7 @@  discard block
 block discarded – undo
3587 3587
         ) {
3588 3588
             $pk_field = $this->get_primary_key_field();
3589 3589
             $order    = $this->_extract_order($query_params['order']);
3590
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3590
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3591 3591
         }
3592 3592
         // set group by
3593 3593
         if (array_key_exists('group_by', $query_params)) {
@@ -3597,10 +3597,10 @@  discard block
 block discarded – undo
3597 3597
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3598 3598
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3599 3599
                 }
3600
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3601
-            } elseif (! empty($query_params['group_by'])) {
3600
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3601
+            } elseif ( ! empty($query_params['group_by'])) {
3602 3602
                 $query_object->set_group_by_sql(
3603
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3603
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3604 3604
                 );
3605 3605
             }
3606 3606
         }
@@ -3610,7 +3610,7 @@  discard block
 block discarded – undo
3610 3610
         }
3611 3611
         // now, just verify they didn't pass anything wack
3612 3612
         foreach ($query_params as $query_key => $query_value) {
3613
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3613
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3614 3614
                 throw new EE_Error(
3615 3615
                     sprintf(
3616 3616
                         esc_html__(
@@ -3714,7 +3714,7 @@  discard block
 block discarded – undo
3714 3714
         $where_query_params = []
3715 3715
     ) {
3716 3716
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3717
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3717
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3718 3718
             throw new EE_Error(
3719 3719
                 sprintf(
3720 3720
                     esc_html__(
@@ -3744,7 +3744,7 @@  discard block
 block discarded – undo
3744 3744
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3745 3745
                 continue;
3746 3746
             }
3747
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3747
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3748 3748
                 $related_model_universal_where_params,
3749 3749
                 $where_query_params,
3750 3750
                 $related_model,
@@ -3853,19 +3853,19 @@  discard block
 block discarded – undo
3853 3853
     ) {
3854 3854
         $null_friendly_where_conditions = [];
3855 3855
         $none_overridden                = true;
3856
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3856
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3857 3857
         foreach ($default_where_conditions as $key => $val) {
3858
-            if (isset($provided_where_conditions[ $key ])) {
3858
+            if (isset($provided_where_conditions[$key])) {
3859 3859
                 $none_overridden = false;
3860 3860
             } else {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3862 3862
             }
3863 3863
         }
3864 3864
         if ($none_overridden && $default_where_conditions) {
3865 3865
             if ($model->has_primary_key_field()) {
3866
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3866
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3867 3867
                                                                                    . "."
3868
-                                                                                   . $model->primary_key_name() ] =
3868
+                                                                                   . $model->primary_key_name()] =
3869 3869
                     ['IS NULL'];
3870 3870
             }/*else{
3871 3871
                 //@todo NO PK, use other defaults
@@ -3974,7 +3974,7 @@  discard block
 block discarded – undo
3974 3974
             foreach ($tables as $table_obj) {
3975 3975
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3976 3976
                                        . $table_obj->get_fully_qualified_pk_column();
3977
-                if (! in_array($qualified_pk_column, $selects)) {
3977
+                if ( ! in_array($qualified_pk_column, $selects)) {
3978 3978
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3979 3979
                 }
3980 3980
             }
@@ -4126,9 +4126,9 @@  discard block
 block discarded – undo
4126 4126
         $query_parameter_type
4127 4127
     ) {
4128 4128
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4129
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4129
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4130 4130
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4131
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4131
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4132 4132
                 if ($possible_join_string === '') {
4133 4133
                     // nothing left to $query_param
4134 4134
                     // we should actually end in a field name, not a model like this!
@@ -4260,7 +4260,7 @@  discard block
 block discarded – undo
4260 4260
     {
4261 4261
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4262 4262
         if ($SQL) {
4263
-            return " WHERE " . $SQL;
4263
+            return " WHERE ".$SQL;
4264 4264
         }
4265 4265
         return '';
4266 4266
     }
@@ -4278,7 +4278,7 @@  discard block
 block discarded – undo
4278 4278
     {
4279 4279
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4280 4280
         if ($SQL) {
4281
-            return " HAVING " . $SQL;
4281
+            return " HAVING ".$SQL;
4282 4282
         }
4283 4283
         return '';
4284 4284
     }
@@ -4301,7 +4301,7 @@  discard block
 block discarded – undo
4301 4301
             $query_param =
4302 4302
                 $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4303 4303
                     $query_param
4304
-                );// str_replace("*",'',$query_param);
4304
+                ); // str_replace("*",'',$query_param);
4305 4305
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4306 4306
                 switch ($query_param) {
4307 4307
                     case 'not':
@@ -4335,7 +4335,7 @@  discard block
 block discarded – undo
4335 4335
             } else {
4336 4336
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4337 4337
                 // if it's not a normal field, maybe it's a custom selection?
4338
-                if (! $field_obj) {
4338
+                if ( ! $field_obj) {
4339 4339
                     if ($this->_custom_selections instanceof CustomSelects) {
4340 4340
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4341 4341
                     } else {
@@ -4351,7 +4351,7 @@  discard block
 block discarded – undo
4351 4351
                     }
4352 4352
                 }
4353 4353
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4354
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4354
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4355 4355
             }
4356 4356
         }
4357 4357
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4373,7 +4373,7 @@  discard block
 block discarded – undo
4373 4373
                 $field->get_model_name(),
4374 4374
                 $query_param
4375 4375
             );
4376
-            return $table_alias_prefix . $field->get_qualified_column();
4376
+            return $table_alias_prefix.$field->get_qualified_column();
4377 4377
         }
4378 4378
         if (
4379 4379
             $this->_custom_selections instanceof CustomSelects
@@ -4430,7 +4430,7 @@  discard block
 block discarded – undo
4430 4430
     {
4431 4431
         if (is_array($op_and_value)) {
4432 4432
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4433
-            if (! $operator) {
4433
+            if ( ! $operator) {
4434 4434
                 $php_array_like_string = [];
4435 4435
                 foreach ($op_and_value as $key => $value) {
4436 4436
                     $php_array_like_string[] = "$key=>$value";
@@ -4452,14 +4452,14 @@  discard block
 block discarded – undo
4452 4452
         }
4453 4453
         // check to see if the value is actually another field
4454 4454
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4455
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4455
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4456 4456
         }
4457 4457
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4458 4458
             // in this case, the value should be an array, or at least a comma-separated list
4459 4459
             // it will need to handle a little differently
4460 4460
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4461 4461
             // note: $cleaned_value has already been run through $wpdb->prepare()
4462
-            return $operator . SP . $cleaned_value;
4462
+            return $operator.SP.$cleaned_value;
4463 4463
         }
4464 4464
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4465 4465
             // the value should be an array with count of two.
@@ -4475,7 +4475,7 @@  discard block
 block discarded – undo
4475 4475
                 );
4476 4476
             }
4477 4477
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4478
-            return $operator . SP . $cleaned_value;
4478
+            return $operator.SP.$cleaned_value;
4479 4479
         }
4480 4480
         if (in_array($operator, $this->valid_null_style_operators())) {
4481 4481
             if ($value !== null) {
@@ -4495,10 +4495,10 @@  discard block
 block discarded – undo
4495 4495
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4496 4496
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4497 4497
             // remove other junk. So just treat it as a string.
4498
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4498
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4499 4499
         }
4500
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4500
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4502 4502
         }
4503 4503
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4504 4504
             throw new EE_Error(
@@ -4512,7 +4512,7 @@  discard block
 block discarded – undo
4512 4512
                 )
4513 4513
             );
4514 4514
         }
4515
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4515
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4516 4516
             throw new EE_Error(
4517 4517
                 sprintf(
4518 4518
                     esc_html__(
@@ -4551,7 +4551,7 @@  discard block
 block discarded – undo
4551 4551
         foreach ($values as $value) {
4552 4552
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4553 4553
         }
4554
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4554
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4555 4555
     }
4556 4556
 
4557 4557
 
@@ -4591,7 +4591,7 @@  discard block
 block discarded – undo
4591 4591
                                 . $main_table->get_table_name()
4592 4592
                                 . " WHERE FALSE";
4593 4593
         }
4594
-        return "(" . implode(",", $cleaned_values) . ")";
4594
+        return "(".implode(",", $cleaned_values).")";
4595 4595
     }
4596 4596
 
4597 4597
 
@@ -4610,7 +4610,7 @@  discard block
 block discarded – undo
4610 4610
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4611 4611
             );
4612 4612
         } //$field_obj should really just be a data type
4613
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4613
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4614 4614
             throw new EE_Error(
4615 4615
                 sprintf(
4616 4616
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4647,12 +4647,12 @@  discard block
 block discarded – undo
4647 4647
             );
4648 4648
         }
4649 4649
         $number_of_parts       = count($query_param_parts);
4650
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4650
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4651 4651
         $field_name = $last_query_param_part;
4652 4652
         $model_obj  = $number_of_parts === 1
4653 4653
             ? $this
4654 4654
             // $number_of_parts >= 2, the last part is the column name, and there are only 2parts. therefore...
4655
-            : $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4655
+            : $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4656 4656
         try {
4657 4657
             return $model_obj->field_settings_for($field_name);
4658 4658
         } catch (EE_Error $e) {
@@ -4672,7 +4672,7 @@  discard block
 block discarded – undo
4672 4672
     public function _get_qualified_column_for_field($field_name)
4673 4673
     {
4674 4674
         $all_fields = $this->field_settings();
4675
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4675
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4676 4676
         if ($field) {
4677 4677
             return $field->get_qualified_column();
4678 4678
         }
@@ -4742,10 +4742,10 @@  discard block
 block discarded – undo
4742 4742
      */
4743 4743
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4744 4744
     {
4745
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4745
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4746 4746
         $qualified_columns = [];
4747 4747
         foreach ($this->field_settings() as $field) {
4748
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4748
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4749 4749
         }
4750 4750
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4751 4751
     }
@@ -4769,11 +4769,11 @@  discard block
 block discarded – undo
4769 4769
             if ($table_obj instanceof EE_Primary_Table) {
4770 4770
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4771 4771
                     ? $table_obj->get_select_join_limit($limit)
4772
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4772
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4773 4773
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4774 4774
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4775 4775
                     ? $table_obj->get_select_join_limit_join($limit)
4776
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4776
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4777 4777
             }
4778 4778
         }
4779 4779
         return $SQL;
@@ -4843,7 +4843,7 @@  discard block
 block discarded – undo
4843 4843
         foreach ($this->field_settings() as $field_obj) {
4844 4844
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4845 4845
             /** @var $field_obj EE_Model_Field_Base */
4846
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4846
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4847 4847
         }
4848 4848
         return $data_types;
4849 4849
     }
@@ -4858,8 +4858,8 @@  discard block
 block discarded – undo
4858 4858
      */
4859 4859
     public function get_related_model_obj($model_name)
4860 4860
     {
4861
-        $model_classname = "EEM_" . $model_name;
4862
-        if (! class_exists($model_classname)) {
4861
+        $model_classname = "EEM_".$model_name;
4862
+        if ( ! class_exists($model_classname)) {
4863 4863
             throw new EE_Error(
4864 4864
                 sprintf(
4865 4865
                     esc_html__(
@@ -4871,7 +4871,7 @@  discard block
 block discarded – undo
4871 4871
                 )
4872 4872
             );
4873 4873
         }
4874
-        return call_user_func($model_classname . "::instance");
4874
+        return call_user_func($model_classname."::instance");
4875 4875
     }
4876 4876
 
4877 4877
 
@@ -4898,7 +4898,7 @@  discard block
 block discarded – undo
4898 4898
         $belongs_to_relations = [];
4899 4899
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4900 4900
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4901
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4901
+                $belongs_to_relations[$model_name] = $relation_obj;
4902 4902
             }
4903 4903
         }
4904 4904
         return $belongs_to_relations;
@@ -4915,7 +4915,7 @@  discard block
 block discarded – undo
4915 4915
     public function related_settings_for($relation_name)
4916 4916
     {
4917 4917
         $relatedModels = $this->relation_settings();
4918
-        if (! array_key_exists($relation_name, $relatedModels)) {
4918
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4919 4919
             throw new EE_Error(
4920 4920
                 sprintf(
4921 4921
                     esc_html__(
@@ -4928,7 +4928,7 @@  discard block
 block discarded – undo
4928 4928
                 )
4929 4929
             );
4930 4930
         }
4931
-        return $relatedModels[ $relation_name ];
4931
+        return $relatedModels[$relation_name];
4932 4932
     }
4933 4933
 
4934 4934
 
@@ -4944,7 +4944,7 @@  discard block
 block discarded – undo
4944 4944
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4945 4945
     {
4946 4946
         $fieldSettings = $this->field_settings($include_db_only_fields);
4947
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4947
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4948 4948
             throw new EE_Error(
4949 4949
                 sprintf(
4950 4950
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4953,7 +4953,7 @@  discard block
 block discarded – undo
4953 4953
                 )
4954 4954
             );
4955 4955
         }
4956
-        return $fieldSettings[ $fieldName ];
4956
+        return $fieldSettings[$fieldName];
4957 4957
     }
4958 4958
 
4959 4959
 
@@ -4966,7 +4966,7 @@  discard block
 block discarded – undo
4966 4966
     public function has_field($fieldName)
4967 4967
     {
4968 4968
         $fieldSettings = $this->field_settings(true);
4969
-        if (isset($fieldSettings[ $fieldName ])) {
4969
+        if (isset($fieldSettings[$fieldName])) {
4970 4970
             return true;
4971 4971
         }
4972 4972
         return false;
@@ -4982,7 +4982,7 @@  discard block
 block discarded – undo
4982 4982
     public function has_relation($relation_name)
4983 4983
     {
4984 4984
         $relations = $this->relation_settings();
4985
-        if (isset($relations[ $relation_name ])) {
4985
+        if (isset($relations[$relation_name])) {
4986 4986
             return true;
4987 4987
         }
4988 4988
         return false;
@@ -5018,7 +5018,7 @@  discard block
 block discarded – undo
5018 5018
                     break;
5019 5019
                 }
5020 5020
             }
5021
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5021
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5022 5022
                 throw new EE_Error(
5023 5023
                     sprintf(
5024 5024
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5078,17 +5078,17 @@  discard block
 block discarded – undo
5078 5078
      */
5079 5079
     public function get_foreign_key_to($model_name)
5080 5080
     {
5081
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5081
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5082 5082
             foreach ($this->field_settings() as $field) {
5083 5083
                 if (
5084 5084
                     $field instanceof EE_Foreign_Key_Field_Base
5085 5085
                     && in_array($model_name, $field->get_model_names_pointed_to())
5086 5086
                 ) {
5087
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5087
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5088 5088
                     break;
5089 5089
                 }
5090 5090
             }
5091
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5091
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5092 5092
                 throw new EE_Error(
5093 5093
                     sprintf(
5094 5094
                         esc_html__(
@@ -5101,7 +5101,7 @@  discard block
 block discarded – undo
5101 5101
                 );
5102 5102
             }
5103 5103
         }
5104
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5104
+        return $this->_cache_foreign_key_to_fields[$model_name];
5105 5105
     }
5106 5106
 
5107 5107
 
@@ -5117,7 +5117,7 @@  discard block
 block discarded – undo
5117 5117
     {
5118 5118
         $table_alias_sans_model_relation_chain_prefix =
5119 5119
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5120
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5120
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5121 5121
     }
5122 5122
 
5123 5123
 
@@ -5135,7 +5135,7 @@  discard block
 block discarded – undo
5135 5135
                 $this->_cached_fields = [];
5136 5136
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5137 5137
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5138
+                        $this->_cached_fields[$field_name] = $field_obj;
5139 5139
                     }
5140 5140
                 }
5141 5141
             }
@@ -5146,8 +5146,8 @@  discard block
 block discarded – undo
5146 5146
             foreach ($this->_fields as $fields_corresponding_to_table) {
5147 5147
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148 5148
                     /** @var $field_obj EE_Model_Field_Base */
5149
-                    if (! $field_obj->is_db_only_field()) {
5150
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5149
+                    if ( ! $field_obj->is_db_only_field()) {
5150
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5151 5151
                     }
5152 5152
                 }
5153 5153
             }
@@ -5175,7 +5175,7 @@  discard block
 block discarded – undo
5175 5175
         $count_if_model_has_no_primary_key = 0;
5176 5176
         $has_primary_key                   = $this->has_primary_key_field();
5177 5177
         $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5178
-        foreach ((array)$rows as $row) {
5178
+        foreach ((array) $rows as $row) {
5179 5179
             if (empty($row)) {
5180 5180
                 // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5181 5181
                 return [];
@@ -5188,12 +5188,12 @@  discard block
 block discarded – undo
5188 5188
                     $primary_key_field->get_qualified_column(),
5189 5189
                     $primary_key_field->get_table_column()
5190 5190
                 );
5191
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5191
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5192 5192
                     continue;
5193 5193
                 }
5194 5194
             }
5195 5195
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5196
-            if (! $classInstance) {
5196
+            if ( ! $classInstance) {
5197 5197
                 throw new EE_Error(
5198 5198
                     sprintf(
5199 5199
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5206,7 +5206,7 @@  discard block
 block discarded – undo
5206 5206
             $classInstance->set_timezone($this->get_timezone(), true);
5207 5207
             // make sure if there is any timezone setting present that we set the timezone for the object
5208 5208
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5209
-            $array_of_objects[ $key ] = $classInstance;
5209
+            $array_of_objects[$key] = $classInstance;
5210 5210
             // also, for all the relations of type BelongsTo, see if we can cache
5211 5211
             // those related models
5212 5212
             // (we could do this for other relations too, but if there are conditions
@@ -5250,9 +5250,9 @@  discard block
 block discarded – undo
5250 5250
         $results = [];
5251 5251
         if ($this->_custom_selections instanceof CustomSelects) {
5252 5252
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5253
-                if (isset($db_results_row[ $alias ])) {
5254
-                    $results[ $alias ] = $this->convertValueToDataType(
5255
-                        $db_results_row[ $alias ],
5253
+                if (isset($db_results_row[$alias])) {
5254
+                    $results[$alias] = $this->convertValueToDataType(
5255
+                        $db_results_row[$alias],
5256 5256
                         $this->_custom_selections->getDataTypeForAlias($alias)
5257 5257
                     );
5258 5258
                 }
@@ -5273,11 +5273,11 @@  discard block
 block discarded – undo
5273 5273
     {
5274 5274
         switch ($datatype) {
5275 5275
             case '%f':
5276
-                return (float)$value;
5276
+                return (float) $value;
5277 5277
             case '%d':
5278
-                return (int)$value;
5278
+                return (int) $value;
5279 5279
             default:
5280
-                return (string)$value;
5280
+                return (string) $value;
5281 5281
         }
5282 5282
     }
5283 5283
 
@@ -5297,7 +5297,7 @@  discard block
 block discarded – undo
5297 5297
         $this_model_fields_and_values = [];
5298 5298
         // setup the row using default values;
5299 5299
         foreach ($this->field_settings() as $field_name => $field_obj) {
5300
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5300
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5301 5301
         }
5302 5302
         $className = $this->_get_class_name();
5303 5303
         return EE_Registry::instance()->load_class(
@@ -5318,20 +5318,20 @@  discard block
 block discarded – undo
5318 5318
      */
5319 5319
     public function instantiate_class_from_array_or_object($cols_n_values)
5320 5320
     {
5321
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5321
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5322 5322
             $cols_n_values = get_object_vars($cols_n_values);
5323 5323
         }
5324 5324
         $primary_key = null;
5325 5325
         // make sure the array only has keys that are fields/columns on this model
5326 5326
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5327
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5328
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5327
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5328
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5329 5329
         }
5330 5330
         $className = $this->_get_class_name();
5331 5331
         // check we actually found results that we can use to build our model object
5332 5332
         // if not, return null
5333 5333
         if ($this->has_primary_key_field()) {
5334
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5334
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5335 5335
                 return null;
5336 5336
             }
5337 5337
         } elseif ($this->unique_indexes()) {
@@ -5343,7 +5343,7 @@  discard block
 block discarded – undo
5343 5343
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5344 5344
         if ($primary_key) {
5345 5345
             $classInstance = $this->get_from_entity_map($primary_key);
5346
-            if (! $classInstance) {
5346
+            if ( ! $classInstance) {
5347 5347
                 $classInstance = EE_Registry::instance()->load_class(
5348 5348
                     $className,
5349 5349
                     [$this_model_fields_n_values, $this->get_timezone()],
@@ -5373,8 +5373,8 @@  discard block
 block discarded – undo
5373 5373
      */
5374 5374
     public function get_from_entity_map($id)
5375 5375
     {
5376
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5377
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5376
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5377
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id]
5378 5378
             : null;
5379 5379
     }
5380 5380
 
@@ -5397,7 +5397,7 @@  discard block
 block discarded – undo
5397 5397
     public function add_to_entity_map(EE_Base_Class $object)
5398 5398
     {
5399 5399
         $className = $this->_get_class_name();
5400
-        if (! $object instanceof $className) {
5400
+        if ( ! $object instanceof $className) {
5401 5401
             throw new EE_Error(
5402 5402
                 sprintf(
5403 5403
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5406,7 +5406,7 @@  discard block
 block discarded – undo
5406 5406
                 )
5407 5407
             );
5408 5408
         }
5409
-        if (! $object->ID()) {
5409
+        if ( ! $object->ID()) {
5410 5410
             throw new DomainException(
5411 5411
                 sprintf(
5412 5412
                     esc_html__(
@@ -5422,7 +5422,7 @@  discard block
 block discarded – undo
5422 5422
         if ($classInstance) {
5423 5423
             return $classInstance;
5424 5424
         }
5425
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5425
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5426 5426
         return $object;
5427 5427
     }
5428 5428
 
@@ -5437,11 +5437,11 @@  discard block
 block discarded – undo
5437 5437
     public function clear_entity_map($id = null)
5438 5438
     {
5439 5439
         if (empty($id)) {
5440
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5440
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5441 5441
             return true;
5442 5442
         }
5443
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5444
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5443
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5444
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5445 5445
             return true;
5446 5446
         }
5447 5447
         return false;
@@ -5486,18 +5486,18 @@  discard block
 block discarded – undo
5486 5486
             // there is a primary key on this table and its not set. Use defaults for all its columns
5487 5487
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5488 5488
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5489
-                    if (! $field_obj->is_db_only_field()) {
5489
+                    if ( ! $field_obj->is_db_only_field()) {
5490 5490
                         // prepare field as if its coming from db
5491 5491
                         $prepared_value                            =
5492 5492
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5493
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5493
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5494 5494
                     }
5495 5495
                 }
5496 5496
             } else {
5497 5497
                 // the table's rows existed. Use their values
5498 5498
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5499
-                    if (! $field_obj->is_db_only_field()) {
5500
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5499
+                    if ( ! $field_obj->is_db_only_field()) {
5500
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5501 5501
                             $cols_n_values,
5502 5502
                             $field_obj->get_qualified_column(),
5503 5503
                             $field_obj->get_table_column()
@@ -5524,17 +5524,17 @@  discard block
 block discarded – undo
5524 5524
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5525 5525
         // does the field on the model relate to this column retrieved from the db?
5526 5526
         // or is it a db-only field? (not relating to the model)
5527
-        if (isset($cols_n_values[ $qualified_column ])) {
5528
-            $value = $cols_n_values[ $qualified_column ];
5529
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5530
-            $value = $cols_n_values[ $regular_column ];
5531
-        } elseif (! empty($this->foreign_key_aliases)) {
5527
+        if (isset($cols_n_values[$qualified_column])) {
5528
+            $value = $cols_n_values[$qualified_column];
5529
+        } elseif (isset($cols_n_values[$regular_column])) {
5530
+            $value = $cols_n_values[$regular_column];
5531
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5532 5532
             // no PK?  ok check if there is a foreign key alias set for this table
5533 5533
             // then check if that alias exists in the incoming data
5534 5534
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5535 5535
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5536
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5537
-                    $value = $cols_n_values[ $FK_alias ];
5536
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5537
+                    $value = $cols_n_values[$FK_alias];
5538 5538
                     [$pk_class] = explode('.', $PK_column);
5539 5539
                     $pk_model_name = "EEM_{$pk_class}";
5540 5540
                     /** @var EEM_Base $pk_model */
@@ -5578,7 +5578,7 @@  discard block
 block discarded – undo
5578 5578
                     $obj_in_map->clear_cache($relation_name, null, true);
5579 5579
                 }
5580 5580
             }
5581
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5581
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5582 5582
             return $obj_in_map;
5583 5583
         }
5584 5584
         return $this->get_one_by_ID($id);
@@ -5630,7 +5630,7 @@  discard block
 block discarded – undo
5630 5630
      */
5631 5631
     private function _get_class_name()
5632 5632
     {
5633
-        return "EE_" . $this->get_this_model_name();
5633
+        return "EE_".$this->get_this_model_name();
5634 5634
     }
5635 5635
 
5636 5636
 
@@ -5644,7 +5644,7 @@  discard block
 block discarded – undo
5644 5644
      */
5645 5645
     public function item_name($quantity = 1)
5646 5646
     {
5647
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5647
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5648 5648
     }
5649 5649
 
5650 5650
 
@@ -5676,7 +5676,7 @@  discard block
 block discarded – undo
5676 5676
     {
5677 5677
         $className = get_class($this);
5678 5678
         $tagName   = "FHEE__{$className}__{$methodName}";
5679
-        if (! has_filter($tagName)) {
5679
+        if ( ! has_filter($tagName)) {
5680 5680
             throw new EE_Error(
5681 5681
                 sprintf(
5682 5682
                     esc_html__(
@@ -5845,7 +5845,7 @@  discard block
 block discarded – undo
5845 5845
         $unique_indexes = [];
5846 5846
         foreach ($this->_indexes as $name => $index) {
5847 5847
             if ($index instanceof EE_Unique_Index) {
5848
-                $unique_indexes [ $name ] = $index;
5848
+                $unique_indexes [$name] = $index;
5849 5849
             }
5850 5850
         }
5851 5851
         return $unique_indexes;
@@ -5909,7 +5909,7 @@  discard block
 block discarded – undo
5909 5909
         $key_values_in_combined_pk = [];
5910 5910
         parse_str($index_primary_key_string, $key_values_in_combined_pk);
5911 5911
         foreach ($key_fields as $key_field_name => $field_obj) {
5912
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5912
+            if ( ! isset($key_values_in_combined_pk[$key_field_name])) {
5913 5913
                 return null;
5914 5914
             }
5915 5915
         }
@@ -5929,7 +5929,7 @@  discard block
 block discarded – undo
5929 5929
     {
5930 5930
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5931 5931
         foreach ($keys_it_should_have as $key) {
5932
-            if (! isset($key_values[ $key ])) {
5932
+            if ( ! isset($key_values[$key])) {
5933 5933
                 return false;
5934 5934
             }
5935 5935
         }
@@ -5968,8 +5968,8 @@  discard block
 block discarded – undo
5968 5968
         }
5969 5969
         // even copies obviously won't have the same ID, so remove the primary key
5970 5970
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5971
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5972
-            unset($attributes_array[ $this->primary_key_name() ]);
5971
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5972
+            unset($attributes_array[$this->primary_key_name()]);
5973 5973
         }
5974 5974
         if (isset($query_params[0])) {
5975 5975
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5991,7 +5991,7 @@  discard block
 block discarded – undo
5991 5991
      */
5992 5992
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5993 5993
     {
5994
-        if (! is_array($query_params)) {
5994
+        if ( ! is_array($query_params)) {
5995 5995
             EE_Error::doing_it_wrong(
5996 5996
                 'EEM_Base::get_one_copy',
5997 5997
                 sprintf(
@@ -6041,7 +6041,7 @@  discard block
 block discarded – undo
6041 6041
     private function _prepare_operator_for_sql($operator_supplied)
6042 6042
     {
6043 6043
         $sql_operator =
6044
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6044
+            isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6045 6045
                 : null;
6046 6046
         if ($sql_operator) {
6047 6047
             return $sql_operator;
@@ -6140,7 +6140,7 @@  discard block
 block discarded – undo
6140 6140
         $objs  = $this->get_all($query_params);
6141 6141
         $names = [];
6142 6142
         foreach ($objs as $obj) {
6143
-            $names[ $obj->ID() ] = $obj->name();
6143
+            $names[$obj->ID()] = $obj->name();
6144 6144
         }
6145 6145
         return $names;
6146 6146
     }
@@ -6160,7 +6160,7 @@  discard block
 block discarded – undo
6160 6160
      */
6161 6161
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6162 6162
     {
6163
-        if (! $this->has_primary_key_field()) {
6163
+        if ( ! $this->has_primary_key_field()) {
6164 6164
             if (WP_DEBUG) {
6165 6165
                 EE_Error::add_error(
6166 6166
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6173,7 +6173,7 @@  discard block
 block discarded – undo
6173 6173
         $IDs = [];
6174 6174
         foreach ($model_objects as $model_object) {
6175 6175
             $id = $model_object->ID();
6176
-            if (! $id) {
6176
+            if ( ! $id) {
6177 6177
                 if ($filter_out_empty_ids) {
6178 6178
                     continue;
6179 6179
                 }
@@ -6223,22 +6223,22 @@  discard block
 block discarded – undo
6223 6223
         EEM_Base::verify_is_valid_cap_context($context);
6224 6224
         // check if we ought to run the restriction generator first
6225 6225
         if (
6226
-            isset($this->_cap_restriction_generators[ $context ])
6227
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6228
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6226
+            isset($this->_cap_restriction_generators[$context])
6227
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6228
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6229 6229
         ) {
6230
-            $this->_cap_restrictions[ $context ] = array_merge(
6231
-                $this->_cap_restrictions[ $context ],
6232
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6230
+            $this->_cap_restrictions[$context] = array_merge(
6231
+                $this->_cap_restrictions[$context],
6232
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6233 6233
             );
6234 6234
         }
6235 6235
         // and make sure we've finalized the construction of each restriction
6236
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6236
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6237 6237
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6238 6238
                 $where_conditions_obj->_finalize_construct($this);
6239 6239
             }
6240 6240
         }
6241
-        return $this->_cap_restrictions[ $context ];
6241
+        return $this->_cap_restrictions[$context];
6242 6242
     }
6243 6243
 
6244 6244
 
@@ -6268,9 +6268,9 @@  discard block
 block discarded – undo
6268 6268
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6269 6269
             if (
6270 6270
             ! EE_Capabilities::instance()
6271
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6271
+                             ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6272 6272
             ) {
6273
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6273
+                $missing_caps[$cap] = $restriction_if_no_cap;
6274 6274
             }
6275 6275
         }
6276 6276
         return $missing_caps;
@@ -6303,8 +6303,8 @@  discard block
 block discarded – undo
6303 6303
     public function cap_action_for_context($context)
6304 6304
     {
6305 6305
         $mapping = $this->cap_contexts_to_cap_action_map();
6306
-        if (isset($mapping[ $context ])) {
6307
-            return $mapping[ $context ];
6306
+        if (isset($mapping[$context])) {
6307
+            return $mapping[$context];
6308 6308
         }
6309 6309
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6310 6310
             return $action;
@@ -6422,7 +6422,7 @@  discard block
 block discarded – undo
6422 6422
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6423 6423
             if (
6424 6424
                 $query_param_key === $logic_query_param_key
6425
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6425
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6426 6426
             ) {
6427 6427
                 return true;
6428 6428
             }
@@ -6480,7 +6480,7 @@  discard block
 block discarded – undo
6480 6480
         if ($password_field instanceof EE_Password_Field) {
6481 6481
             $field_names = $password_field->protectedFields();
6482 6482
             foreach ($field_names as $field_name) {
6483
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6483
+                $fields[$field_name] = $this->field_settings_for($field_name);
6484 6484
             }
6485 6485
         }
6486 6486
         return $fields;
@@ -6506,7 +6506,7 @@  discard block
 block discarded – undo
6506 6506
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6507 6507
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6508 6508
         }
6509
-        if (! is_array($model_obj_or_fields_n_values)) {
6509
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6510 6510
             throw new UnexpectedEntityException(
6511 6511
                 $model_obj_or_fields_n_values,
6512 6512
                 'EE_Base_Class',
@@ -6586,7 +6586,7 @@  discard block
 block discarded – undo
6586 6586
                 )
6587 6587
             );
6588 6588
         }
6589
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6589
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6590 6590
     }
6591 6591
 
6592 6592
 
Please login to merge, or discard this patch.
core/db_models/EEM_Event_Venue.model.php 2 patches
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -9,68 +9,68 @@
 block discarded – undo
9 9
  */
10 10
 class EEM_Event_Venue extends EEM_Base
11 11
 {
12
-    // private instance of the Attendee object
13
-    protected static $_instance;
12
+	// private instance of the Attendee object
13
+	protected static $_instance;
14 14
 
15 15
 
16
-    protected function __construct(string $timezone = '')
17
-    {
18
-        $this->singular_item    = esc_html__('Event to Question Group Link', 'event_espresso');
19
-        $this->plural_item      = esc_html__('Event to Question Group Links', 'event_espresso');
20
-        $this->_tables          = [
21
-            'Event_Venue' => new EE_Primary_Table('esp_event_venue', 'EVV_ID'),
22
-        ];
23
-        $this->_fields          = [
24
-            'Event_Venue' => [
25
-                'EVV_ID'      => new EE_Primary_Key_Int_Field(
26
-                    'EVV_ID',
27
-                    esc_html__('Event to Venue Link ID', 'event_espresso')
28
-                ),
29
-                'EVT_ID'      => new EE_Foreign_Key_Int_Field(
30
-                    'EVT_ID',
31
-                    esc_html__('Event ID', 'event_espresso'),
32
-                    false,
33
-                    0,
34
-                    'Event'
35
-                ),
36
-                'VNU_ID'      => new EE_Foreign_Key_Int_Field(
37
-                    'VNU_ID',
38
-                    esc_html__('Venue ID', 'event_espresso'),
39
-                    false,
40
-                    0,
41
-                    'Venue'
42
-                ),
43
-                'EVV_primary' => new EE_Boolean_Field(
44
-                    'EVV_primary',
45
-                    esc_html__("Flag indicating venue is primary one for event", "event_espresso"),
46
-                    false,
47
-                    true
48
-                ),
16
+	protected function __construct(string $timezone = '')
17
+	{
18
+		$this->singular_item    = esc_html__('Event to Question Group Link', 'event_espresso');
19
+		$this->plural_item      = esc_html__('Event to Question Group Links', 'event_espresso');
20
+		$this->_tables          = [
21
+			'Event_Venue' => new EE_Primary_Table('esp_event_venue', 'EVV_ID'),
22
+		];
23
+		$this->_fields          = [
24
+			'Event_Venue' => [
25
+				'EVV_ID'      => new EE_Primary_Key_Int_Field(
26
+					'EVV_ID',
27
+					esc_html__('Event to Venue Link ID', 'event_espresso')
28
+				),
29
+				'EVT_ID'      => new EE_Foreign_Key_Int_Field(
30
+					'EVT_ID',
31
+					esc_html__('Event ID', 'event_espresso'),
32
+					false,
33
+					0,
34
+					'Event'
35
+				),
36
+				'VNU_ID'      => new EE_Foreign_Key_Int_Field(
37
+					'VNU_ID',
38
+					esc_html__('Venue ID', 'event_espresso'),
39
+					false,
40
+					0,
41
+					'Venue'
42
+				),
43
+				'EVV_primary' => new EE_Boolean_Field(
44
+					'EVV_primary',
45
+					esc_html__("Flag indicating venue is primary one for event", "event_espresso"),
46
+					false,
47
+					true
48
+				),
49 49
 
50
-            ],
51
-        ];
52
-        $this->_model_relations = [
53
-            'Event' => new EE_Belongs_To_Relation(),
54
-            'Venue' => new EE_Belongs_To_Relation(),
55
-        ];
56
-        // this model is generally available for reading
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
58
-            'Event'
59
-        );
60
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
61
-                                                                  = new EE_Restriction_Generator_Event_Related_Protected(
62
-            'Event'
63
-        );
64
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]
65
-                                                                  = new EE_Restriction_Generator_Event_Related_Protected(
66
-            'Event'
67
-        );
68
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]
69
-                                                                  = new EE_Restriction_Generator_Event_Related_Protected(
70
-            'Event',
71
-            EEM_Base::caps_edit
72
-        );
73
-        $this->model_chain_to_password                            = 'Event';
74
-        parent::__construct($timezone);
75
-    }
50
+			],
51
+		];
52
+		$this->_model_relations = [
53
+			'Event' => new EE_Belongs_To_Relation(),
54
+			'Venue' => new EE_Belongs_To_Relation(),
55
+		];
56
+		// this model is generally available for reading
57
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
58
+			'Event'
59
+		);
60
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
61
+																  = new EE_Restriction_Generator_Event_Related_Protected(
62
+			'Event'
63
+		);
64
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]
65
+																  = new EE_Restriction_Generator_Event_Related_Protected(
66
+			'Event'
67
+		);
68
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]
69
+																  = new EE_Restriction_Generator_Event_Related_Protected(
70
+			'Event',
71
+			EEM_Base::caps_edit
72
+		);
73
+		$this->model_chain_to_password                            = 'Event';
74
+		parent::__construct($timezone);
75
+	}
76 76
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -54,23 +54,23 @@
 block discarded – undo
54 54
             'Venue' => new EE_Belongs_To_Relation(),
55 55
         ];
56 56
         // this model is generally available for reading
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
57
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public(
58 58
             'Event'
59 59
         );
60
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
60
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin]
61 61
                                                                   = new EE_Restriction_Generator_Event_Related_Protected(
62 62
             'Event'
63 63
         );
64
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]
64
+        $this->_cap_restriction_generators[EEM_Base::caps_edit]
65 65
                                                                   = new EE_Restriction_Generator_Event_Related_Protected(
66 66
             'Event'
67 67
         );
68
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]
68
+        $this->_cap_restriction_generators[EEM_Base::caps_delete]
69 69
                                                                   = new EE_Restriction_Generator_Event_Related_Protected(
70 70
             'Event',
71 71
             EEM_Base::caps_edit
72 72
         );
73
-        $this->model_chain_to_password                            = 'Event';
73
+        $this->model_chain_to_password = 'Event';
74 74
         parent::__construct($timezone);
75 75
     }
76 76
 }
Please login to merge, or discard this patch.
core/db_models/EEM_WP_User.model.php 1 patch
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -13,132 +13,132 @@
 block discarded – undo
13 13
 class EEM_WP_User extends EEM_Base
14 14
 {
15 15
 
16
-    /**
17
-     * private instance of the EEM_WP_User object
18
-     *
19
-     * @type EEM_WP_User
20
-     */
21
-    protected static $_instance;
16
+	/**
17
+	 * private instance of the EEM_WP_User object
18
+	 *
19
+	 * @type EEM_WP_User
20
+	 */
21
+	protected static $_instance;
22 22
 
23 23
 
24
-    /**
25
-     *    constructor
26
-     *
27
-     * @param string                 $timezone
28
-     * @param ModelFieldFactory|null $model_field_factory
29
-     * @throws EE_Error
30
-     */
31
-    protected function __construct(string $timezone = '', ModelFieldFactory $model_field_factory = null)
32
-    {
33
-        $this->singular_item = esc_html__('WP_User', 'event_espresso');
34
-        $this->plural_item = esc_html__('WP_Users', 'event_espresso');
35
-        global $wpdb;
36
-        $this->_tables = array(
37
-            'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
38
-        );
39
-        $this->_fields = array(
40
-            'WP_User' => array(
41
-                'ID'                  => $model_field_factory->createPrimaryKeyIntField(
42
-                    'ID',
43
-                    esc_html__('WP_User ID', 'event_espresso')
44
-                ),
45
-                'user_login'          => $model_field_factory->createPlainTextField(
46
-                    'user_login',
47
-                    esc_html__('User Login', 'event_espresso'),
48
-                    false
49
-                ),
50
-                'user_pass'           => $model_field_factory->createPlainTextField(
51
-                    'user_pass',
52
-                    esc_html__('User Password', 'event_espresso'),
53
-                    false
54
-                ),
55
-                'user_nicename'       => $model_field_factory->createPlainTextField(
56
-                    'user_nicename',
57
-                    esc_html__(' User Nice Name', 'event_espresso'),
58
-                    false
59
-                ),
60
-                'user_email'          => $model_field_factory->createEmailField(
61
-                    'user_email',
62
-                    esc_html__('User Email', 'event_espresso'),
63
-                    false,
64
-                    null
65
-                ),
66
-                'user_registered'     => $model_field_factory->createDatetimeField(
67
-                    'user_registered',
68
-                    esc_html__('Date User Registered', 'event_espresso'),
69
-                    $timezone
70
-                ),
71
-                'user_activation_key' => $model_field_factory->createPlainTextField(
72
-                    'user_activation_key',
73
-                    esc_html__('User Activation Key', 'event_espresso'),
74
-                    false
75
-                ),
76
-                'user_status'         => $model_field_factory->createIntegerField(
77
-                    'user_status',
78
-                    esc_html__('User Status', 'event_espresso')
79
-                ),
80
-                'display_name'        => $model_field_factory->createPlainTextField(
81
-                    'display_name',
82
-                    esc_html__('Display Name', 'event_espresso'),
83
-                    false
84
-                ),
85
-            ),
86
-        );
87
-        $this->_model_relations = array(
88
-            'Attendee'       => new EE_Has_Many_Relation(),
89
-            // all models are related to the change log
90
-            // 'Change_Log'     => new EE_Has_Many_Relation(),
91
-            'Event'          => new EE_Has_Many_Relation(),
92
-            'Message'        => new EE_Has_Many_Relation(),
93
-            'Payment_Method' => new EE_Has_Many_Relation(),
94
-            'Price'          => new EE_Has_Many_Relation(),
95
-            'Price_Type'     => new EE_Has_Many_Relation(),
96
-            'Question'       => new EE_Has_Many_Relation(),
97
-            'Question_Group' => new EE_Has_Many_Relation(),
98
-            'Ticket'         => new EE_Has_Many_Relation(),
99
-            'Venue'          => new EE_Has_Many_Relation(),
100
-        );
101
-        $this->foreign_key_aliases = [
102
-            'Event.EVT_wp_user'          => 'WP_User.ID',
103
-            'Payment_Method.PMD_wp_user' => 'WP_User.ID',
104
-            'Price.PRC_wp_user'          => 'WP_User.ID',
105
-            'Price_Type.PRT_wp_user'     => 'WP_User.ID',
106
-            'Question.QST_wp_user'       => 'WP_User.ID',
107
-            'Question_Group.QSG_wp_user' => 'WP_User.ID',
108
-            'Ticket.VNU_wp_user'         => 'WP_User.ID',
109
-            'Venue.TKT_wp_user'          => 'WP_User.ID',
110
-        ];
111
-        $this->_wp_core_model = true;
112
-        $this->_caps_slug = 'users';
113
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
114
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
115
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
116
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
117
-        }
118
-        // @todo: account for create_users controls whether they can create users at all
119
-        parent::__construct($timezone);
120
-    }
24
+	/**
25
+	 *    constructor
26
+	 *
27
+	 * @param string                 $timezone
28
+	 * @param ModelFieldFactory|null $model_field_factory
29
+	 * @throws EE_Error
30
+	 */
31
+	protected function __construct(string $timezone = '', ModelFieldFactory $model_field_factory = null)
32
+	{
33
+		$this->singular_item = esc_html__('WP_User', 'event_espresso');
34
+		$this->plural_item = esc_html__('WP_Users', 'event_espresso');
35
+		global $wpdb;
36
+		$this->_tables = array(
37
+			'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
38
+		);
39
+		$this->_fields = array(
40
+			'WP_User' => array(
41
+				'ID'                  => $model_field_factory->createPrimaryKeyIntField(
42
+					'ID',
43
+					esc_html__('WP_User ID', 'event_espresso')
44
+				),
45
+				'user_login'          => $model_field_factory->createPlainTextField(
46
+					'user_login',
47
+					esc_html__('User Login', 'event_espresso'),
48
+					false
49
+				),
50
+				'user_pass'           => $model_field_factory->createPlainTextField(
51
+					'user_pass',
52
+					esc_html__('User Password', 'event_espresso'),
53
+					false
54
+				),
55
+				'user_nicename'       => $model_field_factory->createPlainTextField(
56
+					'user_nicename',
57
+					esc_html__(' User Nice Name', 'event_espresso'),
58
+					false
59
+				),
60
+				'user_email'          => $model_field_factory->createEmailField(
61
+					'user_email',
62
+					esc_html__('User Email', 'event_espresso'),
63
+					false,
64
+					null
65
+				),
66
+				'user_registered'     => $model_field_factory->createDatetimeField(
67
+					'user_registered',
68
+					esc_html__('Date User Registered', 'event_espresso'),
69
+					$timezone
70
+				),
71
+				'user_activation_key' => $model_field_factory->createPlainTextField(
72
+					'user_activation_key',
73
+					esc_html__('User Activation Key', 'event_espresso'),
74
+					false
75
+				),
76
+				'user_status'         => $model_field_factory->createIntegerField(
77
+					'user_status',
78
+					esc_html__('User Status', 'event_espresso')
79
+				),
80
+				'display_name'        => $model_field_factory->createPlainTextField(
81
+					'display_name',
82
+					esc_html__('Display Name', 'event_espresso'),
83
+					false
84
+				),
85
+			),
86
+		);
87
+		$this->_model_relations = array(
88
+			'Attendee'       => new EE_Has_Many_Relation(),
89
+			// all models are related to the change log
90
+			// 'Change_Log'     => new EE_Has_Many_Relation(),
91
+			'Event'          => new EE_Has_Many_Relation(),
92
+			'Message'        => new EE_Has_Many_Relation(),
93
+			'Payment_Method' => new EE_Has_Many_Relation(),
94
+			'Price'          => new EE_Has_Many_Relation(),
95
+			'Price_Type'     => new EE_Has_Many_Relation(),
96
+			'Question'       => new EE_Has_Many_Relation(),
97
+			'Question_Group' => new EE_Has_Many_Relation(),
98
+			'Ticket'         => new EE_Has_Many_Relation(),
99
+			'Venue'          => new EE_Has_Many_Relation(),
100
+		);
101
+		$this->foreign_key_aliases = [
102
+			'Event.EVT_wp_user'          => 'WP_User.ID',
103
+			'Payment_Method.PMD_wp_user' => 'WP_User.ID',
104
+			'Price.PRC_wp_user'          => 'WP_User.ID',
105
+			'Price_Type.PRT_wp_user'     => 'WP_User.ID',
106
+			'Question.QST_wp_user'       => 'WP_User.ID',
107
+			'Question_Group.QSG_wp_user' => 'WP_User.ID',
108
+			'Ticket.VNU_wp_user'         => 'WP_User.ID',
109
+			'Venue.TKT_wp_user'          => 'WP_User.ID',
110
+		];
111
+		$this->_wp_core_model = true;
112
+		$this->_caps_slug = 'users';
113
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
114
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
115
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
116
+			$this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
117
+		}
118
+		// @todo: account for create_users controls whether they can create users at all
119
+		parent::__construct($timezone);
120
+	}
121 121
 
122 122
 
123
-    /**
124
-     * We don't need a foreign key to the WP_User model, we just need its primary key
125
-     *
126
-     * @return string
127
-     * @throws EE_Error
128
-     */
129
-    public function wp_user_field_name(): string
130
-    {
131
-        return $this->primary_key_name();
132
-    }
123
+	/**
124
+	 * We don't need a foreign key to the WP_User model, we just need its primary key
125
+	 *
126
+	 * @return string
127
+	 * @throws EE_Error
128
+	 */
129
+	public function wp_user_field_name(): string
130
+	{
131
+		return $this->primary_key_name();
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * This WP_User model IS owned, even though it doesn't have a foreign key to itself
137
-     *
138
-     * @return boolean
139
-     */
140
-    public function is_owned(): bool
141
-    {
142
-        return true;
143
-    }
135
+	/**
136
+	 * This WP_User model IS owned, even though it doesn't have a foreign key to itself
137
+	 *
138
+	 * @return boolean
139
+	 */
140
+	public function is_owned(): bool
141
+	{
142
+		return true;
143
+	}
144 144
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Line_Item.model.php 2 patches
Indentation   +627 added lines, -627 removed lines patch added patch discarded remove patch
@@ -28,634 +28,634 @@
 block discarded – undo
28 28
 class EEM_Line_Item extends EEM_Base
29 29
 {
30 30
 
31
-    /**
32
-     * Tax sub-total is just the total of all the taxes, which should be children
33
-     * of this line item. There should only ever be one tax sub-total, and it should
34
-     * be a direct child of. Its quantity and LIN_unit_price = 1.
35
-     */
36
-    const type_tax_sub_total = 'tax-sub-total';
37
-
38
-    /**
39
-     * Tax line items indicate a tax applied to all the taxable line items.
40
-     * Should not have any children line items. Its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal
41
-     * (eg 10% tax = 10, not 0.1). Its LIN_total = LIN_unit_price * pre-tax-total. Quantity = 1.
42
-     */
43
-    const type_tax = 'tax';
44
-
45
-    /**
46
-     * Indicating individual items purchased, or discounts or surcharges.
47
-     * The sum of all the regular line items  plus the tax items should equal the grand total.
48
-     * Possible children are sub-line-items and cancellations.
49
-     * For flat items, LIN_unit_price * LIN_quantity = LIN_total. Its LIN_total is the sum of all the children
50
-     * LIN_totals. Its LIN_percent = 0.
51
-     * For percent items, its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal (eg 10% = 10, not 0.1).
52
-     * Its LIN_total is LIN_percent / 100 * sum of lower-priority sibling line items. Quantity = 1.
53
-     */
54
-    const type_line_item = 'line-item';
55
-
56
-    /**
57
-     * Line item indicating all the factors that make a single line item.
58
-     * Sub-line items should have NO children line items.
59
-     * For flat sub-items, their quantity should match their parent item, their LIN_unit_price should be this sub-item's
60
-     * contribution towards the price of ONE of their parent items, and its LIN_total should be
61
-     *  = LIN_quantity * LIN_unit_price. Its LIN_percent = 0.
62
-     * For percent sub-items, the quantity should be 1, LIN_unit_price should be 0, and its LIN_total should
63
-     * = LIN_percent / 100 * sum of lower-priority sibling line items..
64
-     */
65
-    const type_sub_line_item = 'sub-item';
66
-
67
-    /**
68
-     * Line item indicating a sub-total (eg total for an event, or pre-tax subtotal).
69
-     * Direct children should be event subtotals.
70
-     * Should have quantity of 1, and a LIN_total and LIN_unit_price of the sum of all its sub-items' LIN_totals.
71
-     */
72
-    const type_sub_total = 'sub-total';
73
-
74
-    /**
75
-     * Line item for the grand total of an order.
76
-     * Its direct children should be tax subtotals and (pre-tax) subtotals,
77
-     * and possibly a regular line item indicating a transaction-wide discount/surcharge.
78
-     * Should have a quantity of 1, a LIN_total and LIN_unit_price of the entire order's amount.
79
-     */
80
-    const type_total = 'total';
81
-
82
-    /**
83
-     * When a line item is cancelled, a sub-line-item of type 'cancellation'
84
-     * should be created, indicating the quantity that were cancelled
85
-     * (because a line item could have a quantity of 1, and its cancellation item
86
-     * could be for 3, indicating that originally 4 were purchased, but 3 have been
87
-     * cancelled, and only one remains).
88
-     * When items are refunded, a cancellation line item should be made, which points
89
-     * to teh payment model object which actually refunded the payment.
90
-     * Cancellations should NOT have any children line items; the should NOT affect
91
-     * any calculations, and are only meant as a record that cancellations have occurred.
92
-     * Their LIN_percent should be 0.
93
-     */
94
-    const type_cancellation = 'cancellation';
95
-
96
-    // various line item object types
97
-    const OBJ_TYPE_EVENT       = 'Event';
98
-
99
-    const OBJ_TYPE_PRICE       = 'Price';
100
-
101
-    const OBJ_TYPE_PROMOTION   = 'Promotion';
102
-
103
-    const OBJ_TYPE_TICKET      = 'Ticket';
104
-
105
-    const OBJ_TYPE_TRANSACTION = 'Transaction';
106
-
107
-    /**
108
-     * @var EEM_Line_Item $_instance
109
-     */
110
-    protected static $_instance;
111
-
112
-
113
-    /**
114
-     * private constructor to prevent direct creation
115
-     *
116
-     * @Constructor
117
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
118
-     *                         (and any incoming timezone data that gets saved).
119
-     *                         Note this just sends the timezone info to the date time model field objects.
120
-     *                         Default is NULL
121
-     *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
122
-     * @throws EE_Error
123
-     * @throws InvalidArgumentException
124
-     */
125
-    protected function __construct(string $timezone = '')
126
-    {
127
-        $this->singular_item = esc_html__('Line Item', 'event_espresso');
128
-        $this->plural_item   = esc_html__('Line Items', 'event_espresso');
129
-
130
-        $this->_tables                 = [
131
-            'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID'),
132
-        ];
133
-        $line_items_can_be_for         = apply_filters(
134
-            'FHEE__EEM_Line_Item__line_items_can_be_for',
135
-            ['Ticket', 'Price', 'Event']
136
-        );
137
-        $this->_fields                 = [
138
-            'Line_Item' => [
139
-                'LIN_ID'         => new EE_Primary_Key_Int_Field(
140
-                    'LIN_ID',
141
-                    esc_html__('ID', 'event_espresso')
142
-                ),
143
-                'LIN_code'       => new EE_Slug_Field(
144
-                    'LIN_code',
145
-                    esc_html__('Code for index into Cart', 'event_espresso'),
146
-                    true
147
-                ),
148
-                'TXN_ID'         => new EE_Foreign_Key_Int_Field(
149
-                    'TXN_ID',
150
-                    esc_html__('Transaction ID', 'event_espresso'),
151
-                    true,
152
-                    null,
153
-                    'Transaction'
154
-                ),
155
-                'LIN_name'       => new EE_Full_HTML_Field(
156
-                    'LIN_name',
157
-                    esc_html__('Line Item Name', 'event_espresso'),
158
-                    false,
159
-                    ''
160
-                ),
161
-                'LIN_desc'       => new EE_Full_HTML_Field(
162
-                    'LIN_desc',
163
-                    esc_html__('Line Item Description', 'event_espresso'),
164
-                    true
165
-                ),
166
-                'LIN_unit_price' => new EE_Money_Field(
167
-                    'LIN_unit_price',
168
-                    esc_html__('Unit Price', 'event_espresso'),
169
-                    false,
170
-                    0
171
-                ),
172
-                'LIN_percent'    => new EE_Float_Field(
173
-                    'LIN_percent',
174
-                    esc_html__('Percent', 'event_espresso'),
175
-                    false,
176
-                    0
177
-                ),
178
-                'LIN_is_taxable' => new EE_Boolean_Field(
179
-                    'LIN_is_taxable',
180
-                    esc_html__('Taxable', 'event_espresso'),
181
-                    false,
182
-                    false
183
-                ),
184
-                'LIN_order'      => new EE_Integer_Field(
185
-                    'LIN_order',
186
-                    esc_html__('Order of Application towards total of parent', 'event_espresso'),
187
-                    false,
188
-                    1
189
-                ),
190
-                'LIN_total'      => new EE_Money_Field(
191
-                    'LIN_total',
192
-                    esc_html__('Total (unit price x quantity)', 'event_espresso'),
193
-                    false,
194
-                    0
195
-                ),
196
-                'LIN_quantity'   => new EE_Integer_Field(
197
-                    'LIN_quantity',
198
-                    esc_html__('Quantity', 'event_espresso'),
199
-                    true,
200
-                    1
201
-                ),
202
-                'LIN_parent'     => new EE_Integer_Field(
203
-                    'LIN_parent',
204
-                    esc_html__(
205
-                        "Parent ID (this item goes towards that Line Item's total)",
206
-                        'event_espresso'
207
-                    ),
208
-                    true,
209
-                    null
210
-                ),
211
-                'LIN_type'       => new EE_Enum_Text_Field(
212
-                    'LIN_type',
213
-                    esc_html__('Type', 'event_espresso'),
214
-                    false,
215
-                    'line-item',
216
-                    [
217
-                        self::type_line_item     => esc_html__('Line Item', 'event_espresso'),
218
-                        self::type_sub_line_item => esc_html__('Sub-Item', 'event_espresso'),
219
-                        self::type_sub_total     => esc_html__('Subtotal', 'event_espresso'),
220
-                        self::type_tax_sub_total => esc_html__('Tax Subtotal', 'event_espresso'),
221
-                        self::type_tax           => esc_html__('Tax', 'event_espresso'),
222
-                        self::type_total         => esc_html__('Total', 'event_espresso'),
223
-                        self::type_cancellation  => esc_html__('Cancellation', 'event_espresso'),
224
-                    ]
225
-                ),
226
-                'OBJ_ID'         => new EE_Foreign_Key_Int_Field(
227
-                    'OBJ_ID',
228
-                    esc_html__('ID of Item purchased.', 'event_espresso'),
229
-                    true,
230
-                    null,
231
-                    $line_items_can_be_for
232
-                ),
233
-                'OBJ_type'       => new EE_Any_Foreign_Model_Name_Field(
234
-                    'OBJ_type',
235
-                    esc_html__('Model Name this Line Item is for', 'event_espresso'),
236
-                    true,
237
-                    null,
238
-                    $line_items_can_be_for
239
-                ),
240
-                'LIN_timestamp'  => new EE_Datetime_Field(
241
-                    'LIN_timestamp',
242
-                    esc_html__('When the line item was created', 'event_espresso'),
243
-                    false,
244
-                    EE_Datetime_Field::now,
245
-                    $timezone
246
-                ),
247
-            ],
248
-        ];
249
-        $this->_model_relations        = [
250
-            'Transaction' => new EE_Belongs_To_Relation(),
251
-            'Ticket'      => new EE_Belongs_To_Any_Relation(),
252
-            'Price'       => new EE_Belongs_To_Any_Relation(),
253
-            'Event'       => new EE_Belongs_To_Any_Relation(),
254
-        ];
255
-        $this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
256
-        $this->_caps_slug              = 'transactions';
257
-        parent::__construct($timezone);
258
-    }
259
-
260
-
261
-    /**
262
-     * Gets all the line items for this transaction of the given type
263
-     *
264
-     * @param string             $line_item_type like one of EEM_Line_Item::type_*
265
-     * @param EE_Transaction|int $transaction
266
-     * @return EE_Line_Item[]
267
-     * @throws EE_Error
268
-     * @throws InvalidArgumentException
269
-     * @throws InvalidDataTypeException
270
-     * @throws InvalidInterfaceException
271
-     * @throws ReflectionException
272
-     */
273
-    public function get_all_of_type_for_transaction(string $line_item_type, $transaction): array
274
-    {
275
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
276
-        return $this->get_all(
277
-            [
278
-                [
279
-                    'LIN_type' => $line_item_type,
280
-                    'TXN_ID'   => $transaction,
281
-                ],
282
-            ]
283
-        );
284
-    }
285
-
286
-
287
-    /**
288
-     * Gets all line items unrelated to tickets that are normal line items
289
-     * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
290
-     *
291
-     * @param EE_Transaction|int $transaction
292
-     * @return EE_Line_Item[]
293
-     * @throws EE_Error
294
-     * @throws InvalidArgumentException
295
-     * @throws InvalidDataTypeException
296
-     * @throws InvalidInterfaceException
297
-     * @throws ReflectionException
298
-     */
299
-    public function get_all_non_ticket_line_items_for_transaction($transaction): array
300
-    {
301
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
302
-        return $this->get_all(
303
-            [
304
-                [
305
-                    'LIN_type' => self::type_line_item,
306
-                    'TXN_ID'   => $transaction,
307
-                    'OR'       => [
308
-                        'OBJ_type*notticket' => ['!=', EEM_Line_Item::OBJ_TYPE_TICKET],
309
-                        'OBJ_type*null'      => ['IS_NULL'],
310
-                    ],
311
-                ],
312
-            ]
313
-        );
314
-    }
315
-
316
-
317
-    /**
318
-     * Deletes line items with no transaction who have passed the transaction cutoff time.
319
-     * This needs to be very efficient
320
-     * because if there are spam bots afoot there will be LOTS of line items. Also MySQL doesn't allow a limit when
321
-     * deleting and joining tables like this.
322
-     *
323
-     * @return int count of how many deleted
324
-     * @throws EE_Error
325
-     * @throws InvalidArgumentException
326
-     * @throws InvalidDataTypeException
327
-     * @throws InvalidInterfaceException
328
-     */
329
-    public function delete_line_items_with_no_transaction(): int
330
-    {
331
-        global $wpdb;
332
-        $time_to_leave_alone = apply_filters(
333
-            'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone',
334
-            WEEK_IN_SECONDS
335
-        );
336
-        $query               = $wpdb->prepare(
337
-            'DELETE li
31
+	/**
32
+	 * Tax sub-total is just the total of all the taxes, which should be children
33
+	 * of this line item. There should only ever be one tax sub-total, and it should
34
+	 * be a direct child of. Its quantity and LIN_unit_price = 1.
35
+	 */
36
+	const type_tax_sub_total = 'tax-sub-total';
37
+
38
+	/**
39
+	 * Tax line items indicate a tax applied to all the taxable line items.
40
+	 * Should not have any children line items. Its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal
41
+	 * (eg 10% tax = 10, not 0.1). Its LIN_total = LIN_unit_price * pre-tax-total. Quantity = 1.
42
+	 */
43
+	const type_tax = 'tax';
44
+
45
+	/**
46
+	 * Indicating individual items purchased, or discounts or surcharges.
47
+	 * The sum of all the regular line items  plus the tax items should equal the grand total.
48
+	 * Possible children are sub-line-items and cancellations.
49
+	 * For flat items, LIN_unit_price * LIN_quantity = LIN_total. Its LIN_total is the sum of all the children
50
+	 * LIN_totals. Its LIN_percent = 0.
51
+	 * For percent items, its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal (eg 10% = 10, not 0.1).
52
+	 * Its LIN_total is LIN_percent / 100 * sum of lower-priority sibling line items. Quantity = 1.
53
+	 */
54
+	const type_line_item = 'line-item';
55
+
56
+	/**
57
+	 * Line item indicating all the factors that make a single line item.
58
+	 * Sub-line items should have NO children line items.
59
+	 * For flat sub-items, their quantity should match their parent item, their LIN_unit_price should be this sub-item's
60
+	 * contribution towards the price of ONE of their parent items, and its LIN_total should be
61
+	 *  = LIN_quantity * LIN_unit_price. Its LIN_percent = 0.
62
+	 * For percent sub-items, the quantity should be 1, LIN_unit_price should be 0, and its LIN_total should
63
+	 * = LIN_percent / 100 * sum of lower-priority sibling line items..
64
+	 */
65
+	const type_sub_line_item = 'sub-item';
66
+
67
+	/**
68
+	 * Line item indicating a sub-total (eg total for an event, or pre-tax subtotal).
69
+	 * Direct children should be event subtotals.
70
+	 * Should have quantity of 1, and a LIN_total and LIN_unit_price of the sum of all its sub-items' LIN_totals.
71
+	 */
72
+	const type_sub_total = 'sub-total';
73
+
74
+	/**
75
+	 * Line item for the grand total of an order.
76
+	 * Its direct children should be tax subtotals and (pre-tax) subtotals,
77
+	 * and possibly a regular line item indicating a transaction-wide discount/surcharge.
78
+	 * Should have a quantity of 1, a LIN_total and LIN_unit_price of the entire order's amount.
79
+	 */
80
+	const type_total = 'total';
81
+
82
+	/**
83
+	 * When a line item is cancelled, a sub-line-item of type 'cancellation'
84
+	 * should be created, indicating the quantity that were cancelled
85
+	 * (because a line item could have a quantity of 1, and its cancellation item
86
+	 * could be for 3, indicating that originally 4 were purchased, but 3 have been
87
+	 * cancelled, and only one remains).
88
+	 * When items are refunded, a cancellation line item should be made, which points
89
+	 * to teh payment model object which actually refunded the payment.
90
+	 * Cancellations should NOT have any children line items; the should NOT affect
91
+	 * any calculations, and are only meant as a record that cancellations have occurred.
92
+	 * Their LIN_percent should be 0.
93
+	 */
94
+	const type_cancellation = 'cancellation';
95
+
96
+	// various line item object types
97
+	const OBJ_TYPE_EVENT       = 'Event';
98
+
99
+	const OBJ_TYPE_PRICE       = 'Price';
100
+
101
+	const OBJ_TYPE_PROMOTION   = 'Promotion';
102
+
103
+	const OBJ_TYPE_TICKET      = 'Ticket';
104
+
105
+	const OBJ_TYPE_TRANSACTION = 'Transaction';
106
+
107
+	/**
108
+	 * @var EEM_Line_Item $_instance
109
+	 */
110
+	protected static $_instance;
111
+
112
+
113
+	/**
114
+	 * private constructor to prevent direct creation
115
+	 *
116
+	 * @Constructor
117
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
118
+	 *                         (and any incoming timezone data that gets saved).
119
+	 *                         Note this just sends the timezone info to the date time model field objects.
120
+	 *                         Default is NULL
121
+	 *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
122
+	 * @throws EE_Error
123
+	 * @throws InvalidArgumentException
124
+	 */
125
+	protected function __construct(string $timezone = '')
126
+	{
127
+		$this->singular_item = esc_html__('Line Item', 'event_espresso');
128
+		$this->plural_item   = esc_html__('Line Items', 'event_espresso');
129
+
130
+		$this->_tables                 = [
131
+			'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID'),
132
+		];
133
+		$line_items_can_be_for         = apply_filters(
134
+			'FHEE__EEM_Line_Item__line_items_can_be_for',
135
+			['Ticket', 'Price', 'Event']
136
+		);
137
+		$this->_fields                 = [
138
+			'Line_Item' => [
139
+				'LIN_ID'         => new EE_Primary_Key_Int_Field(
140
+					'LIN_ID',
141
+					esc_html__('ID', 'event_espresso')
142
+				),
143
+				'LIN_code'       => new EE_Slug_Field(
144
+					'LIN_code',
145
+					esc_html__('Code for index into Cart', 'event_espresso'),
146
+					true
147
+				),
148
+				'TXN_ID'         => new EE_Foreign_Key_Int_Field(
149
+					'TXN_ID',
150
+					esc_html__('Transaction ID', 'event_espresso'),
151
+					true,
152
+					null,
153
+					'Transaction'
154
+				),
155
+				'LIN_name'       => new EE_Full_HTML_Field(
156
+					'LIN_name',
157
+					esc_html__('Line Item Name', 'event_espresso'),
158
+					false,
159
+					''
160
+				),
161
+				'LIN_desc'       => new EE_Full_HTML_Field(
162
+					'LIN_desc',
163
+					esc_html__('Line Item Description', 'event_espresso'),
164
+					true
165
+				),
166
+				'LIN_unit_price' => new EE_Money_Field(
167
+					'LIN_unit_price',
168
+					esc_html__('Unit Price', 'event_espresso'),
169
+					false,
170
+					0
171
+				),
172
+				'LIN_percent'    => new EE_Float_Field(
173
+					'LIN_percent',
174
+					esc_html__('Percent', 'event_espresso'),
175
+					false,
176
+					0
177
+				),
178
+				'LIN_is_taxable' => new EE_Boolean_Field(
179
+					'LIN_is_taxable',
180
+					esc_html__('Taxable', 'event_espresso'),
181
+					false,
182
+					false
183
+				),
184
+				'LIN_order'      => new EE_Integer_Field(
185
+					'LIN_order',
186
+					esc_html__('Order of Application towards total of parent', 'event_espresso'),
187
+					false,
188
+					1
189
+				),
190
+				'LIN_total'      => new EE_Money_Field(
191
+					'LIN_total',
192
+					esc_html__('Total (unit price x quantity)', 'event_espresso'),
193
+					false,
194
+					0
195
+				),
196
+				'LIN_quantity'   => new EE_Integer_Field(
197
+					'LIN_quantity',
198
+					esc_html__('Quantity', 'event_espresso'),
199
+					true,
200
+					1
201
+				),
202
+				'LIN_parent'     => new EE_Integer_Field(
203
+					'LIN_parent',
204
+					esc_html__(
205
+						"Parent ID (this item goes towards that Line Item's total)",
206
+						'event_espresso'
207
+					),
208
+					true,
209
+					null
210
+				),
211
+				'LIN_type'       => new EE_Enum_Text_Field(
212
+					'LIN_type',
213
+					esc_html__('Type', 'event_espresso'),
214
+					false,
215
+					'line-item',
216
+					[
217
+						self::type_line_item     => esc_html__('Line Item', 'event_espresso'),
218
+						self::type_sub_line_item => esc_html__('Sub-Item', 'event_espresso'),
219
+						self::type_sub_total     => esc_html__('Subtotal', 'event_espresso'),
220
+						self::type_tax_sub_total => esc_html__('Tax Subtotal', 'event_espresso'),
221
+						self::type_tax           => esc_html__('Tax', 'event_espresso'),
222
+						self::type_total         => esc_html__('Total', 'event_espresso'),
223
+						self::type_cancellation  => esc_html__('Cancellation', 'event_espresso'),
224
+					]
225
+				),
226
+				'OBJ_ID'         => new EE_Foreign_Key_Int_Field(
227
+					'OBJ_ID',
228
+					esc_html__('ID of Item purchased.', 'event_espresso'),
229
+					true,
230
+					null,
231
+					$line_items_can_be_for
232
+				),
233
+				'OBJ_type'       => new EE_Any_Foreign_Model_Name_Field(
234
+					'OBJ_type',
235
+					esc_html__('Model Name this Line Item is for', 'event_espresso'),
236
+					true,
237
+					null,
238
+					$line_items_can_be_for
239
+				),
240
+				'LIN_timestamp'  => new EE_Datetime_Field(
241
+					'LIN_timestamp',
242
+					esc_html__('When the line item was created', 'event_espresso'),
243
+					false,
244
+					EE_Datetime_Field::now,
245
+					$timezone
246
+				),
247
+			],
248
+		];
249
+		$this->_model_relations        = [
250
+			'Transaction' => new EE_Belongs_To_Relation(),
251
+			'Ticket'      => new EE_Belongs_To_Any_Relation(),
252
+			'Price'       => new EE_Belongs_To_Any_Relation(),
253
+			'Event'       => new EE_Belongs_To_Any_Relation(),
254
+		];
255
+		$this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
256
+		$this->_caps_slug              = 'transactions';
257
+		parent::__construct($timezone);
258
+	}
259
+
260
+
261
+	/**
262
+	 * Gets all the line items for this transaction of the given type
263
+	 *
264
+	 * @param string             $line_item_type like one of EEM_Line_Item::type_*
265
+	 * @param EE_Transaction|int $transaction
266
+	 * @return EE_Line_Item[]
267
+	 * @throws EE_Error
268
+	 * @throws InvalidArgumentException
269
+	 * @throws InvalidDataTypeException
270
+	 * @throws InvalidInterfaceException
271
+	 * @throws ReflectionException
272
+	 */
273
+	public function get_all_of_type_for_transaction(string $line_item_type, $transaction): array
274
+	{
275
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
276
+		return $this->get_all(
277
+			[
278
+				[
279
+					'LIN_type' => $line_item_type,
280
+					'TXN_ID'   => $transaction,
281
+				],
282
+			]
283
+		);
284
+	}
285
+
286
+
287
+	/**
288
+	 * Gets all line items unrelated to tickets that are normal line items
289
+	 * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
290
+	 *
291
+	 * @param EE_Transaction|int $transaction
292
+	 * @return EE_Line_Item[]
293
+	 * @throws EE_Error
294
+	 * @throws InvalidArgumentException
295
+	 * @throws InvalidDataTypeException
296
+	 * @throws InvalidInterfaceException
297
+	 * @throws ReflectionException
298
+	 */
299
+	public function get_all_non_ticket_line_items_for_transaction($transaction): array
300
+	{
301
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
302
+		return $this->get_all(
303
+			[
304
+				[
305
+					'LIN_type' => self::type_line_item,
306
+					'TXN_ID'   => $transaction,
307
+					'OR'       => [
308
+						'OBJ_type*notticket' => ['!=', EEM_Line_Item::OBJ_TYPE_TICKET],
309
+						'OBJ_type*null'      => ['IS_NULL'],
310
+					],
311
+				],
312
+			]
313
+		);
314
+	}
315
+
316
+
317
+	/**
318
+	 * Deletes line items with no transaction who have passed the transaction cutoff time.
319
+	 * This needs to be very efficient
320
+	 * because if there are spam bots afoot there will be LOTS of line items. Also MySQL doesn't allow a limit when
321
+	 * deleting and joining tables like this.
322
+	 *
323
+	 * @return int count of how many deleted
324
+	 * @throws EE_Error
325
+	 * @throws InvalidArgumentException
326
+	 * @throws InvalidDataTypeException
327
+	 * @throws InvalidInterfaceException
328
+	 */
329
+	public function delete_line_items_with_no_transaction(): int
330
+	{
331
+		global $wpdb;
332
+		$time_to_leave_alone = apply_filters(
333
+			'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone',
334
+			WEEK_IN_SECONDS
335
+		);
336
+		$query               = $wpdb->prepare(
337
+			'DELETE li
338 338
 				FROM ' . $this->table() . ' li
339 339
 				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
340 340
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
341
-            // use GMT time because that's what TXN_timestamps are in
342
-            date('Y-m-d H:i:s', time() - $time_to_leave_alone)
343
-        );
344
-        return $wpdb->query($query);
345
-    }
346
-
347
-
348
-    /**
349
-     * get_line_item_for_transaction_object
350
-     * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
351
-     *
352
-     * @param int           $TXN_ID
353
-     * @param EE_Base_Class $object
354
-     * @return EE_Line_Item[]
355
-     * @throws EE_Error
356
-     * @throws InvalidArgumentException
357
-     * @throws InvalidDataTypeException
358
-     * @throws InvalidInterfaceException
359
-     * @throws ReflectionException
360
-     */
361
-    public function get_line_item_for_transaction_object(int $TXN_ID, EE_Base_Class $object): array
362
-    {
363
-        return $this->get_all(
364
-            [
365
-                [
366
-                    'TXN_ID'   => $TXN_ID,
367
-                    'OBJ_type' => str_replace('EE_', '', get_class($object)),
368
-                    'OBJ_ID'   => $object->ID(),
369
-                ],
370
-            ]
371
-        );
372
-    }
373
-
374
-
375
-    /**
376
-     * get_object_line_items_for_transaction
377
-     * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
378
-     *
379
-     * @param int    $TXN_ID
380
-     * @param string $OBJ_type
381
-     * @param array  $OBJ_IDs
382
-     * @return EE_Line_Item[]
383
-     * @throws EE_Error
384
-     * @throws ReflectionException
385
-     */
386
-    public function get_object_line_items_for_transaction(
387
-        int $TXN_ID,
388
-        string $OBJ_type = EEM_Line_Item::OBJ_TYPE_EVENT,
389
-        array $OBJ_IDs = []
390
-    ): array {
391
-        $query_params = [
392
-            'OBJ_type' => $OBJ_type,
393
-            // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
394
-            'OBJ_ID'   => is_array($OBJ_IDs) && ! isset($OBJ_IDs['IN']) ? ['IN', $OBJ_IDs] : $OBJ_IDs,
395
-        ];
396
-        if ($TXN_ID) {
397
-            $query_params['TXN_ID'] = $TXN_ID;
398
-        }
399
-        return $this->get_all([$query_params]);
400
-    }
401
-
402
-
403
-    /**
404
-     * get_all_ticket_line_items_for_transaction
405
-     *
406
-     * @param EE_Transaction $transaction
407
-     * @return EE_Line_Item[]
408
-     * @throws EE_Error
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidDataTypeException
411
-     * @throws InvalidInterfaceException
412
-     * @throws ReflectionException
413
-     */
414
-    public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction): array
415
-    {
416
-        return $this->get_all(
417
-            [
418
-                [
419
-                    'TXN_ID'   => $transaction->ID(),
420
-                    'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TICKET,
421
-                ],
422
-            ]
423
-        );
424
-    }
425
-
426
-
427
-    /**
428
-     * get_ticket_line_item_for_transaction
429
-     *
430
-     * @param int $TXN_ID
431
-     * @param int $TKT_ID
432
-     * @return EE_Line_Item|null
433
-     * @throws EE_Error
434
-     * @throws InvalidArgumentException
435
-     * @throws InvalidDataTypeException
436
-     * @throws InvalidInterfaceException
437
-     * @throws ReflectionException
438
-     */
439
-    public function get_ticket_line_item_for_transaction(int $TXN_ID, int $TKT_ID): ?EE_Line_Item
440
-    {
441
-        return $this->get_one(
442
-            [
443
-                [
444
-                    'TXN_ID'   => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
445
-                    'OBJ_ID'   => $TKT_ID,
446
-                    'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TICKET,
447
-                ],
448
-            ]
449
-        );
450
-    }
451
-
452
-
453
-    /**
454
-     * get_existing_promotion_line_item
455
-     * searches the cart for existing line items for the specified promotion
456
-     *
457
-     * @param EE_Line_Item $parent_line_item
458
-     * @param EE_Promotion $promotion
459
-     * @return EE_Line_Item|null
460
-     * @throws EE_Error
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidDataTypeException
463
-     * @throws InvalidInterfaceException
464
-     * @throws ReflectionException
465
-     * @since 1.0.0
466
-     */
467
-    public function get_existing_promotion_line_item(
468
-        EE_Line_Item $parent_line_item,
469
-        EE_Promotion $promotion
470
-    ): ?EE_Line_Item {
471
-        return $this->get_one(
472
-            [
473
-                [
474
-                    'TXN_ID'     => $parent_line_item->TXN_ID(),
475
-                    'LIN_parent' => $parent_line_item->ID(),
476
-                    'OBJ_type'   => EEM_Line_Item::OBJ_TYPE_PROMOTION,
477
-                    'OBJ_ID'     => $promotion->ID(),
478
-                ],
479
-            ]
480
-        );
481
-    }
482
-
483
-
484
-    /**
485
-     * get_all_promotion_line_items
486
-     * searches the cart for any and all existing promotion line items
487
-     *
488
-     * @param EE_Line_Item $parent_line_item
489
-     * @return EE_Line_Item[]
490
-     * @throws EE_Error
491
-     * @throws InvalidArgumentException
492
-     * @throws InvalidDataTypeException
493
-     * @throws InvalidInterfaceException
494
-     * @throws ReflectionException
495
-     * @since   1.0.0
496
-     */
497
-    public function get_all_promotion_line_items(EE_Line_Item $parent_line_item): array
498
-    {
499
-        return $this->get_all(
500
-            [
501
-                [
502
-                    'TXN_ID'     => $parent_line_item->TXN_ID(),
503
-                    'LIN_parent' => $parent_line_item->ID(),
504
-                    'OBJ_type'   => EEM_Line_Item::OBJ_TYPE_PROMOTION,
505
-                ],
506
-            ]
507
-        );
508
-    }
509
-
510
-
511
-    /**
512
-     * Gets the registration's corresponding line item.
513
-     * Note: basically does NOT support having multiple line items for a single ticket,
514
-     * which would happen if some of the registrations had a price modifier while others didn't.
515
-     * In order to support that, we'd probably need a LIN_ID on registrations or something.
516
-     *
517
-     * @param EE_Registration $registration
518
-     * @return EE_Line_Item|null
519
-     * @throws EE_Error
520
-     * @throws ReflectionException
521
-     */
522
-    public function get_line_item_for_registration(EE_Registration $registration): ?EE_Line_Item
523
-    {
524
-        return $this->get_one($this->line_item_for_registration_query_params($registration));
525
-    }
526
-
527
-
528
-    /**
529
-     * Gets the query params used to retrieve a specific line item for the given registration
530
-     *
531
-     * @param EE_Registration $registration
532
-     * @param array           $original_query_params any extra query params you'd like to be merged with
533
-     * @return array @see
534
-     *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
535
-     * @throws EE_Error
536
-     */
537
-    public function line_item_for_registration_query_params(
538
-        EE_Registration $registration,
539
-        array $original_query_params = []
540
-    ): array {
541
-        return array_replace_recursive(
542
-            $original_query_params,
543
-            [
544
-                [
545
-                    'OBJ_ID'   => $registration->ticket_ID(),
546
-                    'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TICKET,
547
-                    'TXN_ID'   => $registration->transaction_ID(),
548
-                ],
549
-            ]
550
-        );
551
-    }
552
-
553
-
554
-    /**
555
-     * @return EE_Line_Item[]
556
-     * @throws InvalidInterfaceException
557
-     * @throws InvalidDataTypeException
558
-     * @throws EE_Error
559
-     * @throws InvalidArgumentException
560
-     * @throws ReflectionException
561
-     */
562
-    public function get_total_line_items_with_no_transaction(): array
563
-    {
564
-        return $this->get_total_line_items_for_carts();
565
-    }
566
-
567
-
568
-    /**
569
-     * @return EE_Line_Item[]
570
-     * @throws InvalidInterfaceException
571
-     * @throws InvalidDataTypeException
572
-     * @throws EE_Error
573
-     * @throws InvalidArgumentException
574
-     * @throws ReflectionException
575
-     */
576
-    public function get_total_line_items_for_active_carts(): array
577
-    {
578
-        return $this->get_total_line_items_for_carts(false);
579
-    }
580
-
581
-
582
-    /**
583
-     * @return EE_Line_Item[]
584
-     * @throws InvalidInterfaceException
585
-     * @throws InvalidDataTypeException
586
-     * @throws EE_Error
587
-     * @throws InvalidArgumentException
588
-     * @throws ReflectionException
589
-     */
590
-    public function get_total_line_items_for_expired_carts(): array
591
-    {
592
-        return $this->get_total_line_items_for_carts(true);
593
-    }
594
-
595
-
596
-    /**
597
-     * Returns an array of grand total line items where the TXN_ID is 0.
598
-     * If $expired is set to true, then only line items for expired sessions will be returned.
599
-     * If $expired is set to false, then only line items for active sessions will be returned.
600
-     *
601
-     * @param bool|null $expired
602
-     * @return EE_Line_Item[]
603
-     * @throws EE_Error
604
-     * @throws InvalidArgumentException
605
-     * @throws InvalidDataTypeException
606
-     * @throws InvalidInterfaceException
607
-     * @throws ReflectionException
608
-     */
609
-    private function get_total_line_items_for_carts(bool $expired = null): array
610
-    {
611
-        $where_params = [
612
-            'TXN_ID'   => 0,
613
-            'LIN_type' => 'total',
614
-        ];
615
-        if ($expired !== null) {
616
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
617
-            $session_lifespan              = LoaderFactory::getLoader()->getShared(
618
-                'EventEspresso\core\domain\values\session\SessionLifespan'
619
-            );
620
-            $expired                       = filter_var($expired, FILTER_VALIDATE_BOOLEAN);
621
-            $where_params['LIN_timestamp'] = [
622
-                $expired ? '<=' : '>',
623
-                $session_lifespan->expiration(),
624
-            ];
625
-        }
626
-        return $this->get_all([$where_params]);
627
-    }
628
-
629
-
630
-    /**
631
-     * Returns an array of ticket total line items where the TXN_ID is 0
632
-     * AND the timestamp is older than the session lifespan.
633
-     *
634
-     * @param int $timestamp
635
-     * @return EE_Line_Item[]
636
-     * @throws EE_Error
637
-     * @throws InvalidArgumentException
638
-     * @throws InvalidDataTypeException
639
-     * @throws InvalidInterfaceException
640
-     * @throws ReflectionException
641
-     */
642
-    public function getTicketLineItemsForExpiredCarts(int $timestamp = 0): array
643
-    {
644
-        if (! absint($timestamp)) {
645
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
646
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
647
-                'EventEspresso\core\domain\values\session\SessionLifespan'
648
-            );
649
-            $timestamp        = $session_lifespan->expiration();
650
-        }
651
-        return $this->get_all(
652
-            [
653
-                [
654
-                    'TXN_ID'        => 0,
655
-                    'OBJ_type'      => EEM_Line_Item::OBJ_TYPE_TICKET,
656
-                    'LIN_timestamp' => ['<=', $timestamp],
657
-                ],
658
-            ]
659
-        );
660
-    }
341
+			// use GMT time because that's what TXN_timestamps are in
342
+			date('Y-m-d H:i:s', time() - $time_to_leave_alone)
343
+		);
344
+		return $wpdb->query($query);
345
+	}
346
+
347
+
348
+	/**
349
+	 * get_line_item_for_transaction_object
350
+	 * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
351
+	 *
352
+	 * @param int           $TXN_ID
353
+	 * @param EE_Base_Class $object
354
+	 * @return EE_Line_Item[]
355
+	 * @throws EE_Error
356
+	 * @throws InvalidArgumentException
357
+	 * @throws InvalidDataTypeException
358
+	 * @throws InvalidInterfaceException
359
+	 * @throws ReflectionException
360
+	 */
361
+	public function get_line_item_for_transaction_object(int $TXN_ID, EE_Base_Class $object): array
362
+	{
363
+		return $this->get_all(
364
+			[
365
+				[
366
+					'TXN_ID'   => $TXN_ID,
367
+					'OBJ_type' => str_replace('EE_', '', get_class($object)),
368
+					'OBJ_ID'   => $object->ID(),
369
+				],
370
+			]
371
+		);
372
+	}
373
+
374
+
375
+	/**
376
+	 * get_object_line_items_for_transaction
377
+	 * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
378
+	 *
379
+	 * @param int    $TXN_ID
380
+	 * @param string $OBJ_type
381
+	 * @param array  $OBJ_IDs
382
+	 * @return EE_Line_Item[]
383
+	 * @throws EE_Error
384
+	 * @throws ReflectionException
385
+	 */
386
+	public function get_object_line_items_for_transaction(
387
+		int $TXN_ID,
388
+		string $OBJ_type = EEM_Line_Item::OBJ_TYPE_EVENT,
389
+		array $OBJ_IDs = []
390
+	): array {
391
+		$query_params = [
392
+			'OBJ_type' => $OBJ_type,
393
+			// if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
394
+			'OBJ_ID'   => is_array($OBJ_IDs) && ! isset($OBJ_IDs['IN']) ? ['IN', $OBJ_IDs] : $OBJ_IDs,
395
+		];
396
+		if ($TXN_ID) {
397
+			$query_params['TXN_ID'] = $TXN_ID;
398
+		}
399
+		return $this->get_all([$query_params]);
400
+	}
401
+
402
+
403
+	/**
404
+	 * get_all_ticket_line_items_for_transaction
405
+	 *
406
+	 * @param EE_Transaction $transaction
407
+	 * @return EE_Line_Item[]
408
+	 * @throws EE_Error
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws InvalidInterfaceException
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction): array
415
+	{
416
+		return $this->get_all(
417
+			[
418
+				[
419
+					'TXN_ID'   => $transaction->ID(),
420
+					'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TICKET,
421
+				],
422
+			]
423
+		);
424
+	}
425
+
426
+
427
+	/**
428
+	 * get_ticket_line_item_for_transaction
429
+	 *
430
+	 * @param int $TXN_ID
431
+	 * @param int $TKT_ID
432
+	 * @return EE_Line_Item|null
433
+	 * @throws EE_Error
434
+	 * @throws InvalidArgumentException
435
+	 * @throws InvalidDataTypeException
436
+	 * @throws InvalidInterfaceException
437
+	 * @throws ReflectionException
438
+	 */
439
+	public function get_ticket_line_item_for_transaction(int $TXN_ID, int $TKT_ID): ?EE_Line_Item
440
+	{
441
+		return $this->get_one(
442
+			[
443
+				[
444
+					'TXN_ID'   => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
445
+					'OBJ_ID'   => $TKT_ID,
446
+					'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TICKET,
447
+				],
448
+			]
449
+		);
450
+	}
451
+
452
+
453
+	/**
454
+	 * get_existing_promotion_line_item
455
+	 * searches the cart for existing line items for the specified promotion
456
+	 *
457
+	 * @param EE_Line_Item $parent_line_item
458
+	 * @param EE_Promotion $promotion
459
+	 * @return EE_Line_Item|null
460
+	 * @throws EE_Error
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidDataTypeException
463
+	 * @throws InvalidInterfaceException
464
+	 * @throws ReflectionException
465
+	 * @since 1.0.0
466
+	 */
467
+	public function get_existing_promotion_line_item(
468
+		EE_Line_Item $parent_line_item,
469
+		EE_Promotion $promotion
470
+	): ?EE_Line_Item {
471
+		return $this->get_one(
472
+			[
473
+				[
474
+					'TXN_ID'     => $parent_line_item->TXN_ID(),
475
+					'LIN_parent' => $parent_line_item->ID(),
476
+					'OBJ_type'   => EEM_Line_Item::OBJ_TYPE_PROMOTION,
477
+					'OBJ_ID'     => $promotion->ID(),
478
+				],
479
+			]
480
+		);
481
+	}
482
+
483
+
484
+	/**
485
+	 * get_all_promotion_line_items
486
+	 * searches the cart for any and all existing promotion line items
487
+	 *
488
+	 * @param EE_Line_Item $parent_line_item
489
+	 * @return EE_Line_Item[]
490
+	 * @throws EE_Error
491
+	 * @throws InvalidArgumentException
492
+	 * @throws InvalidDataTypeException
493
+	 * @throws InvalidInterfaceException
494
+	 * @throws ReflectionException
495
+	 * @since   1.0.0
496
+	 */
497
+	public function get_all_promotion_line_items(EE_Line_Item $parent_line_item): array
498
+	{
499
+		return $this->get_all(
500
+			[
501
+				[
502
+					'TXN_ID'     => $parent_line_item->TXN_ID(),
503
+					'LIN_parent' => $parent_line_item->ID(),
504
+					'OBJ_type'   => EEM_Line_Item::OBJ_TYPE_PROMOTION,
505
+				],
506
+			]
507
+		);
508
+	}
509
+
510
+
511
+	/**
512
+	 * Gets the registration's corresponding line item.
513
+	 * Note: basically does NOT support having multiple line items for a single ticket,
514
+	 * which would happen if some of the registrations had a price modifier while others didn't.
515
+	 * In order to support that, we'd probably need a LIN_ID on registrations or something.
516
+	 *
517
+	 * @param EE_Registration $registration
518
+	 * @return EE_Line_Item|null
519
+	 * @throws EE_Error
520
+	 * @throws ReflectionException
521
+	 */
522
+	public function get_line_item_for_registration(EE_Registration $registration): ?EE_Line_Item
523
+	{
524
+		return $this->get_one($this->line_item_for_registration_query_params($registration));
525
+	}
526
+
527
+
528
+	/**
529
+	 * Gets the query params used to retrieve a specific line item for the given registration
530
+	 *
531
+	 * @param EE_Registration $registration
532
+	 * @param array           $original_query_params any extra query params you'd like to be merged with
533
+	 * @return array @see
534
+	 *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
535
+	 * @throws EE_Error
536
+	 */
537
+	public function line_item_for_registration_query_params(
538
+		EE_Registration $registration,
539
+		array $original_query_params = []
540
+	): array {
541
+		return array_replace_recursive(
542
+			$original_query_params,
543
+			[
544
+				[
545
+					'OBJ_ID'   => $registration->ticket_ID(),
546
+					'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TICKET,
547
+					'TXN_ID'   => $registration->transaction_ID(),
548
+				],
549
+			]
550
+		);
551
+	}
552
+
553
+
554
+	/**
555
+	 * @return EE_Line_Item[]
556
+	 * @throws InvalidInterfaceException
557
+	 * @throws InvalidDataTypeException
558
+	 * @throws EE_Error
559
+	 * @throws InvalidArgumentException
560
+	 * @throws ReflectionException
561
+	 */
562
+	public function get_total_line_items_with_no_transaction(): array
563
+	{
564
+		return $this->get_total_line_items_for_carts();
565
+	}
566
+
567
+
568
+	/**
569
+	 * @return EE_Line_Item[]
570
+	 * @throws InvalidInterfaceException
571
+	 * @throws InvalidDataTypeException
572
+	 * @throws EE_Error
573
+	 * @throws InvalidArgumentException
574
+	 * @throws ReflectionException
575
+	 */
576
+	public function get_total_line_items_for_active_carts(): array
577
+	{
578
+		return $this->get_total_line_items_for_carts(false);
579
+	}
580
+
581
+
582
+	/**
583
+	 * @return EE_Line_Item[]
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws InvalidDataTypeException
586
+	 * @throws EE_Error
587
+	 * @throws InvalidArgumentException
588
+	 * @throws ReflectionException
589
+	 */
590
+	public function get_total_line_items_for_expired_carts(): array
591
+	{
592
+		return $this->get_total_line_items_for_carts(true);
593
+	}
594
+
595
+
596
+	/**
597
+	 * Returns an array of grand total line items where the TXN_ID is 0.
598
+	 * If $expired is set to true, then only line items for expired sessions will be returned.
599
+	 * If $expired is set to false, then only line items for active sessions will be returned.
600
+	 *
601
+	 * @param bool|null $expired
602
+	 * @return EE_Line_Item[]
603
+	 * @throws EE_Error
604
+	 * @throws InvalidArgumentException
605
+	 * @throws InvalidDataTypeException
606
+	 * @throws InvalidInterfaceException
607
+	 * @throws ReflectionException
608
+	 */
609
+	private function get_total_line_items_for_carts(bool $expired = null): array
610
+	{
611
+		$where_params = [
612
+			'TXN_ID'   => 0,
613
+			'LIN_type' => 'total',
614
+		];
615
+		if ($expired !== null) {
616
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
617
+			$session_lifespan              = LoaderFactory::getLoader()->getShared(
618
+				'EventEspresso\core\domain\values\session\SessionLifespan'
619
+			);
620
+			$expired                       = filter_var($expired, FILTER_VALIDATE_BOOLEAN);
621
+			$where_params['LIN_timestamp'] = [
622
+				$expired ? '<=' : '>',
623
+				$session_lifespan->expiration(),
624
+			];
625
+		}
626
+		return $this->get_all([$where_params]);
627
+	}
628
+
629
+
630
+	/**
631
+	 * Returns an array of ticket total line items where the TXN_ID is 0
632
+	 * AND the timestamp is older than the session lifespan.
633
+	 *
634
+	 * @param int $timestamp
635
+	 * @return EE_Line_Item[]
636
+	 * @throws EE_Error
637
+	 * @throws InvalidArgumentException
638
+	 * @throws InvalidDataTypeException
639
+	 * @throws InvalidInterfaceException
640
+	 * @throws ReflectionException
641
+	 */
642
+	public function getTicketLineItemsForExpiredCarts(int $timestamp = 0): array
643
+	{
644
+		if (! absint($timestamp)) {
645
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
646
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
647
+				'EventEspresso\core\domain\values\session\SessionLifespan'
648
+			);
649
+			$timestamp        = $session_lifespan->expiration();
650
+		}
651
+		return $this->get_all(
652
+			[
653
+				[
654
+					'TXN_ID'        => 0,
655
+					'OBJ_type'      => EEM_Line_Item::OBJ_TYPE_TICKET,
656
+					'LIN_timestamp' => ['<=', $timestamp],
657
+				],
658
+			]
659
+		);
660
+	}
661 661
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
             'FHEE__EEM_Line_Item__line_items_can_be_for',
135 135
             ['Ticket', 'Price', 'Event']
136 136
         );
137
-        $this->_fields                 = [
137
+        $this->_fields = [
138 138
             'Line_Item' => [
139 139
                 'LIN_ID'         => new EE_Primary_Key_Int_Field(
140 140
                     'LIN_ID',
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
                 ),
247 247
             ],
248 248
         ];
249
-        $this->_model_relations        = [
249
+        $this->_model_relations = [
250 250
             'Transaction' => new EE_Belongs_To_Relation(),
251 251
             'Ticket'      => new EE_Belongs_To_Any_Relation(),
252 252
             'Price'       => new EE_Belongs_To_Any_Relation(),
@@ -333,10 +333,10 @@  discard block
 block discarded – undo
333 333
             'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone',
334 334
             WEEK_IN_SECONDS
335 335
         );
336
-        $query               = $wpdb->prepare(
336
+        $query = $wpdb->prepare(
337 337
             'DELETE li
338
-				FROM ' . $this->table() . ' li
339
-				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
338
+				FROM ' . $this->table().' li
339
+				LEFT JOIN ' . EEM_Transaction::instance()->table().' t ON li.TXN_ID = t.TXN_ID
340 340
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
341 341
             // use GMT time because that's what TXN_timestamps are in
342 342
             date('Y-m-d H:i:s', time() - $time_to_leave_alone)
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
      */
642 642
     public function getTicketLineItemsForExpiredCarts(int $timestamp = 0): array
643 643
     {
644
-        if (! absint($timestamp)) {
644
+        if ( ! absint($timestamp)) {
645 645
             /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
646 646
             $session_lifespan = LoaderFactory::getLoader()->getShared(
647 647
                 'EventEspresso\core\domain\values\session\SessionLifespan'
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 2 patches
Indentation   +413 added lines, -413 removed lines patch added patch discarded remove patch
@@ -12,425 +12,425 @@
 block discarded – undo
12 12
 class EEM_Attendee extends EEM_CPT_Base
13 13
 {
14 14
 
15
-    // private instance of the Attendee object
16
-    protected static $_instance;
15
+	// private instance of the Attendee object
16
+	protected static $_instance;
17 17
 
18
-    /**
19
-     * QST_system for questions are strings not integers now,
20
-     * so these constants are deprecated.
21
-     * Please instead use the EEM_Attendee::system_question_* constants
22
-     *
23
-     * @deprecated
24
-     */
25
-    const fname_question_id = 1;
18
+	/**
19
+	 * QST_system for questions are strings not integers now,
20
+	 * so these constants are deprecated.
21
+	 * Please instead use the EEM_Attendee::system_question_* constants
22
+	 *
23
+	 * @deprecated
24
+	 */
25
+	const fname_question_id = 1;
26 26
 
27
-    /**
28
-     * @deprecated
29
-     */
30
-    const lname_question_id = 2;
27
+	/**
28
+	 * @deprecated
29
+	 */
30
+	const lname_question_id = 2;
31 31
 
32 32
 
33
-    /**
34
-     * @deprecated
35
-     */
36
-    const email_question_id = 3;
33
+	/**
34
+	 * @deprecated
35
+	 */
36
+	const email_question_id = 3;
37 37
 
38 38
 
39
-    /**
40
-     * @deprecated
41
-     */
42
-    const address_question_id = 4;
39
+	/**
40
+	 * @deprecated
41
+	 */
42
+	const address_question_id = 4;
43 43
 
44 44
 
45
-    /**
46
-     * @deprecated
47
-     */
48
-    const address2_question_id = 5;
49
-
50
-
51
-    /**
52
-     * @deprecated
53
-     */
54
-    const city_question_id = 6;
55
-
56
-
57
-    /**
58
-     * @deprecated
59
-     */
60
-    const state_question_id = 7;
61
-
62
-
63
-    /**
64
-     * @deprecated
65
-     */
66
-    const country_question_id = 8;
67
-
68
-
69
-    /**
70
-     * @deprecated
71
-     */
72
-    const zip_question_id = 9;
73
-
74
-
75
-    /**
76
-     * @deprecated
77
-     */
78
-    const phone_question_id = 10;
79
-
80
-    /**
81
-     * When looking for questions that correspond to attendee fields,
82
-     * look for the question with this QST_system value.
83
-     * These replace the old constants like EEM_Attendee::*_question_id
84
-     */
85
-    const system_question_fname         = 'fname';
86
-
87
-    const system_question_lname         = 'lname';
88
-
89
-    const system_question_email         = 'email';
90
-
91
-    const system_question_email_confirm = 'email_confirm';
92
-
93
-    const system_question_address       = 'address';
94
-
95
-    const system_question_address2      = 'address2';
96
-
97
-    const system_question_city          = 'city';
98
-
99
-    const system_question_state         = 'state';
100
-
101
-    const system_question_country       = 'country';
102
-
103
-    const system_question_zip           = 'zip';
104
-
105
-    const system_question_phone         = 'phone';
106
-
107
-    /**
108
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
109
-     * also all the values of QST_system in the questions table, and values
110
-     * are their corresponding Attendee field names
111
-     *
112
-     * @var array
113
-     */
114
-    protected $_system_question_to_attendee_field_name
115
-        = [
116
-            EEM_Attendee::system_question_fname    => 'ATT_fname',
117
-            EEM_Attendee::system_question_lname    => 'ATT_lname',
118
-            EEM_Attendee::system_question_email    => 'ATT_email',
119
-            EEM_Attendee::system_question_address  => 'ATT_address',
120
-            EEM_Attendee::system_question_address2 => 'ATT_address2',
121
-            EEM_Attendee::system_question_city     => 'ATT_city',
122
-            EEM_Attendee::system_question_state    => 'STA_ID',
123
-            EEM_Attendee::system_question_country  => 'CNT_ISO',
124
-            EEM_Attendee::system_question_zip      => 'ATT_zip',
125
-            EEM_Attendee::system_question_phone    => 'ATT_phone',
126
-        ];
127
-
128
-
129
-    /**
130
-     * EEM_Attendee constructor.
131
-     *
132
-     * @param string                 $timezone
133
-     * @param ModelFieldFactory|null $model_field_factory
134
-     * @throws EE_Error
135
-     * @throws InvalidArgumentException
136
-     */
137
-    protected function __construct(string $timezone = '', ModelFieldFactory $model_field_factory = null)
138
-    {
139
-        $this->singular_item           = esc_html__('Attendee', 'event_espresso');
140
-        $this->plural_item             = esc_html__('Attendees', 'event_espresso');
141
-        $this->_tables                 = [
142
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
143
-            'Attendee_Meta' => new EE_Secondary_Table(
144
-                'esp_attendee_meta',
145
-                'ATTM_ID',
146
-                'ATT_ID'
147
-            ),
148
-        ];
149
-        $this->_fields                 = [
150
-            'Attendee_CPT'  => [
151
-                'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
152
-                    'ID',
153
-                    esc_html__('Attendee ID', 'event_espresso')
154
-                ),
155
-                'ATT_full_name' => $model_field_factory->createPlainTextField(
156
-                    'post_title',
157
-                    esc_html__('Attendee Full Name', 'event_espresso'),
158
-                    false,
159
-                    esc_html__('Unknown', 'event_espresso')
160
-                ),
161
-                'ATT_bio'       => $model_field_factory->createPostContentField(
162
-                    'post_content',
163
-                    esc_html__('Attendee Biography', 'event_espresso'),
164
-                    false,
165
-                    esc_html__('No Biography Provided', 'event_espresso')
166
-                ),
167
-                'ATT_slug'      => $model_field_factory->createSlugField(
168
-                    'post_name',
169
-                    esc_html__('Attendee URL Slug', 'event_espresso')
170
-                ),
171
-                'ATT_created'   => $model_field_factory->createDatetimeField(
172
-                    'post_date',
173
-                    esc_html__('Time Attendee Created', 'event_espresso')
174
-                ),
175
-                'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
176
-                    'post_excerpt',
177
-                    esc_html__('Attendee Short Biography', 'event_espresso'),
178
-                    true,
179
-                    esc_html__('No Biography Provided', 'event_espresso')
180
-                ),
181
-                'ATT_modified'  => $model_field_factory->createDatetimeField(
182
-                    'post_modified',
183
-                    esc_html__('Time Attendee Last Modified', 'event_espresso')
184
-                ),
185
-                'ATT_author'    => $model_field_factory->createWpUserField(
186
-                    'post_author',
187
-                    esc_html__('Creator ID of the first Event attended', 'event_espresso'),
188
-                    false
189
-                ),
190
-                'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
191
-                    'post_parent',
192
-                    esc_html__('Parent Attendee (unused)', 'event_espresso'),
193
-                    false,
194
-                    0
195
-                ),
196
-                'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
197
-                'status'        => $model_field_factory->createWpPostStatusField(
198
-                    'post_status',
199
-                    esc_html__('Attendee Status', 'event_espresso'),
200
-                    false,
201
-                    'publish'
202
-                ),
203
-                'password'      => new EE_Password_Field(
204
-                    'post_password',
205
-                    esc_html__('Password', 'event_espresso'),
206
-                    false,
207
-                    '',
208
-                    [
209
-                        'ATT_bio',
210
-                        'ATT_short_bio',
211
-                        'ATT_address',
212
-                        'ATT_address2',
213
-                        'ATT_city',
214
-                        'STA_ID',
215
-                        'CNT_ISO',
216
-                        'ATT_zip',
217
-                        'ATT_email',
218
-                        'ATT_phone',
219
-                    ]
220
-                ),
221
-            ],
222
-            'Attendee_Meta' => [
223
-                'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
224
-                    'ATTM_ID',
225
-                    esc_html__('Attendee Meta Row ID', 'event_espresso'),
226
-                    false
227
-                ),
228
-                'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
229
-                    'ATT_ID',
230
-                    esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
231
-                    false
232
-                ),
233
-                'ATT_fname'    => $model_field_factory->createPlainTextField(
234
-                    'ATT_fname',
235
-                    esc_html__('First Name', 'event_espresso')
236
-                ),
237
-                'ATT_lname'    => $model_field_factory->createPlainTextField(
238
-                    'ATT_lname',
239
-                    esc_html__('Last Name', 'event_espresso')
240
-                ),
241
-                'ATT_address'  => $model_field_factory->createPlainTextField(
242
-                    'ATT_address',
243
-                    esc_html__('Address Part 1', 'event_espresso')
244
-                ),
245
-                'ATT_address2' => $model_field_factory->createPlainTextField(
246
-                    'ATT_address2',
247
-                    esc_html__('Address Part 2', 'event_espresso')
248
-                ),
249
-                'ATT_city'     => $model_field_factory->createPlainTextField(
250
-                    'ATT_city',
251
-                    esc_html__('City', 'event_espresso')
252
-                ),
253
-                'STA_ID'       => $model_field_factory->createForeignKeyIntField(
254
-                    'STA_ID',
255
-                    esc_html__('State', 'event_espresso'),
256
-                    true,
257
-                    0,
258
-                    'State'
259
-                ),
260
-                'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
261
-                    'CNT_ISO',
262
-                    esc_html__('Country', 'event_espresso'),
263
-                    true,
264
-                    '',
265
-                    'Country'
266
-                ),
267
-                'ATT_zip'      => $model_field_factory->createPlainTextField(
268
-                    'ATT_zip',
269
-                    esc_html__('ZIP/Postal Code', 'event_espresso')
270
-                ),
271
-                'ATT_email'    => $model_field_factory->createEmailField(
272
-                    'ATT_email',
273
-                    esc_html__('Email Address', 'event_espresso')
274
-                ),
275
-                'ATT_phone'    => $model_field_factory->createPlainTextField(
276
-                    'ATT_phone',
277
-                    esc_html__('Phone', 'event_espresso')
278
-                ),
279
-            ],
280
-        ];
281
-        $this->_model_relations        = [
282
-            'Registration'      => new EE_Has_Many_Relation(),
283
-            'State'             => new EE_Belongs_To_Relation(),
284
-            'Country'           => new EE_Belongs_To_Relation(),
285
-            'Event'             => new EE_HABTM_Relation('Registration', false),
286
-            'WP_User'           => new EE_Belongs_To_Relation(),
287
-            'Message'           => new EE_Has_Many_Any_Relation(false),
288
-            // allow deletion of attendees even if they have messages in the queue for them.
289
-            'Term_Relationship' => new EE_Has_Many_Relation(),
290
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
291
-        ];
292
-        $this->_caps_slug              = 'contacts';
293
-        $this->model_chain_to_password = '';
294
-        parent::__construct($timezone);
295
-    }
296
-
297
-
298
-    /**
299
-     * Gets the name of the field on the attendee model corresponding to the system question string
300
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
301
-     *
302
-     * @param string $system_question_string
303
-     * @return string|null if not found
304
-     */
305
-    public function get_attendee_field_for_system_question(string $system_question_string): ?string
306
-    {
307
-        return $this->_system_question_to_attendee_field_name[ $system_question_string ] ?? null;
308
-    }
309
-
310
-
311
-    /**
312
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
313
-     *
314
-     * @return array
315
-     */
316
-    public function system_question_to_attendee_field_mapping(): array
317
-    {
318
-        return $this->_system_question_to_attendee_field_name;
319
-    }
320
-
321
-
322
-    /**
323
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
324
-     *
325
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
326
-     * @return EE_Attendee[]|null
327
-     * @throws EE_Error
328
-     * @throws ReflectionException
329
-     */
330
-    public function get_attendees_for_transaction($transaction_id_or_obj): ?array
331
-    {
332
-        return $this->get_all(
333
-            [
334
-                [
335
-                    'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
336
-                        ? $transaction_id_or_obj->ID()
337
-                        : $transaction_id_or_obj,
338
-                ],
339
-            ]
340
-        );
341
-    }
342
-
343
-
344
-    /**
345
-     * retrieve  a single attendee from db via their ID
346
-     *
347
-     * @param int $ATT_ID
348
-     * @return EE_Attendee[]|null array on success, FALSE on fail
349
-     * @throws EE_Error
350
-     * @throws ReflectionException
351
-     * @deprecated
352
-     */
353
-    public function get_attendee_by_ID(int $ATT_ID = 0): ?EE_Attendee
354
-    {
355
-        // retrieve a particular EE_Attendee
356
-        return $this->get_one_by_ID($ATT_ID);
357
-    }
358
-
359
-
360
-    /**
361
-     * retrieve  a single attendee from db via their ID
362
-     *
363
-     * @param array $where_cols_n_values
364
-     * @return EE_Attendee|null entity on success, null on fail
365
-     * @throws EE_Error
366
-     * @throws ReflectionException
367
-     */
368
-    public function get_attendee(array $where_cols_n_values = []): ?EE_Attendee
369
-    {
370
-        if (empty($where_cols_n_values)) {
371
-            return null;
372
-        }
373
-        $attendee = $this->get_all([$where_cols_n_values]);
374
-        if (! empty($attendee)) {
375
-            return array_shift($attendee);
376
-        }
377
-        return null;
378
-    }
379
-
380
-
381
-    /**
382
-     * Search for an existing Attendee record in the DB
383
-     *
384
-     * @param array $where_cols_n_values
385
-     * @return EE_Attendee|null
386
-     * @throws EE_Error
387
-     * @throws ReflectionException
388
-     */
389
-    public function find_existing_attendee(array $where_cols_n_values = []): ?EE_Attendee
390
-    {
391
-        // search by combo of first and last names plus the email address
392
-        $attendee_data_keys = [
393
-            'ATT_fname' => $this->_ATT_fname,
394
-            'ATT_lname' => $this->_ATT_lname,
395
-            'ATT_email' => $this->_ATT_email,
396
-        ];
397
-        // no search params means attendee object already exists.
398
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
399
-            ? $where_cols_n_values
400
-            : $attendee_data_keys;
401
-        $valid_data          = true;
402
-        // check for required values
403
-        $valid_data = isset($where_cols_n_values['ATT_fname'])
404
-                      && ! empty($where_cols_n_values['ATT_fname'])
405
-                      && $valid_data;
406
-        $valid_data = isset($where_cols_n_values['ATT_lname'])
407
-                      && ! empty($where_cols_n_values['ATT_lname'])
408
-                      && $valid_data;
409
-        $valid_data = isset($where_cols_n_values['ATT_email'])
410
-                      && ! empty($where_cols_n_values['ATT_email'])
411
-                      && $valid_data;
412
-        if ($valid_data) {
413
-            $attendee = $this->get_attendee($where_cols_n_values);
414
-            if ($attendee instanceof EE_Attendee) {
415
-                return $attendee;
416
-            }
417
-        }
418
-        return null;
419
-    }
420
-
421
-
422
-    /**
423
-     * Takes an incoming array of EE_Registration ids
424
-     * and sends back a list of corresponding non duplicate EE_Attendee objects.
425
-     *
426
-     * @param array $ids array of EE_Registration ids
427
-     * @return EE_Attendee[]
428
-     * @throws EE_Error
429
-     * @throws ReflectionException
430
-     * @since  4.3.0
431
-     */
432
-    public function get_array_of_contacts_from_reg_ids(array $ids): array
433
-    {
434
-        return $this->get_all([['Registration.REG_ID' => ['in', $ids]]]);
435
-    }
45
+	/**
46
+	 * @deprecated
47
+	 */
48
+	const address2_question_id = 5;
49
+
50
+
51
+	/**
52
+	 * @deprecated
53
+	 */
54
+	const city_question_id = 6;
55
+
56
+
57
+	/**
58
+	 * @deprecated
59
+	 */
60
+	const state_question_id = 7;
61
+
62
+
63
+	/**
64
+	 * @deprecated
65
+	 */
66
+	const country_question_id = 8;
67
+
68
+
69
+	/**
70
+	 * @deprecated
71
+	 */
72
+	const zip_question_id = 9;
73
+
74
+
75
+	/**
76
+	 * @deprecated
77
+	 */
78
+	const phone_question_id = 10;
79
+
80
+	/**
81
+	 * When looking for questions that correspond to attendee fields,
82
+	 * look for the question with this QST_system value.
83
+	 * These replace the old constants like EEM_Attendee::*_question_id
84
+	 */
85
+	const system_question_fname         = 'fname';
86
+
87
+	const system_question_lname         = 'lname';
88
+
89
+	const system_question_email         = 'email';
90
+
91
+	const system_question_email_confirm = 'email_confirm';
92
+
93
+	const system_question_address       = 'address';
94
+
95
+	const system_question_address2      = 'address2';
96
+
97
+	const system_question_city          = 'city';
98
+
99
+	const system_question_state         = 'state';
100
+
101
+	const system_question_country       = 'country';
102
+
103
+	const system_question_zip           = 'zip';
104
+
105
+	const system_question_phone         = 'phone';
106
+
107
+	/**
108
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
109
+	 * also all the values of QST_system in the questions table, and values
110
+	 * are their corresponding Attendee field names
111
+	 *
112
+	 * @var array
113
+	 */
114
+	protected $_system_question_to_attendee_field_name
115
+		= [
116
+			EEM_Attendee::system_question_fname    => 'ATT_fname',
117
+			EEM_Attendee::system_question_lname    => 'ATT_lname',
118
+			EEM_Attendee::system_question_email    => 'ATT_email',
119
+			EEM_Attendee::system_question_address  => 'ATT_address',
120
+			EEM_Attendee::system_question_address2 => 'ATT_address2',
121
+			EEM_Attendee::system_question_city     => 'ATT_city',
122
+			EEM_Attendee::system_question_state    => 'STA_ID',
123
+			EEM_Attendee::system_question_country  => 'CNT_ISO',
124
+			EEM_Attendee::system_question_zip      => 'ATT_zip',
125
+			EEM_Attendee::system_question_phone    => 'ATT_phone',
126
+		];
127
+
128
+
129
+	/**
130
+	 * EEM_Attendee constructor.
131
+	 *
132
+	 * @param string                 $timezone
133
+	 * @param ModelFieldFactory|null $model_field_factory
134
+	 * @throws EE_Error
135
+	 * @throws InvalidArgumentException
136
+	 */
137
+	protected function __construct(string $timezone = '', ModelFieldFactory $model_field_factory = null)
138
+	{
139
+		$this->singular_item           = esc_html__('Attendee', 'event_espresso');
140
+		$this->plural_item             = esc_html__('Attendees', 'event_espresso');
141
+		$this->_tables                 = [
142
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
143
+			'Attendee_Meta' => new EE_Secondary_Table(
144
+				'esp_attendee_meta',
145
+				'ATTM_ID',
146
+				'ATT_ID'
147
+			),
148
+		];
149
+		$this->_fields                 = [
150
+			'Attendee_CPT'  => [
151
+				'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
152
+					'ID',
153
+					esc_html__('Attendee ID', 'event_espresso')
154
+				),
155
+				'ATT_full_name' => $model_field_factory->createPlainTextField(
156
+					'post_title',
157
+					esc_html__('Attendee Full Name', 'event_espresso'),
158
+					false,
159
+					esc_html__('Unknown', 'event_espresso')
160
+				),
161
+				'ATT_bio'       => $model_field_factory->createPostContentField(
162
+					'post_content',
163
+					esc_html__('Attendee Biography', 'event_espresso'),
164
+					false,
165
+					esc_html__('No Biography Provided', 'event_espresso')
166
+				),
167
+				'ATT_slug'      => $model_field_factory->createSlugField(
168
+					'post_name',
169
+					esc_html__('Attendee URL Slug', 'event_espresso')
170
+				),
171
+				'ATT_created'   => $model_field_factory->createDatetimeField(
172
+					'post_date',
173
+					esc_html__('Time Attendee Created', 'event_espresso')
174
+				),
175
+				'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
176
+					'post_excerpt',
177
+					esc_html__('Attendee Short Biography', 'event_espresso'),
178
+					true,
179
+					esc_html__('No Biography Provided', 'event_espresso')
180
+				),
181
+				'ATT_modified'  => $model_field_factory->createDatetimeField(
182
+					'post_modified',
183
+					esc_html__('Time Attendee Last Modified', 'event_espresso')
184
+				),
185
+				'ATT_author'    => $model_field_factory->createWpUserField(
186
+					'post_author',
187
+					esc_html__('Creator ID of the first Event attended', 'event_espresso'),
188
+					false
189
+				),
190
+				'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
191
+					'post_parent',
192
+					esc_html__('Parent Attendee (unused)', 'event_espresso'),
193
+					false,
194
+					0
195
+				),
196
+				'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
197
+				'status'        => $model_field_factory->createWpPostStatusField(
198
+					'post_status',
199
+					esc_html__('Attendee Status', 'event_espresso'),
200
+					false,
201
+					'publish'
202
+				),
203
+				'password'      => new EE_Password_Field(
204
+					'post_password',
205
+					esc_html__('Password', 'event_espresso'),
206
+					false,
207
+					'',
208
+					[
209
+						'ATT_bio',
210
+						'ATT_short_bio',
211
+						'ATT_address',
212
+						'ATT_address2',
213
+						'ATT_city',
214
+						'STA_ID',
215
+						'CNT_ISO',
216
+						'ATT_zip',
217
+						'ATT_email',
218
+						'ATT_phone',
219
+					]
220
+				),
221
+			],
222
+			'Attendee_Meta' => [
223
+				'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
224
+					'ATTM_ID',
225
+					esc_html__('Attendee Meta Row ID', 'event_espresso'),
226
+					false
227
+				),
228
+				'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
229
+					'ATT_ID',
230
+					esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
231
+					false
232
+				),
233
+				'ATT_fname'    => $model_field_factory->createPlainTextField(
234
+					'ATT_fname',
235
+					esc_html__('First Name', 'event_espresso')
236
+				),
237
+				'ATT_lname'    => $model_field_factory->createPlainTextField(
238
+					'ATT_lname',
239
+					esc_html__('Last Name', 'event_espresso')
240
+				),
241
+				'ATT_address'  => $model_field_factory->createPlainTextField(
242
+					'ATT_address',
243
+					esc_html__('Address Part 1', 'event_espresso')
244
+				),
245
+				'ATT_address2' => $model_field_factory->createPlainTextField(
246
+					'ATT_address2',
247
+					esc_html__('Address Part 2', 'event_espresso')
248
+				),
249
+				'ATT_city'     => $model_field_factory->createPlainTextField(
250
+					'ATT_city',
251
+					esc_html__('City', 'event_espresso')
252
+				),
253
+				'STA_ID'       => $model_field_factory->createForeignKeyIntField(
254
+					'STA_ID',
255
+					esc_html__('State', 'event_espresso'),
256
+					true,
257
+					0,
258
+					'State'
259
+				),
260
+				'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
261
+					'CNT_ISO',
262
+					esc_html__('Country', 'event_espresso'),
263
+					true,
264
+					'',
265
+					'Country'
266
+				),
267
+				'ATT_zip'      => $model_field_factory->createPlainTextField(
268
+					'ATT_zip',
269
+					esc_html__('ZIP/Postal Code', 'event_espresso')
270
+				),
271
+				'ATT_email'    => $model_field_factory->createEmailField(
272
+					'ATT_email',
273
+					esc_html__('Email Address', 'event_espresso')
274
+				),
275
+				'ATT_phone'    => $model_field_factory->createPlainTextField(
276
+					'ATT_phone',
277
+					esc_html__('Phone', 'event_espresso')
278
+				),
279
+			],
280
+		];
281
+		$this->_model_relations        = [
282
+			'Registration'      => new EE_Has_Many_Relation(),
283
+			'State'             => new EE_Belongs_To_Relation(),
284
+			'Country'           => new EE_Belongs_To_Relation(),
285
+			'Event'             => new EE_HABTM_Relation('Registration', false),
286
+			'WP_User'           => new EE_Belongs_To_Relation(),
287
+			'Message'           => new EE_Has_Many_Any_Relation(false),
288
+			// allow deletion of attendees even if they have messages in the queue for them.
289
+			'Term_Relationship' => new EE_Has_Many_Relation(),
290
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
291
+		];
292
+		$this->_caps_slug              = 'contacts';
293
+		$this->model_chain_to_password = '';
294
+		parent::__construct($timezone);
295
+	}
296
+
297
+
298
+	/**
299
+	 * Gets the name of the field on the attendee model corresponding to the system question string
300
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
301
+	 *
302
+	 * @param string $system_question_string
303
+	 * @return string|null if not found
304
+	 */
305
+	public function get_attendee_field_for_system_question(string $system_question_string): ?string
306
+	{
307
+		return $this->_system_question_to_attendee_field_name[ $system_question_string ] ?? null;
308
+	}
309
+
310
+
311
+	/**
312
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
313
+	 *
314
+	 * @return array
315
+	 */
316
+	public function system_question_to_attendee_field_mapping(): array
317
+	{
318
+		return $this->_system_question_to_attendee_field_name;
319
+	}
320
+
321
+
322
+	/**
323
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
324
+	 *
325
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
326
+	 * @return EE_Attendee[]|null
327
+	 * @throws EE_Error
328
+	 * @throws ReflectionException
329
+	 */
330
+	public function get_attendees_for_transaction($transaction_id_or_obj): ?array
331
+	{
332
+		return $this->get_all(
333
+			[
334
+				[
335
+					'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
336
+						? $transaction_id_or_obj->ID()
337
+						: $transaction_id_or_obj,
338
+				],
339
+			]
340
+		);
341
+	}
342
+
343
+
344
+	/**
345
+	 * retrieve  a single attendee from db via their ID
346
+	 *
347
+	 * @param int $ATT_ID
348
+	 * @return EE_Attendee[]|null array on success, FALSE on fail
349
+	 * @throws EE_Error
350
+	 * @throws ReflectionException
351
+	 * @deprecated
352
+	 */
353
+	public function get_attendee_by_ID(int $ATT_ID = 0): ?EE_Attendee
354
+	{
355
+		// retrieve a particular EE_Attendee
356
+		return $this->get_one_by_ID($ATT_ID);
357
+	}
358
+
359
+
360
+	/**
361
+	 * retrieve  a single attendee from db via their ID
362
+	 *
363
+	 * @param array $where_cols_n_values
364
+	 * @return EE_Attendee|null entity on success, null on fail
365
+	 * @throws EE_Error
366
+	 * @throws ReflectionException
367
+	 */
368
+	public function get_attendee(array $where_cols_n_values = []): ?EE_Attendee
369
+	{
370
+		if (empty($where_cols_n_values)) {
371
+			return null;
372
+		}
373
+		$attendee = $this->get_all([$where_cols_n_values]);
374
+		if (! empty($attendee)) {
375
+			return array_shift($attendee);
376
+		}
377
+		return null;
378
+	}
379
+
380
+
381
+	/**
382
+	 * Search for an existing Attendee record in the DB
383
+	 *
384
+	 * @param array $where_cols_n_values
385
+	 * @return EE_Attendee|null
386
+	 * @throws EE_Error
387
+	 * @throws ReflectionException
388
+	 */
389
+	public function find_existing_attendee(array $where_cols_n_values = []): ?EE_Attendee
390
+	{
391
+		// search by combo of first and last names plus the email address
392
+		$attendee_data_keys = [
393
+			'ATT_fname' => $this->_ATT_fname,
394
+			'ATT_lname' => $this->_ATT_lname,
395
+			'ATT_email' => $this->_ATT_email,
396
+		];
397
+		// no search params means attendee object already exists.
398
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
399
+			? $where_cols_n_values
400
+			: $attendee_data_keys;
401
+		$valid_data          = true;
402
+		// check for required values
403
+		$valid_data = isset($where_cols_n_values['ATT_fname'])
404
+					  && ! empty($where_cols_n_values['ATT_fname'])
405
+					  && $valid_data;
406
+		$valid_data = isset($where_cols_n_values['ATT_lname'])
407
+					  && ! empty($where_cols_n_values['ATT_lname'])
408
+					  && $valid_data;
409
+		$valid_data = isset($where_cols_n_values['ATT_email'])
410
+					  && ! empty($where_cols_n_values['ATT_email'])
411
+					  && $valid_data;
412
+		if ($valid_data) {
413
+			$attendee = $this->get_attendee($where_cols_n_values);
414
+			if ($attendee instanceof EE_Attendee) {
415
+				return $attendee;
416
+			}
417
+		}
418
+		return null;
419
+	}
420
+
421
+
422
+	/**
423
+	 * Takes an incoming array of EE_Registration ids
424
+	 * and sends back a list of corresponding non duplicate EE_Attendee objects.
425
+	 *
426
+	 * @param array $ids array of EE_Registration ids
427
+	 * @return EE_Attendee[]
428
+	 * @throws EE_Error
429
+	 * @throws ReflectionException
430
+	 * @since  4.3.0
431
+	 */
432
+	public function get_array_of_contacts_from_reg_ids(array $ids): array
433
+	{
434
+		return $this->get_all([['Registration.REG_ID' => ['in', $ids]]]);
435
+	}
436 436
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
                 'ATT_ID'
147 147
             ),
148 148
         ];
149
-        $this->_fields                 = [
149
+        $this->_fields = [
150 150
             'Attendee_CPT'  => [
151 151
                 'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
152 152
                     'ID',
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
                 ),
279 279
             ],
280 280
         ];
281
-        $this->_model_relations        = [
281
+        $this->_model_relations = [
282 282
             'Registration'      => new EE_Has_Many_Relation(),
283 283
             'State'             => new EE_Belongs_To_Relation(),
284 284
             'Country'           => new EE_Belongs_To_Relation(),
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
      */
305 305
     public function get_attendee_field_for_system_question(string $system_question_string): ?string
306 306
     {
307
-        return $this->_system_question_to_attendee_field_name[ $system_question_string ] ?? null;
307
+        return $this->_system_question_to_attendee_field_name[$system_question_string] ?? null;
308 308
     }
309 309
 
310 310
 
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
             return null;
372 372
         }
373 373
         $attendee = $this->get_all([$where_cols_n_values]);
374
-        if (! empty($attendee)) {
374
+        if ( ! empty($attendee)) {
375 375
             return array_shift($attendee);
376 376
         }
377 377
         return null;
Please login to merge, or discard this patch.
core/db_models/EEM_Datetime_Ticket.model.php 2 patches
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -11,77 +11,77 @@
 block discarded – undo
11 11
 {
12 12
 
13 13
 
14
-    // private instance of the EEM_Datetime_Ticket object
15
-    protected static $_instance;
14
+	// private instance of the EEM_Datetime_Ticket object
15
+	protected static $_instance;
16 16
 
17 17
 
18
-    /**
19
-     *      private constructor to prevent direct creation
20
-     *
21
-     * @Constructor
22
-     * @access private
23
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
24
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
25
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
26
-     *                         timezone in the 'timezone_string' wp option)
27
-     * @return void
28
-     * @throws EE_Error
29
-     */
30
-    protected function __construct(string $timezone = '')
31
-    {
32
-        $this->singular_item = esc_html__('Datetime Ticket', 'event_espresso');
33
-        $this->plural_item   = esc_html__('Datetime Tickets', 'event_espresso');
18
+	/**
19
+	 *      private constructor to prevent direct creation
20
+	 *
21
+	 * @Constructor
22
+	 * @access private
23
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
24
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
25
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
26
+	 *                         timezone in the 'timezone_string' wp option)
27
+	 * @return void
28
+	 * @throws EE_Error
29
+	 */
30
+	protected function __construct(string $timezone = '')
31
+	{
32
+		$this->singular_item = esc_html__('Datetime Ticket', 'event_espresso');
33
+		$this->plural_item   = esc_html__('Datetime Tickets', 'event_espresso');
34 34
 
35
-        $this->_tables          = [
36
-            'Datetime_Ticket' => new EE_Primary_Table(
37
-                'esp_datetime_ticket',
38
-                'DTK_ID'
39
-            ),
40
-        ];
41
-        $this->_fields          = [
42
-            'Datetime_Ticket' => [
43
-                'DTK_ID' => new EE_Primary_Key_Int_Field(
44
-                    'DTK_ID',
45
-                    esc_html__('Datetime Ticket ID', 'event_espresso')
46
-                ),
47
-                'DTT_ID' => new EE_Foreign_Key_Int_Field(
48
-                    'DTT_ID',
49
-                    esc_html__('The ID to the Datetime', 'event_espresso'),
50
-                    false,
51
-                    0,
52
-                    'Datetime'
53
-                ),
54
-                'TKT_ID' => new EE_Foreign_Key_Int_Field(
55
-                    'TKT_ID',
56
-                    esc_html__('The ID to the Ticket', 'event_espresso'),
57
-                    false,
58
-                    0,
59
-                    'Ticket'
60
-                ),
61
-            ],
62
-        ];
63
-        $this->_model_relations = [
64
-            'Ticket'   => new EE_Belongs_To_Relation(),
65
-            'Datetime' => new EE_Belongs_To_Relation(),
66
-        ];
67
-        // this model is generally available for reading
68
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
69
-            'Datetime.Event'
70
-        );
71
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
72
-                                                                  = new EE_Restriction_Generator_Event_Related_Protected(
73
-            'Datetime.Event'
74
-        );
75
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]
76
-                                                                  = new EE_Restriction_Generator_Event_Related_Protected(
77
-            'Datetime.Event'
78
-        );
79
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]
80
-                                                                  = new EE_Restriction_Generator_Event_Related_Protected(
81
-            'Datetime.Event',
82
-            EEM_Base::caps_edit
83
-        );
84
-        $this->model_chain_to_password                            = 'Datetime.Event';
85
-        parent::__construct($timezone);
86
-    }
35
+		$this->_tables          = [
36
+			'Datetime_Ticket' => new EE_Primary_Table(
37
+				'esp_datetime_ticket',
38
+				'DTK_ID'
39
+			),
40
+		];
41
+		$this->_fields          = [
42
+			'Datetime_Ticket' => [
43
+				'DTK_ID' => new EE_Primary_Key_Int_Field(
44
+					'DTK_ID',
45
+					esc_html__('Datetime Ticket ID', 'event_espresso')
46
+				),
47
+				'DTT_ID' => new EE_Foreign_Key_Int_Field(
48
+					'DTT_ID',
49
+					esc_html__('The ID to the Datetime', 'event_espresso'),
50
+					false,
51
+					0,
52
+					'Datetime'
53
+				),
54
+				'TKT_ID' => new EE_Foreign_Key_Int_Field(
55
+					'TKT_ID',
56
+					esc_html__('The ID to the Ticket', 'event_espresso'),
57
+					false,
58
+					0,
59
+					'Ticket'
60
+				),
61
+			],
62
+		];
63
+		$this->_model_relations = [
64
+			'Ticket'   => new EE_Belongs_To_Relation(),
65
+			'Datetime' => new EE_Belongs_To_Relation(),
66
+		];
67
+		// this model is generally available for reading
68
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
69
+			'Datetime.Event'
70
+		);
71
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
72
+																  = new EE_Restriction_Generator_Event_Related_Protected(
73
+			'Datetime.Event'
74
+		);
75
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]
76
+																  = new EE_Restriction_Generator_Event_Related_Protected(
77
+			'Datetime.Event'
78
+		);
79
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]
80
+																  = new EE_Restriction_Generator_Event_Related_Protected(
81
+			'Datetime.Event',
82
+			EEM_Base::caps_edit
83
+		);
84
+		$this->model_chain_to_password                            = 'Datetime.Event';
85
+		parent::__construct($timezone);
86
+	}
87 87
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -32,13 +32,13 @@  discard block
 block discarded – undo
32 32
         $this->singular_item = esc_html__('Datetime Ticket', 'event_espresso');
33 33
         $this->plural_item   = esc_html__('Datetime Tickets', 'event_espresso');
34 34
 
35
-        $this->_tables          = [
35
+        $this->_tables = [
36 36
             'Datetime_Ticket' => new EE_Primary_Table(
37 37
                 'esp_datetime_ticket',
38 38
                 'DTK_ID'
39 39
             ),
40 40
         ];
41
-        $this->_fields          = [
41
+        $this->_fields = [
42 42
             'Datetime_Ticket' => [
43 43
                 'DTK_ID' => new EE_Primary_Key_Int_Field(
44 44
                     'DTK_ID',
@@ -65,23 +65,23 @@  discard block
 block discarded – undo
65 65
             'Datetime' => new EE_Belongs_To_Relation(),
66 66
         ];
67 67
         // this model is generally available for reading
68
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
68
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public(
69 69
             'Datetime.Event'
70 70
         );
71
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ]
71
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin]
72 72
                                                                   = new EE_Restriction_Generator_Event_Related_Protected(
73 73
             'Datetime.Event'
74 74
         );
75
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]
75
+        $this->_cap_restriction_generators[EEM_Base::caps_edit]
76 76
                                                                   = new EE_Restriction_Generator_Event_Related_Protected(
77 77
             'Datetime.Event'
78 78
         );
79
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]
79
+        $this->_cap_restriction_generators[EEM_Base::caps_delete]
80 80
                                                                   = new EE_Restriction_Generator_Event_Related_Protected(
81 81
             'Datetime.Event',
82 82
             EEM_Base::caps_edit
83 83
         );
84
-        $this->model_chain_to_password                            = 'Datetime.Event';
84
+        $this->model_chain_to_password = 'Datetime.Event';
85 85
         parent::__construct($timezone);
86 86
     }
87 87
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Status.model.php 2 patches
Indentation   +310 added lines, -310 removed lines patch added patch discarded remove patch
@@ -10,325 +10,325 @@
 block discarded – undo
10 10
 class EEM_Status extends EEM_Base
11 11
 {
12 12
 
13
-    /**
14
-     * @var EEM_Status
15
-     */
16
-    protected static $_instance;
13
+	/**
14
+	 * @var EEM_Status
15
+	 */
16
+	protected static $_instance;
17 17
 
18 18
 
19
-    /**
20
-     * EEM_Status constructor.
21
-     *
22
-     * @param string $timezone
23
-     * @throws EE_Error
24
-     */
25
-    protected function __construct(string $timezone = '')
26
-    {
27
-        $this->singular_item    = esc_html__('Status', 'event_espresso');
28
-        $this->plural_item      = esc_html__('Stati', 'event_espresso');
29
-        $this->_tables          = [
30
-            'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
31
-        ];
32
-        $this->_fields          = [
33
-            'StatusTable' => [
34
-                'STS_ID'       => new EE_Primary_Key_String_Field(
35
-                    'STS_ID',
36
-                    esc_html__('Status ID', 'event_espresso')
37
-                ),
38
-                'STS_code'     => new EE_Plain_Text_Field(
39
-                    'STS_code',
40
-                    esc_html__('Status Code', 'event_espresso'),
41
-                    false,
42
-                    ''
43
-                ),
44
-                'STS_type'     => new EE_Enum_Text_Field(
45
-                    'STS_type',
46
-                    esc_html__("Type", "event_espresso"),
47
-                    false,
48
-                    'event',
49
-                    [
50
-                        'event'        => esc_html__("Event", "event_espresso"),// deprecated
51
-                        'registration' => esc_html__("Registration", "event_espresso"),
52
-                        'transaction'  => esc_html__("Transaction", "event_espresso"),
53
-                        'payment'      => esc_html__("Payment", "event_espresso"),
54
-                        'email'        => esc_html__("Email", "event_espresso"),
55
-                        'message'      => esc_html__("Message", "event_espresso"),
56
-                    ]
57
-                ),
58
-                'STS_can_edit' => new EE_Boolean_Field(
59
-                    'STS_can_edit',
60
-                    esc_html__('Editable?', 'event_espresso'),
61
-                    false,
62
-                    false
63
-                ),
64
-                'STS_desc'     => new EE_Simple_HTML_Field(
65
-                    'STS_desc',
66
-                    esc_html__("Description", "event_espresso"),
67
-                    false,
68
-                    ''
69
-                ),
70
-                'STS_open'     => new EE_Boolean_Field(
71
-                    'STS_open',
72
-                    esc_html__("Open?", "event_espresso"),
73
-                    false,
74
-                    false
75
-                ),
76
-            ],
77
-        ];
78
-        $this->_model_relations = [
79
-            'Registration' => new EE_Has_Many_Relation(),
80
-            'Transaction'  => new EE_Has_Many_Relation(),
81
-            'Payment'      => new EE_Has_Many_Relation(),
82
-        ];
83
-        // this model is generally available for reading
84
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
19
+	/**
20
+	 * EEM_Status constructor.
21
+	 *
22
+	 * @param string $timezone
23
+	 * @throws EE_Error
24
+	 */
25
+	protected function __construct(string $timezone = '')
26
+	{
27
+		$this->singular_item    = esc_html__('Status', 'event_espresso');
28
+		$this->plural_item      = esc_html__('Stati', 'event_espresso');
29
+		$this->_tables          = [
30
+			'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
31
+		];
32
+		$this->_fields          = [
33
+			'StatusTable' => [
34
+				'STS_ID'       => new EE_Primary_Key_String_Field(
35
+					'STS_ID',
36
+					esc_html__('Status ID', 'event_espresso')
37
+				),
38
+				'STS_code'     => new EE_Plain_Text_Field(
39
+					'STS_code',
40
+					esc_html__('Status Code', 'event_espresso'),
41
+					false,
42
+					''
43
+				),
44
+				'STS_type'     => new EE_Enum_Text_Field(
45
+					'STS_type',
46
+					esc_html__("Type", "event_espresso"),
47
+					false,
48
+					'event',
49
+					[
50
+						'event'        => esc_html__("Event", "event_espresso"),// deprecated
51
+						'registration' => esc_html__("Registration", "event_espresso"),
52
+						'transaction'  => esc_html__("Transaction", "event_espresso"),
53
+						'payment'      => esc_html__("Payment", "event_espresso"),
54
+						'email'        => esc_html__("Email", "event_espresso"),
55
+						'message'      => esc_html__("Message", "event_espresso"),
56
+					]
57
+				),
58
+				'STS_can_edit' => new EE_Boolean_Field(
59
+					'STS_can_edit',
60
+					esc_html__('Editable?', 'event_espresso'),
61
+					false,
62
+					false
63
+				),
64
+				'STS_desc'     => new EE_Simple_HTML_Field(
65
+					'STS_desc',
66
+					esc_html__("Description", "event_espresso"),
67
+					false,
68
+					''
69
+				),
70
+				'STS_open'     => new EE_Boolean_Field(
71
+					'STS_open',
72
+					esc_html__("Open?", "event_espresso"),
73
+					false,
74
+					false
75
+				),
76
+			],
77
+		];
78
+		$this->_model_relations = [
79
+			'Registration' => new EE_Has_Many_Relation(),
80
+			'Transaction'  => new EE_Has_Many_Relation(),
81
+			'Payment'      => new EE_Has_Many_Relation(),
82
+		];
83
+		// this model is generally available for reading
84
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
85 85
 
86
-        parent::__construct($timezone);
87
-    }
86
+		parent::__construct($timezone);
87
+	}
88 88
 
89 89
 
90
-    /**
91
-     * This method provides the localized singular or plural string for a given status id
92
-     *
93
-     * @param array   $statuses  This should be an array of statuses in the format array( $status_id, $status_code ).
94
-     *                           That way if there isn't a translation in the index we'll return the default code.
95
-     * @param boolean $plural    Whether to return plural string or not. Note, nearly all of the plural strings are the
96
-     *                           same as the singular (in English), however, this may NOT be the case with other
97
-     *                           languages
98
-     * @param string  $schema    This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
99
-     *                           the status string returned ( UPPER, lower, Sentence)
100
-     * @return array             an array of translated strings for the incoming status id.
101
-     * @throws EE_Error
102
-     */
103
-    public function localized_status(array $statuses, bool $plural = false, string $schema = 'upper'): array
104
-    {
105
-        // note these are all in lower case because ucwords() on upper case will NOT convert.
106
-        $translation_array = [
107
-            EEM_Registration::status_id_pending_payment => [
108
-                esc_html__('pending payment', 'event_espresso'), // singular
109
-                esc_html__('pending payments', 'event_espresso') // plural
110
-            ],
111
-            EEM_Registration::status_id_approved        => [
112
-                esc_html__('approved', 'event_espresso'), // singular
113
-                esc_html__('approved', 'event_espresso') // plural
114
-            ],
115
-            EEM_Registration::status_id_not_approved    => [
116
-                esc_html__('not approved', 'event_espresso'),
117
-                esc_html__('not approved', 'event_espresso'),
118
-            ],
119
-            EEM_Registration::status_id_cancelled       => [
120
-                esc_html__('cancelled', 'event_espresso'),
121
-                esc_html__('cancelled', 'event_espresso'),
122
-            ],
123
-            EEM_Registration::status_id_incomplete      => [
124
-                esc_html__('incomplete', 'event_espresso'),
125
-                esc_html__('incomplete', 'event_espresso'),
126
-            ],
127
-            EEM_Registration::status_id_declined        => [
128
-                esc_html__('declined', 'event_espresso'),
129
-                esc_html__('declined', 'event_espresso'),
130
-            ],
131
-            EEM_Registration::status_id_wait_list       => [
132
-                esc_html__('wait list', 'event_espresso'),
133
-                esc_html__('wait list', 'event_espresso'),
134
-            ],
135
-            EEM_Transaction::overpaid_status_code       => [
136
-                esc_html__('overpaid', 'event_espresso'),
137
-                esc_html__('overpaid', 'event_espresso'),
138
-            ],
139
-            EEM_Transaction::complete_status_code       => [
140
-                esc_html__('complete', 'event_espresso'),
141
-                esc_html__('complete', 'event_espresso'),
142
-            ],
143
-            EEM_Transaction::incomplete_status_code     => [
144
-                esc_html__('incomplete', 'event_espresso'),
145
-                esc_html__('incomplete', 'event_espresso'),
146
-            ],
147
-            EEM_Transaction::failed_status_code         => [
148
-                esc_html__('failed', 'event_espresso'),
149
-                esc_html__('failed', 'event_espresso'),
150
-            ],
151
-            EEM_Transaction::abandoned_status_code      => [
152
-                esc_html__('abandoned', 'event_espresso'),
153
-                esc_html__('abandoned', 'event_espresso'),
154
-            ],
155
-            EEM_Payment::status_id_approved             => [
156
-                esc_html__('accepted', 'event_espresso'),
157
-                esc_html__('accepted', 'event_espresso'),
158
-            ],
159
-            EEM_Payment::status_id_pending              => [
160
-                esc_html__('pending', 'event_espresso'),
161
-                esc_html__('pending', 'event_espresso'),
162
-            ],
163
-            EEM_Payment::status_id_cancelled            => [
164
-                esc_html__('cancelled', 'event_espresso'),
165
-                esc_html__('cancelled', 'event_espresso'),
166
-            ],
167
-            EEM_Payment::status_id_declined             => [
168
-                esc_html__('declined', 'event_espresso'),
169
-                esc_html__('declined', 'event_espresso'),
170
-            ],
171
-            EEM_Payment::status_id_failed               => [
172
-                esc_html__('failed', 'event_espresso'),
173
-                esc_html__('failed', 'event_espresso'),
174
-            ],
175
-            // following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
176
-            EEM_Event::sold_out                         => [
177
-                esc_html__('sold out', 'event_espresso'),
178
-                esc_html__('sold out', 'event_espresso'),
179
-            ],
180
-            EEM_Event::postponed                        => [
181
-                esc_html__('postponed', 'event_espresso'),
182
-                esc_html__('Postponed', 'event_espresso'),
183
-            ],
184
-            EEM_Event::cancelled                        => [
185
-                esc_html__('cancelled', 'event_espresso'),
186
-                esc_html__('cancelled', 'event_espresso'),
187
-            ],
188
-            EE_Ticket::archived                         => [
189
-                esc_html__('archived', 'event_espresso'),
190
-                esc_html__('archived', 'event_espresso'),
191
-            ],
192
-            EE_Ticket::expired                          => [
193
-                esc_html__('expired', 'event_espresso'),
194
-                esc_html__('expired', 'event_espresso'),
195
-            ],
196
-            EE_Ticket::sold_out                         => [
197
-                esc_html__('sold out', 'event_espresso'),
198
-                esc_html__('sold out', 'event_espresso'),
199
-            ],
200
-            EE_Ticket::pending                          => [
201
-                esc_html__('upcoming', 'event_espresso'),
202
-                esc_html__('upcoming', 'event_espresso'),
203
-            ],
204
-            EE_Ticket::onsale                           => [
205
-                esc_html__('on sale', 'event_espresso'),
206
-                esc_html__('on sale', 'event_espresso'),
207
-            ],
208
-            EE_Datetime::cancelled                      => [
209
-                esc_html__('cancelled', 'event_espresso'),
210
-                esc_html__('cancelled', 'event_espresso'),
211
-            ],
212
-            EE_Datetime::sold_out                       => [
213
-                esc_html__('sold out', 'event_espresso'),
214
-                esc_html__('sold out', 'event_espresso'),
215
-            ],
216
-            EE_Datetime::expired                        => [
217
-                esc_html__('expired', 'event_espresso'),
218
-                esc_html__('expired', 'event_espresso'),
219
-            ],
220
-            EE_Datetime::inactive                       => [
221
-                esc_html__('inactive', 'event_espresso'),
222
-                esc_html__('inactive', 'event_espresso'),
223
-            ],
224
-            EE_Datetime::upcoming                       => [
225
-                esc_html__('upcoming', 'event_espresso'),
226
-                esc_html__('upcoming', 'event_espresso'),
227
-            ],
228
-            EE_Datetime::active                         => [
229
-                esc_html__('active', 'event_espresso'),
230
-                esc_html__('active', 'event_espresso'),
231
-            ],
232
-            EE_Datetime::postponed                      => [
233
-                esc_html__('postponed', 'event_espresso'),
234
-                esc_html__('postponed', 'event_espresso'),
235
-            ],
236
-            // messages related
237
-            EEM_Message::status_sent                    => [
238
-                esc_html__('sent', 'event_espresso'),
239
-                esc_html__('sent', 'event_espresso'),
240
-            ],
241
-            EEM_Message::status_idle                    => [
242
-                esc_html__('queued for sending', 'event_espresso'),
243
-                esc_html__('queued for sending', 'event_espresso'),
244
-            ],
245
-            EEM_Message::status_failed                  => [
246
-                esc_html__('failed', 'event_espresso'),
247
-                esc_html__('failed', 'event_espresso'),
248
-            ],
249
-            EEM_Message::status_debug_only              => [
250
-                esc_html__('debug only', 'event_espresso'),
251
-                esc_html__('debug only', 'event_espresso'),
252
-            ],
253
-            EEM_Message::status_messenger_executing     => [
254
-                esc_html__('messenger is executing', 'event_espresso'),
255
-                esc_html__('messenger is executing', 'event_espresso'),
256
-            ],
257
-            EEM_Message::status_resend                  => [
258
-                esc_html__('queued for resending', 'event_espresso'),
259
-                esc_html__('queued for resending', 'event_espresso'),
260
-            ],
261
-            EEM_Message::status_incomplete              => [
262
-                esc_html__('queued for generating', 'event_espresso'),
263
-                esc_html__('queued for generating', 'event_espresso'),
264
-            ],
265
-            EEM_Message::status_retry                   => [
266
-                esc_html__('failed sending, can be retried', 'event_espresso'),
267
-                esc_html__('failed sending, can be retried', 'event_espresso'),
268
-            ],
269
-            EEM_CPT_Base::post_status_publish           => [
270
-                esc_html__('published', 'event_espresso'),
271
-                esc_html__('published', 'event_espresso'),
272
-            ],
273
-            EEM_CPT_Base::post_status_future            => [
274
-                esc_html__('scheduled', 'event_espresso'),
275
-                esc_html__('scheduled', 'event_espresso'),
276
-            ],
277
-            EEM_CPT_Base::post_status_draft             => [
278
-                esc_html__('draft', 'event_espresso'),
279
-                esc_html__('draft', 'event_espresso'),
280
-            ],
281
-            EEM_CPT_Base::post_status_pending           => [
282
-                esc_html__('pending', 'event_espresso'),
283
-                esc_html__('pending', 'event_espresso'),
284
-            ],
285
-            EEM_CPT_Base::post_status_private           => [
286
-                esc_html__('private', 'event_espresso'),
287
-                esc_html__('private', 'event_espresso'),
288
-            ],
289
-            EEM_CPT_Base::post_status_trashed           => [
290
-                esc_html__('trashed', 'event_espresso'),
291
-                esc_html__('trashed', 'event_espresso'),
292
-            ],
293
-        ];
90
+	/**
91
+	 * This method provides the localized singular or plural string for a given status id
92
+	 *
93
+	 * @param array   $statuses  This should be an array of statuses in the format array( $status_id, $status_code ).
94
+	 *                           That way if there isn't a translation in the index we'll return the default code.
95
+	 * @param boolean $plural    Whether to return plural string or not. Note, nearly all of the plural strings are the
96
+	 *                           same as the singular (in English), however, this may NOT be the case with other
97
+	 *                           languages
98
+	 * @param string  $schema    This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
99
+	 *                           the status string returned ( UPPER, lower, Sentence)
100
+	 * @return array             an array of translated strings for the incoming status id.
101
+	 * @throws EE_Error
102
+	 */
103
+	public function localized_status(array $statuses, bool $plural = false, string $schema = 'upper'): array
104
+	{
105
+		// note these are all in lower case because ucwords() on upper case will NOT convert.
106
+		$translation_array = [
107
+			EEM_Registration::status_id_pending_payment => [
108
+				esc_html__('pending payment', 'event_espresso'), // singular
109
+				esc_html__('pending payments', 'event_espresso') // plural
110
+			],
111
+			EEM_Registration::status_id_approved        => [
112
+				esc_html__('approved', 'event_espresso'), // singular
113
+				esc_html__('approved', 'event_espresso') // plural
114
+			],
115
+			EEM_Registration::status_id_not_approved    => [
116
+				esc_html__('not approved', 'event_espresso'),
117
+				esc_html__('not approved', 'event_espresso'),
118
+			],
119
+			EEM_Registration::status_id_cancelled       => [
120
+				esc_html__('cancelled', 'event_espresso'),
121
+				esc_html__('cancelled', 'event_espresso'),
122
+			],
123
+			EEM_Registration::status_id_incomplete      => [
124
+				esc_html__('incomplete', 'event_espresso'),
125
+				esc_html__('incomplete', 'event_espresso'),
126
+			],
127
+			EEM_Registration::status_id_declined        => [
128
+				esc_html__('declined', 'event_espresso'),
129
+				esc_html__('declined', 'event_espresso'),
130
+			],
131
+			EEM_Registration::status_id_wait_list       => [
132
+				esc_html__('wait list', 'event_espresso'),
133
+				esc_html__('wait list', 'event_espresso'),
134
+			],
135
+			EEM_Transaction::overpaid_status_code       => [
136
+				esc_html__('overpaid', 'event_espresso'),
137
+				esc_html__('overpaid', 'event_espresso'),
138
+			],
139
+			EEM_Transaction::complete_status_code       => [
140
+				esc_html__('complete', 'event_espresso'),
141
+				esc_html__('complete', 'event_espresso'),
142
+			],
143
+			EEM_Transaction::incomplete_status_code     => [
144
+				esc_html__('incomplete', 'event_espresso'),
145
+				esc_html__('incomplete', 'event_espresso'),
146
+			],
147
+			EEM_Transaction::failed_status_code         => [
148
+				esc_html__('failed', 'event_espresso'),
149
+				esc_html__('failed', 'event_espresso'),
150
+			],
151
+			EEM_Transaction::abandoned_status_code      => [
152
+				esc_html__('abandoned', 'event_espresso'),
153
+				esc_html__('abandoned', 'event_espresso'),
154
+			],
155
+			EEM_Payment::status_id_approved             => [
156
+				esc_html__('accepted', 'event_espresso'),
157
+				esc_html__('accepted', 'event_espresso'),
158
+			],
159
+			EEM_Payment::status_id_pending              => [
160
+				esc_html__('pending', 'event_espresso'),
161
+				esc_html__('pending', 'event_espresso'),
162
+			],
163
+			EEM_Payment::status_id_cancelled            => [
164
+				esc_html__('cancelled', 'event_espresso'),
165
+				esc_html__('cancelled', 'event_espresso'),
166
+			],
167
+			EEM_Payment::status_id_declined             => [
168
+				esc_html__('declined', 'event_espresso'),
169
+				esc_html__('declined', 'event_espresso'),
170
+			],
171
+			EEM_Payment::status_id_failed               => [
172
+				esc_html__('failed', 'event_espresso'),
173
+				esc_html__('failed', 'event_espresso'),
174
+			],
175
+			// following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
176
+			EEM_Event::sold_out                         => [
177
+				esc_html__('sold out', 'event_espresso'),
178
+				esc_html__('sold out', 'event_espresso'),
179
+			],
180
+			EEM_Event::postponed                        => [
181
+				esc_html__('postponed', 'event_espresso'),
182
+				esc_html__('Postponed', 'event_espresso'),
183
+			],
184
+			EEM_Event::cancelled                        => [
185
+				esc_html__('cancelled', 'event_espresso'),
186
+				esc_html__('cancelled', 'event_espresso'),
187
+			],
188
+			EE_Ticket::archived                         => [
189
+				esc_html__('archived', 'event_espresso'),
190
+				esc_html__('archived', 'event_espresso'),
191
+			],
192
+			EE_Ticket::expired                          => [
193
+				esc_html__('expired', 'event_espresso'),
194
+				esc_html__('expired', 'event_espresso'),
195
+			],
196
+			EE_Ticket::sold_out                         => [
197
+				esc_html__('sold out', 'event_espresso'),
198
+				esc_html__('sold out', 'event_espresso'),
199
+			],
200
+			EE_Ticket::pending                          => [
201
+				esc_html__('upcoming', 'event_espresso'),
202
+				esc_html__('upcoming', 'event_espresso'),
203
+			],
204
+			EE_Ticket::onsale                           => [
205
+				esc_html__('on sale', 'event_espresso'),
206
+				esc_html__('on sale', 'event_espresso'),
207
+			],
208
+			EE_Datetime::cancelled                      => [
209
+				esc_html__('cancelled', 'event_espresso'),
210
+				esc_html__('cancelled', 'event_espresso'),
211
+			],
212
+			EE_Datetime::sold_out                       => [
213
+				esc_html__('sold out', 'event_espresso'),
214
+				esc_html__('sold out', 'event_espresso'),
215
+			],
216
+			EE_Datetime::expired                        => [
217
+				esc_html__('expired', 'event_espresso'),
218
+				esc_html__('expired', 'event_espresso'),
219
+			],
220
+			EE_Datetime::inactive                       => [
221
+				esc_html__('inactive', 'event_espresso'),
222
+				esc_html__('inactive', 'event_espresso'),
223
+			],
224
+			EE_Datetime::upcoming                       => [
225
+				esc_html__('upcoming', 'event_espresso'),
226
+				esc_html__('upcoming', 'event_espresso'),
227
+			],
228
+			EE_Datetime::active                         => [
229
+				esc_html__('active', 'event_espresso'),
230
+				esc_html__('active', 'event_espresso'),
231
+			],
232
+			EE_Datetime::postponed                      => [
233
+				esc_html__('postponed', 'event_espresso'),
234
+				esc_html__('postponed', 'event_espresso'),
235
+			],
236
+			// messages related
237
+			EEM_Message::status_sent                    => [
238
+				esc_html__('sent', 'event_espresso'),
239
+				esc_html__('sent', 'event_espresso'),
240
+			],
241
+			EEM_Message::status_idle                    => [
242
+				esc_html__('queued for sending', 'event_espresso'),
243
+				esc_html__('queued for sending', 'event_espresso'),
244
+			],
245
+			EEM_Message::status_failed                  => [
246
+				esc_html__('failed', 'event_espresso'),
247
+				esc_html__('failed', 'event_espresso'),
248
+			],
249
+			EEM_Message::status_debug_only              => [
250
+				esc_html__('debug only', 'event_espresso'),
251
+				esc_html__('debug only', 'event_espresso'),
252
+			],
253
+			EEM_Message::status_messenger_executing     => [
254
+				esc_html__('messenger is executing', 'event_espresso'),
255
+				esc_html__('messenger is executing', 'event_espresso'),
256
+			],
257
+			EEM_Message::status_resend                  => [
258
+				esc_html__('queued for resending', 'event_espresso'),
259
+				esc_html__('queued for resending', 'event_espresso'),
260
+			],
261
+			EEM_Message::status_incomplete              => [
262
+				esc_html__('queued for generating', 'event_espresso'),
263
+				esc_html__('queued for generating', 'event_espresso'),
264
+			],
265
+			EEM_Message::status_retry                   => [
266
+				esc_html__('failed sending, can be retried', 'event_espresso'),
267
+				esc_html__('failed sending, can be retried', 'event_espresso'),
268
+			],
269
+			EEM_CPT_Base::post_status_publish           => [
270
+				esc_html__('published', 'event_espresso'),
271
+				esc_html__('published', 'event_espresso'),
272
+			],
273
+			EEM_CPT_Base::post_status_future            => [
274
+				esc_html__('scheduled', 'event_espresso'),
275
+				esc_html__('scheduled', 'event_espresso'),
276
+			],
277
+			EEM_CPT_Base::post_status_draft             => [
278
+				esc_html__('draft', 'event_espresso'),
279
+				esc_html__('draft', 'event_espresso'),
280
+			],
281
+			EEM_CPT_Base::post_status_pending           => [
282
+				esc_html__('pending', 'event_espresso'),
283
+				esc_html__('pending', 'event_espresso'),
284
+			],
285
+			EEM_CPT_Base::post_status_private           => [
286
+				esc_html__('private', 'event_espresso'),
287
+				esc_html__('private', 'event_espresso'),
288
+			],
289
+			EEM_CPT_Base::post_status_trashed           => [
290
+				esc_html__('trashed', 'event_espresso'),
291
+				esc_html__('trashed', 'event_espresso'),
292
+			],
293
+		];
294 294
 
295
-        $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
295
+		$translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
296 296
 
297
-        if (! is_array($statuses)) {
298
-            throw new EE_Error(
299
-               esc_html__(
300
-                   'The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
301
-                   'event_espresso'
302
-               )
303
-            );
304
-        }
297
+		if (! is_array($statuses)) {
298
+			throw new EE_Error(
299
+			   esc_html__(
300
+				   'The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
301
+				   'event_espresso'
302
+			   )
303
+			);
304
+		}
305 305
 
306
-        $translation = [];
306
+		$translation = [];
307 307
 
308
-        foreach ($statuses as $id => $code) {
309
-            if (isset($translation_array[ $id ])) {
310
-                $translation[ $id ] = $plural
311
-                    ? $translation_array[ $id ][1]
312
-                    : $translation_array[ $id ][0];
313
-            } else {
314
-                $translation[ $id ] = $code;
315
-            }
308
+		foreach ($statuses as $id => $code) {
309
+			if (isset($translation_array[ $id ])) {
310
+				$translation[ $id ] = $plural
311
+					? $translation_array[ $id ][1]
312
+					: $translation_array[ $id ][0];
313
+			} else {
314
+				$translation[ $id ] = $code;
315
+			}
316 316
 
317
-            // schema
318
-            switch ($schema) {
319
-                case 'lower':
320
-                    // even though these start in lower case, this will catch any statuses added via filter.
321
-                    $translation[ $id ] = strtolower($translation[ $id ]);
322
-                    break;
323
-                case 'sentence':
324
-                    $translation[ $id ] = ucwords($translation[ $id ]);
325
-                    break;
326
-                case 'upper':
327
-                    $translation[ $id ] = strtoupper($translation[ $id ]);
328
-                    break;
329
-            }
330
-        }
317
+			// schema
318
+			switch ($schema) {
319
+				case 'lower':
320
+					// even though these start in lower case, this will catch any statuses added via filter.
321
+					$translation[ $id ] = strtolower($translation[ $id ]);
322
+					break;
323
+				case 'sentence':
324
+					$translation[ $id ] = ucwords($translation[ $id ]);
325
+					break;
326
+				case 'upper':
327
+					$translation[ $id ] = strtoupper($translation[ $id ]);
328
+					break;
329
+			}
330
+		}
331 331
 
332
-        return $translation;
333
-    }
332
+		return $translation;
333
+	}
334 334
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
                     false,
48 48
                     'event',
49 49
                     [
50
-                        'event'        => esc_html__("Event", "event_espresso"),// deprecated
50
+                        'event'        => esc_html__("Event", "event_espresso"), // deprecated
51 51
                         'registration' => esc_html__("Registration", "event_espresso"),
52 52
                         'transaction'  => esc_html__("Transaction", "event_espresso"),
53 53
                         'payment'      => esc_html__("Payment", "event_espresso"),
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
             'Payment'      => new EE_Has_Many_Relation(),
82 82
         ];
83 83
         // this model is generally available for reading
84
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
84
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
85 85
 
86 86
         parent::__construct($timezone);
87 87
     }
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
 
295 295
         $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
296 296
 
297
-        if (! is_array($statuses)) {
297
+        if ( ! is_array($statuses)) {
298 298
             throw new EE_Error(
299 299
                esc_html__(
300 300
                    'The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
@@ -306,25 +306,25 @@  discard block
 block discarded – undo
306 306
         $translation = [];
307 307
 
308 308
         foreach ($statuses as $id => $code) {
309
-            if (isset($translation_array[ $id ])) {
310
-                $translation[ $id ] = $plural
311
-                    ? $translation_array[ $id ][1]
312
-                    : $translation_array[ $id ][0];
309
+            if (isset($translation_array[$id])) {
310
+                $translation[$id] = $plural
311
+                    ? $translation_array[$id][1]
312
+                    : $translation_array[$id][0];
313 313
             } else {
314
-                $translation[ $id ] = $code;
314
+                $translation[$id] = $code;
315 315
             }
316 316
 
317 317
             // schema
318 318
             switch ($schema) {
319 319
                 case 'lower':
320 320
                     // even though these start in lower case, this will catch any statuses added via filter.
321
-                    $translation[ $id ] = strtolower($translation[ $id ]);
321
+                    $translation[$id] = strtolower($translation[$id]);
322 322
                     break;
323 323
                 case 'sentence':
324
-                    $translation[ $id ] = ucwords($translation[ $id ]);
324
+                    $translation[$id] = ucwords($translation[$id]);
325 325
                     break;
326 326
                 case 'upper':
327
-                    $translation[ $id ] = strtoupper($translation[ $id ]);
327
+                    $translation[$id] = strtoupper($translation[$id]);
328 328
                     break;
329 329
             }
330 330
         }
Please login to merge, or discard this patch.
core/db_models/relations/EE_Model_Relation_Base.php 2 patches
Indentation   +507 added lines, -507 removed lines patch added patch discarded remove patch
@@ -16,512 +16,512 @@
 block discarded – undo
16 16
  */
17 17
 abstract class EE_Model_Relation_Base implements HasSchemaInterface
18 18
 {
19
-    /**
20
-     * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
21
-     *
22
-     * @var string eg Event, Question_Group, Registration
23
-     */
24
-    private $_this_model_name;
25
-    /**
26
-     * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
27
-     *
28
-     * @var string eg Event, Question_Group, Registration
29
-     */
30
-    private $_other_model_name;
31
-
32
-    /**
33
-     * this is typically used when calling the relation models to make sure they inherit any set timezone from the
34
-     * initiating model.
35
-     *
36
-     * @var string
37
-     */
38
-    protected $_timezone;
39
-
40
-    /**
41
-     * If you try to delete "this_model", and there are related "other_models",
42
-     * and this isn't null, then abandon the deletion and add this warning.
43
-     * This effectively makes it impossible to delete "this_model" while there are
44
-     * related "other_models" along this relation.
45
-     *
46
-     * @var string (internationalized)
47
-     */
48
-    protected $_blocking_delete_error_message;
49
-
50
-    protected $_blocking_delete = false;
51
-
52
-    /**
53
-     * Object representing the relationship between two models. This knows how to join the models,
54
-     * get related models across the relation, and add-and-remove the relationships.
55
-     *
56
-     * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
57
-     *                                               and add an error) the deletion of this model
58
-     * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
59
-     *                                               default
60
-     */
61
-    public function __construct($block_deletes, $blocking_delete_error_message)
62
-    {
63
-        $this->_blocking_delete               = $block_deletes;
64
-        $this->_blocking_delete_error_message = $blocking_delete_error_message;
65
-    }
66
-
67
-
68
-    /**
69
-     * @param $this_model_name
70
-     * @param $other_model_name
71
-     * @throws EE_Error
72
-     */
73
-    public function _construct_finalize_set_models($this_model_name, $other_model_name)
74
-    {
75
-        $this->_this_model_name  = $this_model_name;
76
-        $this->_other_model_name = $other_model_name;
77
-        if (is_string($this->_blocking_delete)) {
78
-            throw new EE_Error(sprintf(
79
-                esc_html__(
80
-                    "When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
81
-                    "event_espresso"
82
-                ),
83
-                get_class($this),
84
-                $this_model_name,
85
-                $other_model_name,
86
-                $this->_blocking_delete
87
-            ));
88
-        }
89
-    }
90
-
91
-
92
-    /**
93
-     * Gets the model where this relation is defined.
94
-     *
95
-     * @return EEM_Base
96
-     */
97
-    public function get_this_model()
98
-    {
99
-        return $this->_get_model($this->_this_model_name);
100
-    }
101
-
102
-
103
-    /**
104
-     * Gets the model which this relation establishes the relation TO (ie,
105
-     * this relation object was defined on get_this_model(), get_other_model() is the other one)
106
-     *
107
-     * @return EEM_Base
108
-     */
109
-    public function get_other_model()
110
-    {
111
-        return $this->_get_model($this->_other_model_name);
112
-    }
113
-
114
-
115
-    /**
116
-     * Internally used by get_this_model() and get_other_model()
117
-     *
118
-     * @param string $model_name like Event, Question_Group, etc. omit the EEM_
119
-     * @return EEM_Base
120
-     * @throws EE_Error
121
-     * @throws ReflectionException
122
-     */
123
-    protected function _get_model($model_name)
124
-    {
125
-        $modelInstance = EE_Registry::instance()->load_model($model_name);
126
-        // if the timezone is NOT set on the model but IS set for this relation
127
-        // (which seems really unlikely to ever happen, but whatever)
128
-        // make sure the model timezone is set
129
-        if ($this->_timezone && ! $modelInstance->get_timezone()) {
130
-            $modelInstance->set_timezone($this->_timezone);
131
-        }
132
-        return $modelInstance;
133
-    }
134
-
135
-
136
-    /**
137
-     * entirely possible that relations may be called from a model and we need to make sure those relations have their
138
-     * timezone set correctly.
139
-     *
140
-     * @param string $timezone timezone to set.
141
-     */
142
-    public function set_timezone($timezone)
143
-    {
144
-        if (! empty($timezone)) {
145
-            $this->_timezone = $timezone;
146
-        }
147
-    }
148
-
149
-
150
-    /**
151
-     * @param        $other_table
152
-     * @param        $other_table_alias
153
-     * @param        $other_table_column
154
-     * @param        $this_table_alias
155
-     * @param        $this_table_join_column
156
-     * @param string $extra_join_sql
157
-     * @return string
158
-     */
159
-    protected function _left_join(
160
-        $other_table,
161
-        $other_table_alias,
162
-        $other_table_column,
163
-        $this_table_alias,
164
-        $this_table_join_column,
165
-        $extra_join_sql = ''
166
-    ) {
167
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
168
-    }
169
-
170
-
171
-    /**
172
-     * Gets all the model objects of type of other model related to $model_object,
173
-     * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
174
-     * For both of those child classes, $model_object must be saved so that it has an ID before querying,
175
-     * otherwise an error will be thrown. Note: by default we disable default_where_conditions
176
-     * EE_Belongs_To_Relation doesn't need to be saved before querying.
177
-     *
178
-     * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
179
-     * @param array             $query_params                            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
180
-     * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
181
-     * @return EE_Base_Class[]
182
-     * @throws EE_Error
183
-     * @throws ReflectionException
184
-     */
185
-    public function get_all_related(
186
-        $model_object_or_id,
187
-        $query_params = array(),
188
-        $values_already_prepared_by_model_object = false
189
-    ) {
190
-        if ($values_already_prepared_by_model_object !== false) {
191
-            EE_Error::doing_it_wrong(
192
-                'EE_Model_Relation_Base::get_all_related',
193
-                esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
194
-                '4.8.1'
195
-            );
196
-        }
197
-        $query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
198
-        $query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
199
-                                                             . "."
200
-                                                             . $this->get_this_model()->get_primary_key_field()->get_name();
201
-        $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
202
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
203
-        return $this->get_other_model()->get_all($query_params);
204
-    }
205
-
206
-
207
-    /**
208
-     * Alters the $query_params to disable default where conditions, unless otherwise specified
209
-     *
210
-     * @param array $query_params
211
-     * @return array
212
-     */
213
-    protected function _disable_default_where_conditions_on_query_param($query_params)
214
-    {
215
-        if (! isset($query_params['default_where_conditions'])) {
216
-            $query_params['default_where_conditions'] = 'none';
217
-        }
218
-        return $query_params;
219
-    }
220
-
221
-
222
-    /**
223
-     * Deletes the related model objects which meet the query parameters. If no
224
-     * parameters are specified, then all related model objects will be deleted.
225
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
226
-     * model objects will only be soft-deleted.
227
-     *
228
-     * @param EE_Base_Class|int|string $model_object_or_id
229
-     * @param array                    $query_params
230
-     * @return int of how many related models got deleted
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function delete_all_related($model_object_or_id, $query_params = array())
235
-    {
236
-        // for each thing we would delete,
237
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
238
-        // determine if it's blocked by anything else before it can be deleted
239
-        $deleted_count = 0;
240
-        foreach ($related_model_objects as $related_model_object) {
241
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
242
-                $related_model_object,
243
-                $model_object_or_id
244
-            );
245
-            /* @var $model_object_or_id EE_Base_Class */
246
-            if (! $delete_is_blocked) {
247
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
248
-                $related_model_object->delete();
249
-                $deleted_count++;
250
-            }
251
-        }
252
-        return $deleted_count;
253
-    }
254
-
255
-
256
-    /**
257
-     * Deletes the related model objects which meet the query parameters. If no
258
-     * parameters are specified, then all related model objects will be deleted.
259
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
260
-     * model objects will only be soft-deleted.
261
-     *
262
-     * @param EE_Base_Class|int|string $model_object_or_id
263
-     * @param array                    $query_params
264
-     * @return int of how many related models got deleted
265
-     * @throws EE_Error
266
-     * @throws ReflectionException
267
-     */
268
-    public function delete_related_permanently($model_object_or_id, $query_params = array())
269
-    {
270
-        // for each thing we would delete,
271
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
272
-        // determine if it's blocked by anything else before it can be deleted
273
-        $deleted_count = 0;
274
-        foreach ($related_model_objects as $related_model_object) {
275
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
276
-                $related_model_object,
277
-                $model_object_or_id
278
-            );
279
-            /* @var $model_object_or_id EE_Base_Class */
280
-            if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
281
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
282
-                $deleted_count++;
283
-                if (! $delete_is_blocked) {
284
-                    $related_model_object->delete_permanently();
285
-                } else {
286
-                    // delete is blocked
287
-                    // brent and darren, in this case, wanted to just soft delete it then
288
-                    $related_model_object->delete();
289
-                }
290
-            } else {
291
-                // its not a soft-deletable thing anyways. do the normal logic.
292
-                if (! $delete_is_blocked) {
293
-                    $this->remove_relation_to($model_object_or_id, $related_model_object);
294
-                    $related_model_object->delete();
295
-                    $deleted_count++;
296
-                }
297
-            }
298
-        }
299
-        return $deleted_count;
300
-    }
301
-
302
-
303
-    /**
304
-     * this just returns a model_object_id for incoming item that could be an object or id.
305
-     *
306
-     * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
307
-     * @throws EE_Error
308
-     * @return int
309
-     */
310
-    protected function _get_model_object_id($model_object_or_id)
311
-    {
312
-        $model_object_id = $model_object_or_id;
313
-        if ($model_object_or_id instanceof EE_Base_Class) {
314
-            $model_object_id = $model_object_or_id->ID();
315
-        }
316
-        if (! $model_object_id) {
317
-            throw new EE_Error(sprintf(
318
-                esc_html__(
319
-                    "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
320
-                    "event_espresso"
321
-                ),
322
-                $this->get_other_model()->get_this_model_name(),
323
-                $this->get_this_model()->get_this_model_name()
324
-            ));
325
-        }
326
-        return $model_object_id;
327
-    }
328
-
329
-
330
-    /**
331
-     * Gets the SQL string for performing the join between this model and the other model.
332
-     *
333
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
334
-     * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
335
-     *                other_model_primary_table.fk" etc
336
-     */
337
-    abstract public function get_join_statement($model_relation_chain);
338
-
339
-
340
-    /**
341
-     * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
342
-     * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
343
-     * relationship only allows this model to be related to a single other model of this type)
344
-     *
345
-     * @param       $this_obj_or_id
346
-     * @param       $other_obj_or_id
347
-     * @param array $extra_join_model_fields_n_values
348
-     * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
349
-     *                        $other_obj_or_id)
350
-     */
351
-    abstract public function add_relation_to(
352
-        $this_obj_or_id,
353
-        $other_obj_or_id,
354
-        $extra_join_model_fields_n_values = array()
355
-    );
356
-
357
-
358
-    /**
359
-     * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
360
-     * model objects
361
-     *
362
-     * @param       $this_obj_or_id
363
-     * @param       $other_obj_or_id
364
-     * @param array $where_query
365
-     * @return bool
366
-     */
367
-    abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
368
-
369
-
370
-    /**
371
-     * Removes ALL relation instances for this relation obj
372
-     *
373
-     * @param EE_Base_Class|int $this_obj_or_id
374
-     * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
375
-     * @return EE_Base_Class[]
376
-     * @throws \EE_Error
377
-     */
378
-    public function remove_relations($this_obj_or_id, $where_query_param = array())
379
-    {
380
-        $related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
381
-        $objs_removed   = array();
382
-        foreach ($related_things as $related_thing) {
383
-            $objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
384
-        }
385
-        return $objs_removed;
386
-    }
387
-
388
-
389
-    /**
390
-     * If you aren't allowed to delete this model when there are related models across this
391
-     * relation object, return true. Otherwise, if you can delete this model even though
392
-     * related objects exist, returns false.
393
-     *
394
-     * @return boolean
395
-     */
396
-    public function block_delete_if_related_models_exist()
397
-    {
398
-        return $this->_blocking_delete;
399
-    }
400
-
401
-
402
-    /**
403
-     * Gets the error message to show
404
-     *
405
-     * @return string
406
-     */
407
-    public function get_deletion_error_message()
408
-    {
409
-        if ($this->_blocking_delete_error_message) {
410
-            return $this->_blocking_delete_error_message;
411
-        } else {
19
+	/**
20
+	 * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
21
+	 *
22
+	 * @var string eg Event, Question_Group, Registration
23
+	 */
24
+	private $_this_model_name;
25
+	/**
26
+	 * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
27
+	 *
28
+	 * @var string eg Event, Question_Group, Registration
29
+	 */
30
+	private $_other_model_name;
31
+
32
+	/**
33
+	 * this is typically used when calling the relation models to make sure they inherit any set timezone from the
34
+	 * initiating model.
35
+	 *
36
+	 * @var string
37
+	 */
38
+	protected $_timezone;
39
+
40
+	/**
41
+	 * If you try to delete "this_model", and there are related "other_models",
42
+	 * and this isn't null, then abandon the deletion and add this warning.
43
+	 * This effectively makes it impossible to delete "this_model" while there are
44
+	 * related "other_models" along this relation.
45
+	 *
46
+	 * @var string (internationalized)
47
+	 */
48
+	protected $_blocking_delete_error_message;
49
+
50
+	protected $_blocking_delete = false;
51
+
52
+	/**
53
+	 * Object representing the relationship between two models. This knows how to join the models,
54
+	 * get related models across the relation, and add-and-remove the relationships.
55
+	 *
56
+	 * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
57
+	 *                                               and add an error) the deletion of this model
58
+	 * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
59
+	 *                                               default
60
+	 */
61
+	public function __construct($block_deletes, $blocking_delete_error_message)
62
+	{
63
+		$this->_blocking_delete               = $block_deletes;
64
+		$this->_blocking_delete_error_message = $blocking_delete_error_message;
65
+	}
66
+
67
+
68
+	/**
69
+	 * @param $this_model_name
70
+	 * @param $other_model_name
71
+	 * @throws EE_Error
72
+	 */
73
+	public function _construct_finalize_set_models($this_model_name, $other_model_name)
74
+	{
75
+		$this->_this_model_name  = $this_model_name;
76
+		$this->_other_model_name = $other_model_name;
77
+		if (is_string($this->_blocking_delete)) {
78
+			throw new EE_Error(sprintf(
79
+				esc_html__(
80
+					"When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
81
+					"event_espresso"
82
+				),
83
+				get_class($this),
84
+				$this_model_name,
85
+				$other_model_name,
86
+				$this->_blocking_delete
87
+			));
88
+		}
89
+	}
90
+
91
+
92
+	/**
93
+	 * Gets the model where this relation is defined.
94
+	 *
95
+	 * @return EEM_Base
96
+	 */
97
+	public function get_this_model()
98
+	{
99
+		return $this->_get_model($this->_this_model_name);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Gets the model which this relation establishes the relation TO (ie,
105
+	 * this relation object was defined on get_this_model(), get_other_model() is the other one)
106
+	 *
107
+	 * @return EEM_Base
108
+	 */
109
+	public function get_other_model()
110
+	{
111
+		return $this->_get_model($this->_other_model_name);
112
+	}
113
+
114
+
115
+	/**
116
+	 * Internally used by get_this_model() and get_other_model()
117
+	 *
118
+	 * @param string $model_name like Event, Question_Group, etc. omit the EEM_
119
+	 * @return EEM_Base
120
+	 * @throws EE_Error
121
+	 * @throws ReflectionException
122
+	 */
123
+	protected function _get_model($model_name)
124
+	{
125
+		$modelInstance = EE_Registry::instance()->load_model($model_name);
126
+		// if the timezone is NOT set on the model but IS set for this relation
127
+		// (which seems really unlikely to ever happen, but whatever)
128
+		// make sure the model timezone is set
129
+		if ($this->_timezone && ! $modelInstance->get_timezone()) {
130
+			$modelInstance->set_timezone($this->_timezone);
131
+		}
132
+		return $modelInstance;
133
+	}
134
+
135
+
136
+	/**
137
+	 * entirely possible that relations may be called from a model and we need to make sure those relations have their
138
+	 * timezone set correctly.
139
+	 *
140
+	 * @param string $timezone timezone to set.
141
+	 */
142
+	public function set_timezone($timezone)
143
+	{
144
+		if (! empty($timezone)) {
145
+			$this->_timezone = $timezone;
146
+		}
147
+	}
148
+
149
+
150
+	/**
151
+	 * @param        $other_table
152
+	 * @param        $other_table_alias
153
+	 * @param        $other_table_column
154
+	 * @param        $this_table_alias
155
+	 * @param        $this_table_join_column
156
+	 * @param string $extra_join_sql
157
+	 * @return string
158
+	 */
159
+	protected function _left_join(
160
+		$other_table,
161
+		$other_table_alias,
162
+		$other_table_column,
163
+		$this_table_alias,
164
+		$this_table_join_column,
165
+		$extra_join_sql = ''
166
+	) {
167
+		return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
168
+	}
169
+
170
+
171
+	/**
172
+	 * Gets all the model objects of type of other model related to $model_object,
173
+	 * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
174
+	 * For both of those child classes, $model_object must be saved so that it has an ID before querying,
175
+	 * otherwise an error will be thrown. Note: by default we disable default_where_conditions
176
+	 * EE_Belongs_To_Relation doesn't need to be saved before querying.
177
+	 *
178
+	 * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
179
+	 * @param array             $query_params                            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
180
+	 * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
181
+	 * @return EE_Base_Class[]
182
+	 * @throws EE_Error
183
+	 * @throws ReflectionException
184
+	 */
185
+	public function get_all_related(
186
+		$model_object_or_id,
187
+		$query_params = array(),
188
+		$values_already_prepared_by_model_object = false
189
+	) {
190
+		if ($values_already_prepared_by_model_object !== false) {
191
+			EE_Error::doing_it_wrong(
192
+				'EE_Model_Relation_Base::get_all_related',
193
+				esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
194
+				'4.8.1'
195
+			);
196
+		}
197
+		$query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
198
+		$query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
199
+															 . "."
200
+															 . $this->get_this_model()->get_primary_key_field()->get_name();
201
+		$model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
202
+		$query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
203
+		return $this->get_other_model()->get_all($query_params);
204
+	}
205
+
206
+
207
+	/**
208
+	 * Alters the $query_params to disable default where conditions, unless otherwise specified
209
+	 *
210
+	 * @param array $query_params
211
+	 * @return array
212
+	 */
213
+	protected function _disable_default_where_conditions_on_query_param($query_params)
214
+	{
215
+		if (! isset($query_params['default_where_conditions'])) {
216
+			$query_params['default_where_conditions'] = 'none';
217
+		}
218
+		return $query_params;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Deletes the related model objects which meet the query parameters. If no
224
+	 * parameters are specified, then all related model objects will be deleted.
225
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
226
+	 * model objects will only be soft-deleted.
227
+	 *
228
+	 * @param EE_Base_Class|int|string $model_object_or_id
229
+	 * @param array                    $query_params
230
+	 * @return int of how many related models got deleted
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function delete_all_related($model_object_or_id, $query_params = array())
235
+	{
236
+		// for each thing we would delete,
237
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
238
+		// determine if it's blocked by anything else before it can be deleted
239
+		$deleted_count = 0;
240
+		foreach ($related_model_objects as $related_model_object) {
241
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
242
+				$related_model_object,
243
+				$model_object_or_id
244
+			);
245
+			/* @var $model_object_or_id EE_Base_Class */
246
+			if (! $delete_is_blocked) {
247
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
248
+				$related_model_object->delete();
249
+				$deleted_count++;
250
+			}
251
+		}
252
+		return $deleted_count;
253
+	}
254
+
255
+
256
+	/**
257
+	 * Deletes the related model objects which meet the query parameters. If no
258
+	 * parameters are specified, then all related model objects will be deleted.
259
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
260
+	 * model objects will only be soft-deleted.
261
+	 *
262
+	 * @param EE_Base_Class|int|string $model_object_or_id
263
+	 * @param array                    $query_params
264
+	 * @return int of how many related models got deleted
265
+	 * @throws EE_Error
266
+	 * @throws ReflectionException
267
+	 */
268
+	public function delete_related_permanently($model_object_or_id, $query_params = array())
269
+	{
270
+		// for each thing we would delete,
271
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
272
+		// determine if it's blocked by anything else before it can be deleted
273
+		$deleted_count = 0;
274
+		foreach ($related_model_objects as $related_model_object) {
275
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
276
+				$related_model_object,
277
+				$model_object_or_id
278
+			);
279
+			/* @var $model_object_or_id EE_Base_Class */
280
+			if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
281
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
282
+				$deleted_count++;
283
+				if (! $delete_is_blocked) {
284
+					$related_model_object->delete_permanently();
285
+				} else {
286
+					// delete is blocked
287
+					// brent and darren, in this case, wanted to just soft delete it then
288
+					$related_model_object->delete();
289
+				}
290
+			} else {
291
+				// its not a soft-deletable thing anyways. do the normal logic.
292
+				if (! $delete_is_blocked) {
293
+					$this->remove_relation_to($model_object_or_id, $related_model_object);
294
+					$related_model_object->delete();
295
+					$deleted_count++;
296
+				}
297
+			}
298
+		}
299
+		return $deleted_count;
300
+	}
301
+
302
+
303
+	/**
304
+	 * this just returns a model_object_id for incoming item that could be an object or id.
305
+	 *
306
+	 * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
307
+	 * @throws EE_Error
308
+	 * @return int
309
+	 */
310
+	protected function _get_model_object_id($model_object_or_id)
311
+	{
312
+		$model_object_id = $model_object_or_id;
313
+		if ($model_object_or_id instanceof EE_Base_Class) {
314
+			$model_object_id = $model_object_or_id->ID();
315
+		}
316
+		if (! $model_object_id) {
317
+			throw new EE_Error(sprintf(
318
+				esc_html__(
319
+					"Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
320
+					"event_espresso"
321
+				),
322
+				$this->get_other_model()->get_this_model_name(),
323
+				$this->get_this_model()->get_this_model_name()
324
+			));
325
+		}
326
+		return $model_object_id;
327
+	}
328
+
329
+
330
+	/**
331
+	 * Gets the SQL string for performing the join between this model and the other model.
332
+	 *
333
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
334
+	 * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
335
+	 *                other_model_primary_table.fk" etc
336
+	 */
337
+	abstract public function get_join_statement($model_relation_chain);
338
+
339
+
340
+	/**
341
+	 * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
342
+	 * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
343
+	 * relationship only allows this model to be related to a single other model of this type)
344
+	 *
345
+	 * @param       $this_obj_or_id
346
+	 * @param       $other_obj_or_id
347
+	 * @param array $extra_join_model_fields_n_values
348
+	 * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
349
+	 *                        $other_obj_or_id)
350
+	 */
351
+	abstract public function add_relation_to(
352
+		$this_obj_or_id,
353
+		$other_obj_or_id,
354
+		$extra_join_model_fields_n_values = array()
355
+	);
356
+
357
+
358
+	/**
359
+	 * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
360
+	 * model objects
361
+	 *
362
+	 * @param       $this_obj_or_id
363
+	 * @param       $other_obj_or_id
364
+	 * @param array $where_query
365
+	 * @return bool
366
+	 */
367
+	abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
368
+
369
+
370
+	/**
371
+	 * Removes ALL relation instances for this relation obj
372
+	 *
373
+	 * @param EE_Base_Class|int $this_obj_or_id
374
+	 * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
375
+	 * @return EE_Base_Class[]
376
+	 * @throws \EE_Error
377
+	 */
378
+	public function remove_relations($this_obj_or_id, $where_query_param = array())
379
+	{
380
+		$related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
381
+		$objs_removed   = array();
382
+		foreach ($related_things as $related_thing) {
383
+			$objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
384
+		}
385
+		return $objs_removed;
386
+	}
387
+
388
+
389
+	/**
390
+	 * If you aren't allowed to delete this model when there are related models across this
391
+	 * relation object, return true. Otherwise, if you can delete this model even though
392
+	 * related objects exist, returns false.
393
+	 *
394
+	 * @return boolean
395
+	 */
396
+	public function block_delete_if_related_models_exist()
397
+	{
398
+		return $this->_blocking_delete;
399
+	}
400
+
401
+
402
+	/**
403
+	 * Gets the error message to show
404
+	 *
405
+	 * @return string
406
+	 */
407
+	public function get_deletion_error_message()
408
+	{
409
+		if ($this->_blocking_delete_error_message) {
410
+			return $this->_blocking_delete_error_message;
411
+		} else {
412 412
 //          return sprintf(__('Cannot delete %1$s when there are related %2$s', "event_espresso"),$this->get_this_model()->item_name(2),$this->get_other_model()->item_name(2));
413
-            return sprintf(
414
-                esc_html__(
415
-                    'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
416
-                    "event_espresso"
417
-                ),
418
-                $this->get_this_model()->item_name(1),
419
-                $this->get_other_model()->item_name(1),
420
-                $this->get_other_model()->item_name(2)
421
-            );
422
-        }
423
-    }
424
-
425
-    /**
426
-     * Returns whatever is set as the nicename for the object.
427
-     *
428
-     * @return string
429
-     */
430
-    public function getSchemaDescription()
431
-    {
432
-        $description = $this instanceof EE_Belongs_To_Relation
433
-            ? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
434
-            : esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
435
-        return sprintf(
436
-            $description,
437
-            $this->get_other_model()->get_this_model_name(),
438
-            $this->get_this_model()->get_this_model_name()
439
-        );
440
-    }
441
-
442
-    /**
443
-     * Returns whatever is set as the $_schema_type property for the object.
444
-     * Note: this will automatically add 'null' to the schema if the object is_nullable()
445
-     *
446
-     * @return string|array
447
-     */
448
-    public function getSchemaType()
449
-    {
450
-        return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
451
-    }
452
-
453
-    /**
454
-     * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
455
-     * this method and return the properties for the schema.
456
-     * The reason this is not a property on the class is because there may be filters set on the values for the property
457
-     * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
458
-     *
459
-     * @return array
460
-     */
461
-    public function getSchemaProperties()
462
-    {
463
-        return array();
464
-    }
465
-
466
-    /**
467
-     * If a child class has enum values, they should override this method and provide a simple array
468
-     * of the enum values.
469
-     * The reason this is not a property on the class is because there may be filterable enum values that
470
-     * are set on the instantiated object that could be filtered after construct.
471
-     *
472
-     * @return array
473
-     */
474
-    public function getSchemaEnum()
475
-    {
476
-        return array();
477
-    }
478
-
479
-    /**
480
-     * This returns the value of the $_schema_format property on the object.
481
-     *
482
-     * @return string
483
-     */
484
-    public function getSchemaFormat()
485
-    {
486
-        return array();
487
-    }
488
-
489
-    /**
490
-     * This returns the value of the $_schema_readonly property on the object.
491
-     *
492
-     * @return bool
493
-     */
494
-    public function getSchemaReadonly()
495
-    {
496
-        return true;
497
-    }
498
-
499
-    /**
500
-     * This returns elements used to represent this field in the json schema.
501
-     *
502
-     * @link http://json-schema.org/
503
-     * @return array
504
-     */
505
-    public function getSchema()
506
-    {
507
-        $schema = array(
508
-            'description' => $this->getSchemaDescription(),
509
-            'type' => $this->getSchemaType(),
510
-            'relation' => true,
511
-            'relation_type' => get_class($this),
512
-            'readonly' => $this->getSchemaReadonly()
513
-        );
514
-
515
-        if ($this instanceof EE_HABTM_Relation) {
516
-            $schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
517
-        }
518
-
519
-        if ($this->getSchemaType() === 'array') {
520
-            $schema['items'] = array(
521
-                'type' => 'object'
522
-            );
523
-        }
524
-
525
-        return $schema;
526
-    }
413
+			return sprintf(
414
+				esc_html__(
415
+					'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
416
+					"event_espresso"
417
+				),
418
+				$this->get_this_model()->item_name(1),
419
+				$this->get_other_model()->item_name(1),
420
+				$this->get_other_model()->item_name(2)
421
+			);
422
+		}
423
+	}
424
+
425
+	/**
426
+	 * Returns whatever is set as the nicename for the object.
427
+	 *
428
+	 * @return string
429
+	 */
430
+	public function getSchemaDescription()
431
+	{
432
+		$description = $this instanceof EE_Belongs_To_Relation
433
+			? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
434
+			: esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
435
+		return sprintf(
436
+			$description,
437
+			$this->get_other_model()->get_this_model_name(),
438
+			$this->get_this_model()->get_this_model_name()
439
+		);
440
+	}
441
+
442
+	/**
443
+	 * Returns whatever is set as the $_schema_type property for the object.
444
+	 * Note: this will automatically add 'null' to the schema if the object is_nullable()
445
+	 *
446
+	 * @return string|array
447
+	 */
448
+	public function getSchemaType()
449
+	{
450
+		return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
451
+	}
452
+
453
+	/**
454
+	 * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
455
+	 * this method and return the properties for the schema.
456
+	 * The reason this is not a property on the class is because there may be filters set on the values for the property
457
+	 * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
458
+	 *
459
+	 * @return array
460
+	 */
461
+	public function getSchemaProperties()
462
+	{
463
+		return array();
464
+	}
465
+
466
+	/**
467
+	 * If a child class has enum values, they should override this method and provide a simple array
468
+	 * of the enum values.
469
+	 * The reason this is not a property on the class is because there may be filterable enum values that
470
+	 * are set on the instantiated object that could be filtered after construct.
471
+	 *
472
+	 * @return array
473
+	 */
474
+	public function getSchemaEnum()
475
+	{
476
+		return array();
477
+	}
478
+
479
+	/**
480
+	 * This returns the value of the $_schema_format property on the object.
481
+	 *
482
+	 * @return string
483
+	 */
484
+	public function getSchemaFormat()
485
+	{
486
+		return array();
487
+	}
488
+
489
+	/**
490
+	 * This returns the value of the $_schema_readonly property on the object.
491
+	 *
492
+	 * @return bool
493
+	 */
494
+	public function getSchemaReadonly()
495
+	{
496
+		return true;
497
+	}
498
+
499
+	/**
500
+	 * This returns elements used to represent this field in the json schema.
501
+	 *
502
+	 * @link http://json-schema.org/
503
+	 * @return array
504
+	 */
505
+	public function getSchema()
506
+	{
507
+		$schema = array(
508
+			'description' => $this->getSchemaDescription(),
509
+			'type' => $this->getSchemaType(),
510
+			'relation' => true,
511
+			'relation_type' => get_class($this),
512
+			'readonly' => $this->getSchemaReadonly()
513
+		);
514
+
515
+		if ($this instanceof EE_HABTM_Relation) {
516
+			$schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
517
+		}
518
+
519
+		if ($this->getSchemaType() === 'array') {
520
+			$schema['items'] = array(
521
+				'type' => 'object'
522
+			);
523
+		}
524
+
525
+		return $schema;
526
+	}
527 527
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
      */
142 142
     public function set_timezone($timezone)
143 143
     {
144
-        if (! empty($timezone)) {
144
+        if ( ! empty($timezone)) {
145 145
             $this->_timezone = $timezone;
146 146
         }
147 147
     }
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
         $this_table_join_column,
165 165
         $extra_join_sql = ''
166 166
     ) {
167
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
167
+        return " LEFT JOIN ".$other_table." AS ".$other_table_alias." ON ".$other_table_alias.".".$other_table_column."=".$this_table_alias.".".$this_table_join_column.($extra_join_sql ? " AND $extra_join_sql" : '');
168 168
     }
169 169
 
170 170
 
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
                                                              . "."
200 200
                                                              . $this->get_this_model()->get_primary_key_field()->get_name();
201 201
         $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
202
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
202
+        $query_params[0][$query_param_where_this_model_pk] = $model_object_id;
203 203
         return $this->get_other_model()->get_all($query_params);
204 204
     }
205 205
 
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
      */
213 213
     protected function _disable_default_where_conditions_on_query_param($query_params)
214 214
     {
215
-        if (! isset($query_params['default_where_conditions'])) {
215
+        if ( ! isset($query_params['default_where_conditions'])) {
216 216
             $query_params['default_where_conditions'] = 'none';
217 217
         }
218 218
         return $query_params;
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
                 $model_object_or_id
244 244
             );
245 245
             /* @var $model_object_or_id EE_Base_Class */
246
-            if (! $delete_is_blocked) {
246
+            if ( ! $delete_is_blocked) {
247 247
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
248 248
                 $related_model_object->delete();
249 249
                 $deleted_count++;
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
             if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
281 281
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
282 282
                 $deleted_count++;
283
-                if (! $delete_is_blocked) {
283
+                if ( ! $delete_is_blocked) {
284 284
                     $related_model_object->delete_permanently();
285 285
                 } else {
286 286
                     // delete is blocked
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
                 }
290 290
             } else {
291 291
                 // its not a soft-deletable thing anyways. do the normal logic.
292
-                if (! $delete_is_blocked) {
292
+                if ( ! $delete_is_blocked) {
293 293
                     $this->remove_relation_to($model_object_or_id, $related_model_object);
294 294
                     $related_model_object->delete();
295 295
                     $deleted_count++;
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
         if ($model_object_or_id instanceof EE_Base_Class) {
314 314
             $model_object_id = $model_object_or_id->ID();
315 315
         }
316
-        if (! $model_object_id) {
316
+        if ( ! $model_object_id) {
317 317
             throw new EE_Error(sprintf(
318 318
                 esc_html__(
319 319
                     "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
Please login to merge, or discard this patch.
core/db_models/relations/EE_Belongs_To_Relation.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -12,137 +12,137 @@
 block discarded – undo
12 12
 class EE_Belongs_To_Relation extends EE_Model_Relation_Base
13 13
 {
14 14
 
15
-    /**
16
-     * Object representing the relationship between two models. Belongs_To means that THIS model has the foreign key
17
-     * to the other model. This knows how to join the models,
18
-     * get related models across the relation, and add-and-remove the relationships.
19
-     *
20
-     * @param boolean $block_deletes                                For Belongs_To relations, this is set to FALSE by
21
-     *                                                              default. if there are related models across this
22
-     *                                                              relation, block (prevent and add an error) the
23
-     *                                                              deletion of this model
24
-     * @param string  $related_model_objects_deletion_error_message a customized error message on blocking deletes
25
-     *                                                              instead of the default
26
-     */
27
-    public function __construct($block_deletes = false, $related_model_objects_deletion_error_message = null)
28
-    {
29
-        parent::__construct($block_deletes, $related_model_objects_deletion_error_message);
30
-    }
15
+	/**
16
+	 * Object representing the relationship between two models. Belongs_To means that THIS model has the foreign key
17
+	 * to the other model. This knows how to join the models,
18
+	 * get related models across the relation, and add-and-remove the relationships.
19
+	 *
20
+	 * @param boolean $block_deletes                                For Belongs_To relations, this is set to FALSE by
21
+	 *                                                              default. if there are related models across this
22
+	 *                                                              relation, block (prevent and add an error) the
23
+	 *                                                              deletion of this model
24
+	 * @param string  $related_model_objects_deletion_error_message a customized error message on blocking deletes
25
+	 *                                                              instead of the default
26
+	 */
27
+	public function __construct($block_deletes = false, $related_model_objects_deletion_error_message = null)
28
+	{
29
+		parent::__construct($block_deletes, $related_model_objects_deletion_error_message);
30
+	}
31 31
 
32 32
 
33
-    /**
34
-     * get_join_statement
35
-     *
36
-     * @param string $model_relation_chain
37
-     * @return string
38
-     * @throws \EE_Error
39
-     */
40
-    public function get_join_statement($model_relation_chain)
41
-    {
42
-        // create the sql string like
43
-        $this_table_fk_field  = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
44
-        $other_table_pk_field = $this->get_other_model()->get_primary_key_field();
45
-        $this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
46
-            $model_relation_chain,
47
-            $this->get_this_model()->get_this_model_name()
48
-        ) . $this_table_fk_field->get_table_alias();
49
-        $other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
50
-            $model_relation_chain,
51
-            $this->get_other_model()->get_this_model_name()
52
-        ) . $other_table_pk_field->get_table_alias();
53
-        $other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
54
-        return $this->_left_join(
55
-            $other_table,
56
-            $other_table_alias,
57
-            $other_table_pk_field->get_table_column(),
58
-            $this_table_alias,
59
-            $this_table_fk_field->get_table_column()
60
-        ) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
61
-    }
33
+	/**
34
+	 * get_join_statement
35
+	 *
36
+	 * @param string $model_relation_chain
37
+	 * @return string
38
+	 * @throws \EE_Error
39
+	 */
40
+	public function get_join_statement($model_relation_chain)
41
+	{
42
+		// create the sql string like
43
+		$this_table_fk_field  = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
44
+		$other_table_pk_field = $this->get_other_model()->get_primary_key_field();
45
+		$this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
46
+			$model_relation_chain,
47
+			$this->get_this_model()->get_this_model_name()
48
+		) . $this_table_fk_field->get_table_alias();
49
+		$other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
50
+			$model_relation_chain,
51
+			$this->get_other_model()->get_this_model_name()
52
+		) . $other_table_pk_field->get_table_alias();
53
+		$other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
54
+		return $this->_left_join(
55
+			$other_table,
56
+			$other_table_alias,
57
+			$other_table_pk_field->get_table_column(),
58
+			$this_table_alias,
59
+			$this_table_fk_field->get_table_column()
60
+		) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
61
+	}
62 62
 
63 63
 
64
-    /**
65
-     * Sets this model object's foreign key to the other model object's primary key. Feel free to do this manually if
66
-     * you like.
67
-     *
68
-     * @param EE_Base_Class|int $this_obj_or_id
69
-     * @param EE_Base_Class|int $other_obj_or_id
70
-     * @param array             $extra_join_model_fields_n_values
71
-     * @return \EE_Base_Class
72
-     * @throws \EE_Error
73
-     */
74
-    public function add_relation_to($this_obj_or_id, $other_obj_or_id, $extra_join_model_fields_n_values = array())
75
-    {
76
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
77
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
78
-        // find the field on the other model which is a foreign key to this model
79
-        $fk_on_this_model = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
80
-        if ($this_model_obj->get($fk_on_this_model->get_name()) != $other_model_obj->ID()) {
81
-            // set that field on the other model to this model's ID
82
-            $this_model_obj->set($fk_on_this_model->get_name(), $other_model_obj->ID());
83
-            $this_model_obj->save();
84
-        }
85
-        return $other_model_obj;
86
-    }
64
+	/**
65
+	 * Sets this model object's foreign key to the other model object's primary key. Feel free to do this manually if
66
+	 * you like.
67
+	 *
68
+	 * @param EE_Base_Class|int $this_obj_or_id
69
+	 * @param EE_Base_Class|int $other_obj_or_id
70
+	 * @param array             $extra_join_model_fields_n_values
71
+	 * @return \EE_Base_Class
72
+	 * @throws \EE_Error
73
+	 */
74
+	public function add_relation_to($this_obj_or_id, $other_obj_or_id, $extra_join_model_fields_n_values = array())
75
+	{
76
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
77
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
78
+		// find the field on the other model which is a foreign key to this model
79
+		$fk_on_this_model = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
80
+		if ($this_model_obj->get($fk_on_this_model->get_name()) != $other_model_obj->ID()) {
81
+			// set that field on the other model to this model's ID
82
+			$this_model_obj->set($fk_on_this_model->get_name(), $other_model_obj->ID());
83
+			$this_model_obj->save();
84
+		}
85
+		return $other_model_obj;
86
+	}
87 87
 
88 88
 
89
-    /**
90
-     * Sets the this model object's foreign key to its default, instead of pointing to the other model object
91
-     *
92
-     * @param EE_Base_Class|int $this_obj_or_id
93
-     * @param EE_Base_Class|int $other_obj_or_id
94
-     * @param array             $where_query
95
-     * @return \EE_Base_Class
96
-     * @throws \EE_Error
97
-     */
98
-    public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array())
99
-    {
100
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
101
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
102
-        // find the field on the other model which is a foreign key to this model
103
-        $fk_on_this_model = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
104
-        // set that field on the other model to this model's ID
105
-        $this_model_obj->set($fk_on_this_model->get_name(), null, true);
106
-        $this_model_obj->save();
107
-        return $other_model_obj;
108
-    }
89
+	/**
90
+	 * Sets the this model object's foreign key to its default, instead of pointing to the other model object
91
+	 *
92
+	 * @param EE_Base_Class|int $this_obj_or_id
93
+	 * @param EE_Base_Class|int $other_obj_or_id
94
+	 * @param array             $where_query
95
+	 * @return \EE_Base_Class
96
+	 * @throws \EE_Error
97
+	 */
98
+	public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array())
99
+	{
100
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
101
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
102
+		// find the field on the other model which is a foreign key to this model
103
+		$fk_on_this_model = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
104
+		// set that field on the other model to this model's ID
105
+		$this_model_obj->set($fk_on_this_model->get_name(), null, true);
106
+		$this_model_obj->save();
107
+		return $other_model_obj;
108
+	}
109 109
 
110 110
 
111
-    /**
112
-     * Overrides parent so that we don't NEED to save the $model_object before getting the related objects.
113
-     *
114
-     * @param EE_Base_Class $model_obj_or_id
115
-     * @param array         $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
116
-     * @param boolean       $values_already_prepared_by_model_object @deprecated since 4.8.1
117
-     * @return EE_Base_Class[]
118
-     * @throws \EE_Error
119
-     */
120
-    public function get_all_related(
121
-        $model_obj_or_id,
122
-        $query_params = array(),
123
-        $values_already_prepared_by_model_object = false
124
-    ) {
125
-        if ($values_already_prepared_by_model_object !== false) {
126
-            EE_Error::doing_it_wrong(
127
-                'EE_Model_Relation_Base::get_all_related',
128
-                esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
129
-                '4.8.1'
130
-            );
131
-        }
132
-        // get column on this model object which is a foreign key to the other model
133
-        $fk_field_obj = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
134
-        // get its value
135
-        if ($model_obj_or_id instanceof EE_Base_Class) {
136
-            $model_obj = $model_obj_or_id;
137
-        } else {
138
-            $model_obj = $this->get_this_model()->ensure_is_obj($model_obj_or_id);
139
-        }
140
-        $ID_value_on_other_model = $model_obj->get($fk_field_obj->get_name());
141
-        // get all where their PK matches that value
142
-        $query_params[0][ $this->get_other_model()->get_primary_key_field()->get_name() ] = $ID_value_on_other_model;
143
-        $query_params                                                                   = $this->_disable_default_where_conditions_on_query_param($query_params);
111
+	/**
112
+	 * Overrides parent so that we don't NEED to save the $model_object before getting the related objects.
113
+	 *
114
+	 * @param EE_Base_Class $model_obj_or_id
115
+	 * @param array         $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
116
+	 * @param boolean       $values_already_prepared_by_model_object @deprecated since 4.8.1
117
+	 * @return EE_Base_Class[]
118
+	 * @throws \EE_Error
119
+	 */
120
+	public function get_all_related(
121
+		$model_obj_or_id,
122
+		$query_params = array(),
123
+		$values_already_prepared_by_model_object = false
124
+	) {
125
+		if ($values_already_prepared_by_model_object !== false) {
126
+			EE_Error::doing_it_wrong(
127
+				'EE_Model_Relation_Base::get_all_related',
128
+				esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
129
+				'4.8.1'
130
+			);
131
+		}
132
+		// get column on this model object which is a foreign key to the other model
133
+		$fk_field_obj = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
134
+		// get its value
135
+		if ($model_obj_or_id instanceof EE_Base_Class) {
136
+			$model_obj = $model_obj_or_id;
137
+		} else {
138
+			$model_obj = $this->get_this_model()->ensure_is_obj($model_obj_or_id);
139
+		}
140
+		$ID_value_on_other_model = $model_obj->get($fk_field_obj->get_name());
141
+		// get all where their PK matches that value
142
+		$query_params[0][ $this->get_other_model()->get_primary_key_field()->get_name() ] = $ID_value_on_other_model;
143
+		$query_params                                                                   = $this->_disable_default_where_conditions_on_query_param($query_params);
144 144
 //      echo '$query_params';
145 145
 //      var_dump($query_params);
146
-        return $this->get_other_model()->get_all($query_params);
147
-    }
146
+		return $this->get_other_model()->get_all($query_params);
147
+	}
148 148
 }
Please login to merge, or discard this patch.