Completed
Branch FET/reg-form-builder/form-sect... (b379b8)
by
unknown
30:51 queued 20:11
created
core/db_models/EEM_Base.model.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -8,7 +8,6 @@
 block discarded – undo
8 8
 use EventEspresso\core\interfaces\ResettableInterface;
9 9
 use EventEspresso\core\services\loaders\LoaderFactory;
10 10
 use EventEspresso\core\services\loaders\LoaderInterface;
11
-use EventEspresso\core\services\request\RequestInterface;
12 11
 
13 12
 /**
14 13
  * Class EEM_Base
Please login to merge, or discard this patch.
Indentation   +6481 added lines, -6481 removed lines patch added patch discarded remove patch
@@ -37,6487 +37,6487 @@
 block discarded – undo
37 37
 abstract class EEM_Base extends EE_Base implements ResettableInterface
38 38
 {
39 39
 
40
-    /**
41
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
-     * They almost always WILL NOT, but it's not necessarily a requirement.
44
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
-     *
46
-     * @var boolean
47
-     */
48
-    private $_values_already_prepared_by_model_object = 0;
49
-
50
-    /**
51
-     * when $_values_already_prepared_by_model_object equals this, we assume
52
-     * the data is just like form input that needs to have the model fields'
53
-     * prepare_for_set and prepare_for_use_in_db called on it
54
-     */
55
-    const not_prepared_by_model_object = 0;
56
-
57
-    /**
58
-     * when $_values_already_prepared_by_model_object equals this, we
59
-     * assume this value is coming from a model object and doesn't need to have
60
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
61
-     */
62
-    const prepared_by_model_object = 1;
63
-
64
-    /**
65
-     * when $_values_already_prepared_by_model_object equals this, we assume
66
-     * the values are already to be used in the database (ie no processing is done
67
-     * on them by the model's fields)
68
-     */
69
-    const prepared_for_use_in_db = 2;
70
-
71
-
72
-    protected $singular_item = 'Item';
73
-
74
-    protected $plural_item   = 'Items';
75
-
76
-    /**
77
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
-     */
79
-    protected $_tables;
80
-
81
-    /**
82
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
-     *
86
-     * @var \EE_Model_Field_Base[][] $_fields
87
-     */
88
-    protected $_fields;
89
-
90
-    /**
91
-     * array of different kinds of relations
92
-     *
93
-     * @var \EE_Model_Relation_Base[] $_model_relations
94
-     */
95
-    protected $_model_relations;
96
-
97
-    /**
98
-     * @var \EE_Index[] $_indexes
99
-     */
100
-    protected $_indexes = array();
101
-
102
-    /**
103
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
104
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
-     * by setting the same columns as used in these queries in the query yourself.
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_default_where_conditions_strategy;
110
-
111
-    /**
112
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
-     * This is particularly useful when you want something between 'none' and 'default'
114
-     *
115
-     * @var EE_Default_Where_Conditions
116
-     */
117
-    protected $_minimum_where_conditions_strategy;
118
-
119
-    /**
120
-     * String describing how to find the "owner" of this model's objects.
121
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
-     * But when there isn't, this indicates which related model, or transiently-related model,
123
-     * has the foreign key to the wp_users table.
124
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
-     * related to events, and events have a foreign key to wp_users.
126
-     * On EEM_Transaction, this would be 'Transaction.Event'
127
-     *
128
-     * @var string
129
-     */
130
-    protected $_model_chain_to_wp_user = '';
131
-
132
-    /**
133
-     * String describing how to find the model with a password controlling access to this model. This property has the
134
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
-     * This value is the path of models to follow to arrive at the model with the password field.
136
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
-     * model with a password that should affect reading this on the front-end.
138
-     * Eg this is an empty string for the Event model because it has a password.
139
-     * This is null for the Registration model, because its event's password has no bearing on whether
140
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
-     * should hide tickets for datetimes for events that have a password set.
143
-     * @var string |null
144
-     */
145
-    protected $model_chain_to_password = null;
146
-
147
-    /**
148
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
-     * don't need it (particularly CPT models)
150
-     *
151
-     * @var bool
152
-     */
153
-    protected $_ignore_where_strategy = false;
154
-
155
-    /**
156
-     * String used in caps relating to this model. Eg, if the caps relating to this
157
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
-     *
159
-     * @var string. If null it hasn't been initialized yet. If false then we
160
-     * have indicated capabilities don't apply to this
161
-     */
162
-    protected $_caps_slug = null;
163
-
164
-    /**
165
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
-     * and next-level keys are capability names, and each's value is a
167
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
-     * they specify which context to use (ie, frontend, backend, edit or delete)
169
-     * and then each capability in the corresponding sub-array that they're missing
170
-     * adds the where conditions onto the query.
171
-     *
172
-     * @var array
173
-     */
174
-    protected $_cap_restrictions = array(
175
-        self::caps_read       => array(),
176
-        self::caps_read_admin => array(),
177
-        self::caps_edit       => array(),
178
-        self::caps_delete     => array(),
179
-    );
180
-
181
-    /**
182
-     * Array defining which cap restriction generators to use to create default
183
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
184
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
-     * automatically set this to false (not just null).
187
-     *
188
-     * @var EE_Restriction_Generator_Base[]
189
-     */
190
-    protected $_cap_restriction_generators = array();
191
-
192
-    /**
193
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
-     */
195
-    const caps_read       = 'read';
196
-
197
-    const caps_read_admin = 'read_admin';
198
-
199
-    const caps_edit       = 'edit';
200
-
201
-    const caps_delete     = 'delete';
202
-
203
-    /**
204
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
-     * maps to 'read' because when looking for relevant permissions we're going to use
207
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
208
-     *
209
-     * @var array
210
-     */
211
-    protected $_cap_contexts_to_cap_action_map = array(
212
-        self::caps_read       => 'read',
213
-        self::caps_read_admin => 'read',
214
-        self::caps_edit       => 'edit',
215
-        self::caps_delete     => 'delete',
216
-    );
217
-
218
-    /**
219
-     * Timezone
220
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
-     * EE_Datetime_Field data type will have access to it.
224
-     *
225
-     * @var string
226
-     */
227
-    protected $_timezone;
228
-
229
-
230
-    /**
231
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
-     * multisite.
233
-     *
234
-     * @var int
235
-     */
236
-    protected static $_model_query_blog_id;
237
-
238
-    /**
239
-     * A copy of _fields, except the array keys are the model names pointed to by
240
-     * the field
241
-     *
242
-     * @var EE_Model_Field_Base[]
243
-     */
244
-    private $_cache_foreign_key_to_fields = array();
245
-
246
-    /**
247
-     * Cached list of all the fields on the model, indexed by their name
248
-     *
249
-     * @var EE_Model_Field_Base[]
250
-     */
251
-    private $_cached_fields = null;
252
-
253
-    /**
254
-     * Cached list of all the fields on the model, except those that are
255
-     * marked as only pertinent to the database
256
-     *
257
-     * @var EE_Model_Field_Base[]
258
-     */
259
-    private $_cached_fields_non_db_only = null;
260
-
261
-    /**
262
-     * A cached reference to the primary key for quick lookup
263
-     *
264
-     * @var EE_Model_Field_Base
265
-     */
266
-    private $_primary_key_field = null;
267
-
268
-    /**
269
-     * Flag indicating whether this model has a primary key or not
270
-     *
271
-     * @var boolean
272
-     */
273
-    protected $_has_primary_key_field = null;
274
-
275
-    /**
276
-     * array in the format:  [ FK alias => full PK ]
277
-     * where keys are local column name aliases for foreign keys
278
-     * and values are the fully qualified column name for the primary key they represent
279
-     *  ex:
280
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
281
-     *
282
-     * @var array $foreign_key_aliases
283
-     */
284
-    protected $foreign_key_aliases = [];
285
-
286
-    /**
287
-     * Whether or not this model is based off a table in WP core only (CPTs should set
288
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
289
-     * This should be true for models that deal with data that should exist independent of EE.
290
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
291
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
292
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
293
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
294
-     * @var boolean
295
-     */
296
-    protected $_wp_core_model = false;
297
-
298
-    /**
299
-     * @var bool stores whether this model has a password field or not.
300
-     * null until initialized by hasPasswordField()
301
-     */
302
-    protected $has_password_field;
303
-
304
-    /**
305
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
306
-     */
307
-    protected $password_field;
308
-
309
-    /**
310
-     *    List of valid operators that can be used for querying.
311
-     * The keys are all operators we'll accept, the values are the real SQL
312
-     * operators used
313
-     *
314
-     * @var array
315
-     */
316
-    protected $_valid_operators = array(
317
-        '='           => '=',
318
-        '<='          => '<=',
319
-        '<'           => '<',
320
-        '>='          => '>=',
321
-        '>'           => '>',
322
-        '!='          => '!=',
323
-        'LIKE'        => 'LIKE',
324
-        'like'        => 'LIKE',
325
-        'NOT_LIKE'    => 'NOT LIKE',
326
-        'not_like'    => 'NOT LIKE',
327
-        'NOT LIKE'    => 'NOT LIKE',
328
-        'not like'    => 'NOT LIKE',
329
-        'IN'          => 'IN',
330
-        'in'          => 'IN',
331
-        'NOT_IN'      => 'NOT IN',
332
-        'not_in'      => 'NOT IN',
333
-        'NOT IN'      => 'NOT IN',
334
-        'not in'      => 'NOT IN',
335
-        'between'     => 'BETWEEN',
336
-        'BETWEEN'     => 'BETWEEN',
337
-        'IS_NOT_NULL' => 'IS NOT NULL',
338
-        'is_not_null' => 'IS NOT NULL',
339
-        'IS NOT NULL' => 'IS NOT NULL',
340
-        'is not null' => 'IS NOT NULL',
341
-        'IS_NULL'     => 'IS NULL',
342
-        'is_null'     => 'IS NULL',
343
-        'IS NULL'     => 'IS NULL',
344
-        'is null'     => 'IS NULL',
345
-        'REGEXP'      => 'REGEXP',
346
-        'regexp'      => 'REGEXP',
347
-        'NOT_REGEXP'  => 'NOT REGEXP',
348
-        'not_regexp'  => 'NOT REGEXP',
349
-        'NOT REGEXP'  => 'NOT REGEXP',
350
-        'not regexp'  => 'NOT REGEXP',
351
-    );
352
-
353
-    /**
354
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
355
-     *
356
-     * @var array
357
-     */
358
-    protected $_in_style_operators = array('IN', 'NOT IN');
359
-
360
-    /**
361
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
362
-     * '12-31-2012'"
363
-     *
364
-     * @var array
365
-     */
366
-    protected $_between_style_operators = array('BETWEEN');
367
-
368
-    /**
369
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
370
-     * @var array
371
-     */
372
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
373
-    /**
374
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
375
-     * on a join table.
376
-     *
377
-     * @var array
378
-     */
379
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
380
-
381
-    /**
382
-     * Allowed values for $query_params['order'] for ordering in queries
383
-     *
384
-     * @var array
385
-     */
386
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
387
-
388
-    /**
389
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
390
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
391
-     *
392
-     * @var array
393
-     */
394
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
395
-
396
-    /**
397
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
398
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
399
-     *
400
-     * @var array
401
-     */
402
-    private $_allowed_query_params = array(
403
-        0,
404
-        'limit',
405
-        'order_by',
406
-        'group_by',
407
-        'having',
408
-        'force_join',
409
-        'order',
410
-        'on_join_limit',
411
-        'default_where_conditions',
412
-        'caps',
413
-        'extra_selects',
414
-        'exclude_protected',
415
-    );
416
-
417
-    /**
418
-     * All the data types that can be used in $wpdb->prepare statements.
419
-     *
420
-     * @var array
421
-     */
422
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
423
-
424
-    /**
425
-     * @var EE_Registry $EE
426
-     */
427
-    protected $EE = null;
428
-
429
-
430
-    /**
431
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
432
-     *
433
-     * @var int
434
-     */
435
-    protected $_show_next_x_db_queries = 0;
436
-
437
-    /**
438
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
439
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
440
-     * WHERE, GROUP_BY, etc.
441
-     *
442
-     * @var CustomSelects
443
-     */
444
-    protected $_custom_selections = array();
445
-
446
-    /**
447
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
448
-     * caches every model object we've fetched from the DB on this request
449
-     *
450
-     * @var array
451
-     */
452
-    protected $_entity_map;
453
-
454
-    /**
455
-     * @var LoaderInterface
456
-     */
457
-    private static $loader;
458
-
459
-
460
-    /**
461
-     * constant used to show EEM_Base has not yet verified the db on this http request
462
-     */
463
-    const db_verified_none = 0;
464
-
465
-    /**
466
-     * constant used to show EEM_Base has verified the EE core db on this http request,
467
-     * but not the addons' dbs
468
-     */
469
-    const db_verified_core = 1;
470
-
471
-    /**
472
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
473
-     * the EE core db too)
474
-     */
475
-    const db_verified_addons = 2;
476
-
477
-    /**
478
-     * indicates whether an EEM_Base child has already re-verified the DB
479
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
480
-     * looking like EEM_Base::db_verified_*
481
-     *
482
-     * @var int - 0 = none, 1 = core, 2 = addons
483
-     */
484
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
485
-
486
-    /**
487
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
488
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
489
-     *        registrations for non-trashed tickets for non-trashed datetimes)
490
-     */
491
-    const default_where_conditions_all = 'all';
492
-
493
-    /**
494
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
495
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
496
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
497
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
498
-     *        models which share tables with other models, this can return data for the wrong model.
499
-     */
500
-    const default_where_conditions_this_only = 'this_model_only';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
504
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
506
-     */
507
-    const default_where_conditions_others_only = 'other_models_only';
508
-
509
-    /**
510
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
511
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
512
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
513
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
514
-     *        (regardless of whether those events and venues are trashed)
515
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
516
-     *        events.
517
-     */
518
-    const default_where_conditions_minimum_all = 'minimum';
519
-
520
-    /**
521
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
522
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
523
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
524
-     *        not)
525
-     */
526
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
527
-
528
-    /**
529
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
530
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
531
-     *        it's possible it will return table entries for other models. You should use
532
-     *        EEM_Base::default_where_conditions_minimum_all instead.
533
-     */
534
-    const default_where_conditions_none = 'none';
535
-
536
-
537
-
538
-    /**
539
-     * About all child constructors:
540
-     * they should define the _tables, _fields and _model_relations arrays.
541
-     * Should ALWAYS be called after child constructor.
542
-     * In order to make the child constructors to be as simple as possible, this parent constructor
543
-     * finalizes constructing all the object's attributes.
544
-     * Generally, rather than requiring a child to code
545
-     * $this->_tables = array(
546
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
547
-     *        ...);
548
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
549
-     * each EE_Table has a function to set the table's alias after the constructor, using
550
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
551
-     * do something similar.
552
-     *
553
-     * @param null $timezone
554
-     * @throws EE_Error
555
-     */
556
-    protected function __construct($timezone = null)
557
-    {
558
-        // check that the model has not been loaded too soon
559
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
560
-            throw new EE_Error(
561
-                sprintf(
562
-                    __(
563
-                        '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.',
564
-                        'event_espresso'
565
-                    ),
566
-                    get_class($this)
567
-                )
568
-            );
569
-        }
570
-        /**
571
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
572
-         */
573
-        if (empty(EEM_Base::$_model_query_blog_id)) {
574
-            EEM_Base::set_model_query_blog_id();
575
-        }
576
-        /**
577
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
578
-         * just use EE_Register_Model_Extension
579
-         *
580
-         * @var EE_Table_Base[] $_tables
581
-         */
582
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
583
-        foreach ($this->_tables as $table_alias => $table_obj) {
584
-            /** @var $table_obj EE_Table_Base */
585
-            $table_obj->_construct_finalize_with_alias($table_alias);
586
-            if ($table_obj instanceof EE_Secondary_Table) {
587
-                /** @var $table_obj EE_Secondary_Table */
588
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
589
-            }
590
-        }
591
-        /**
592
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
593
-         * EE_Register_Model_Extension
594
-         *
595
-         * @param EE_Model_Field_Base[] $_fields
596
-         */
597
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
598
-        $this->_invalidate_field_caches();
599
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
600
-            if (! array_key_exists($table_alias, $this->_tables)) {
601
-                throw new EE_Error(sprintf(__(
602
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
603
-                    'event_espresso'
604
-                ), $table_alias, implode(",", $this->_fields)));
605
-            }
606
-            foreach ($fields_for_table as $field_name => $field_obj) {
607
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
608
-                // primary key field base has a slightly different _construct_finalize
609
-                /** @var $field_obj EE_Model_Field_Base */
610
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
611
-            }
612
-        }
613
-        // everything is related to Extra_Meta
614
-        if (get_class($this) !== 'EEM_Extra_Meta') {
615
-            // make extra meta related to everything, but don't block deleting things just
616
-            // because they have related extra meta info. For now just orphan those extra meta
617
-            // in the future we should automatically delete them
618
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
619
-        }
620
-        // and change logs
621
-        if (get_class($this) !== 'EEM_Change_Log') {
622
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
623
-        }
624
-        /**
625
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
626
-         * EE_Register_Model_Extension
627
-         *
628
-         * @param EE_Model_Relation_Base[] $_model_relations
629
-         */
630
-        $this->_model_relations = (array) apply_filters(
631
-            'FHEE__' . get_class($this) . '__construct__model_relations',
632
-            $this->_model_relations
633
-        );
634
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
635
-            /** @var $relation_obj EE_Model_Relation_Base */
636
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
637
-        }
638
-        foreach ($this->_indexes as $index_name => $index_obj) {
639
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
-        }
641
-        $this->set_timezone($timezone);
642
-        // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
644
-            // nothing was set during child constructor, so set default
645
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
-        }
647
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
649
-            // nothing was set during child constructor, so set default
650
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
-        }
652
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
654
-        // to indicate to NOT set it, set it to the logical default
655
-        if ($this->_caps_slug === null) {
656
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
-        }
658
-        // initialize the standard cap restriction generators if none were specified by the child constructor
659
-        if (! empty($this->_cap_restriction_generators)) {
660
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
-                        new EE_Restriction_Generator_Protected(),
665
-                        $cap_context,
666
-                        $this
667
-                    );
668
-                }
669
-            }
670
-        }
671
-        // if there are cap restriction generators, use them to make the default cap restrictions
672
-        if (! empty($this->_cap_restriction_generators)) {
673
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
675
-                    continue;
676
-                }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
-                    throw new EE_Error(
679
-                        sprintf(
680
-                            __(
681
-                                '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.',
682
-                                'event_espresso'
683
-                            ),
684
-                            $context,
685
-                            $this->get_this_model_name()
686
-                        )
687
-                    );
688
-                }
689
-                $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
691
-                    $generator_object->_construct_finalize($this, $action);
692
-                }
693
-            }
694
-        }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * Used to set the $_model_query_blog_id static property.
702
-     *
703
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
-     *                      value for get_current_blog_id() will be used.
705
-     */
706
-    public static function set_model_query_blog_id($blog_id = 0)
707
-    {
708
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * Returns whatever is set as the internal $model_query_blog_id.
715
-     *
716
-     * @return int
717
-     */
718
-    public static function get_model_query_blog_id()
719
-    {
720
-        return EEM_Base::$_model_query_blog_id;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * This function is a singleton method used to instantiate the Espresso_model object
727
-     *
728
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
-     *                                (and any incoming timezone data that gets saved).
730
-     *                                Note this just sends the timezone info to the date time model field objects.
731
-     *                                Default is NULL
732
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
-     * @return static (as in the concrete child class)
734
-     * @throws EE_Error
735
-     * @throws InvalidArgumentException
736
-     * @throws InvalidDataTypeException
737
-     * @throws InvalidInterfaceException
738
-     */
739
-    public static function instance($timezone = null)
740
-    {
741
-        // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
743
-            // instantiate Espresso_model
744
-            static::$_instance = new static(
745
-                $timezone,
746
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
-            );
748
-        }
749
-        // we might have a timezone set, let set_timezone decide what to do with it
750
-        static::$_instance->set_timezone($timezone);
751
-        // Espresso_model object
752
-        return static::$_instance;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * resets the model and returns it
759
-     *
760
-     * @param null | string $timezone
761
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
-     * all its properties reset; if it wasn't instantiated, returns null)
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     */
769
-    public static function reset($timezone = null)
770
-    {
771
-        if (static::$_instance instanceof EEM_Base) {
772
-            // let's try to NOT swap out the current instance for a new one
773
-            // because if someone has a reference to it, we can't remove their reference
774
-            // so it's best to keep using the same reference, but change the original object
775
-            // reset all its properties to their original values as defined in the class
776
-            $r = new ReflectionClass(get_class(static::$_instance));
777
-            $static_properties = $r->getStaticProperties();
778
-            foreach ($r->getDefaultProperties() as $property => $value) {
779
-                // don't set instance to null like it was originally,
780
-                // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
782
-                    static::$_instance->{$property} = $value;
783
-                }
784
-            }
785
-            // and then directly call its constructor again, like we would if we were creating a new one
786
-            static::$_instance->__construct(
787
-                $timezone,
788
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
-            );
790
-            return self::instance();
791
-        }
792
-        return null;
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * @return LoaderInterface
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     */
803
-    protected static function getLoader(): LoaderInterface
804
-    {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
806
-            EEM_Base::$loader = LoaderFactory::getLoader();
807
-        }
808
-        return EEM_Base::$loader;
809
-    }
810
-
811
-
812
-
813
-    /**
814
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
-     *
816
-     * @param  boolean $translated return localized strings or JUST the array.
817
-     * @return array
818
-     * @throws EE_Error
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     */
823
-    public function status_array($translated = false)
824
-    {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
826
-            return array();
827
-        }
828
-        $model_name = $this->get_this_model_name();
829
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
-        $status_array = array();
832
-        foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
834
-        }
835
-        return $translated
836
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
-            : $status_array;
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
-     *
845
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
-     *                             or if you have the development copy of EE you can view this at the path:
847
-     *                             /docs/G--Model-System/model-query-params.md
848
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (
873
-            isset($query_params['limit'])
874
-            && ! isset($query_params['group_by'])
875
-        ) {
876
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
-        }
878
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Modifies the query parameters so we only get back model objects
885
-     * that "belong" to the current user
886
-     *
887
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
-     */
890
-    public function alter_query_params_to_only_include_mine($query_params = array())
891
-    {
892
-        $wp_user_field_name = $this->wp_user_field_name();
893
-        if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
-        }
896
-        return $query_params;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * Returns the name of the field's name that points to the WP_User table
903
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
-     * foreign key to the WP_User table)
905
-     *
906
-     * @return string|boolean string on success, boolean false when there is no
907
-     * foreign key to the WP_User table
908
-     */
909
-    public function wp_user_field_name()
910
-    {
911
-        try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
913
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
-                $last_model_name = end($models_to_follow_to_wp_users);
915
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
-            } else {
918
-                $model_with_fk_to_wp_users = $this;
919
-                $model_chain_to_wp_user = '';
920
-            }
921
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
932
-     * (or transiently-related model) has a foreign key to the wp_users table;
933
-     * useful for finding if model objects of this type are 'owned' by the current user.
934
-     * This is an empty string when the foreign key is on this model and when it isn't,
935
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
936
-     * (or transiently-related model)
937
-     *
938
-     * @return string
939
-     */
940
-    public function model_chain_to_wp_user()
941
-    {
942
-        return $this->_model_chain_to_wp_user;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
-     * like how registrations don't have a foreign key to wp_users, but the
950
-     * events they are for are), or is unrelated to wp users.
951
-     * generally available
952
-     *
953
-     * @return boolean
954
-     */
955
-    public function is_owned()
956
-    {
957
-        if ($this->model_chain_to_wp_user()) {
958
-            return true;
959
-        }
960
-        try {
961
-            $this->get_foreign_key_to('WP_User');
962
-            return true;
963
-        } catch (EE_Error $e) {
964
-            return false;
965
-        }
966
-    }
967
-
968
-
969
-    /**
970
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
-     * the model)
973
-     *
974
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
-     *                                  fields on the model, and the models we joined to in the query. However, you can
978
-     *                                  override this and set the select to "*", or a specific column name, like
979
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
-     *                                  the aliases used to refer to this selection, and values are to be
982
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     */
988
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
-    {
990
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
-        ;
992
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
993
-        $select_expressions = $columns_to_select === null
994
-            ? $this->_construct_default_select_sql($model_query_info)
995
-            : '';
996
-        if ($this->_custom_selections instanceof CustomSelects) {
997
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
-            $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
1000
-                : $custom_expressions;
1001
-        }
1002
-
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
-     * method of including extra select information.
1012
-     *
1013
-     * @param array             $query_params
1014
-     * @param null|array|string $columns_to_select
1015
-     * @return null|CustomSelects
1016
-     * @throws InvalidArgumentException
1017
-     */
1018
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
-    {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
-            return null;
1022
-        }
1023
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
-        return new CustomSelects($selects);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the model query params to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            __(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                'event_espresso'
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(', ', $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(', ', $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
-     * If there is no primary key on this model, $id is treated as primary key string
1121
-     *
1122
-     * @param mixed $id int or string, depending on the type of the model's primary key
1123
-     * @return EE_Base_Class
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        $model_object = $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-        $className = $this->_get_class_name();
1138
-        if ($model_object instanceof $className) {
1139
-            // make sure valid objects get added to the entity map
1140
-            // so that the next call to this method doesn't trigger another trip to the db
1141
-            $this->add_to_entity_map($model_object);
1142
-        }
1143
-        return $model_object;
1144
-    }
1145
-
1146
-
1147
-
1148
-    /**
1149
-     * Alters query parameters to only get items with this ID are returned.
1150
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
-     * or could just be a simple primary key ID
1152
-     *
1153
-     * @param int   $id
1154
-     * @param array $query_params
1155
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
-    {
1160
-        if (! isset($query_params[0])) {
1161
-            $query_params[0] = array();
1162
-        }
1163
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1164
-        if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1166
-        } else {
1167
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1168
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
-        }
1170
-        return $query_params;
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
-     * array. If no item is found, null is returned.
1178
-     *
1179
-     * @param array $query_params like EEM_Base's $query_params variable.
1180
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_one($query_params = array())
1184
-    {
1185
-        if (! is_array($query_params)) {
1186
-            EE_Error::doing_it_wrong(
1187
-                'EEM_Base::get_one',
1188
-                sprintf(
1189
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
-                    gettype($query_params)
1191
-                ),
1192
-                '4.6.0'
1193
-            );
1194
-            $query_params = array();
1195
-        }
1196
-        $query_params['limit'] = 1;
1197
-        $items = $this->get_all($query_params);
1198
-        if (empty($items)) {
1199
-            return null;
1200
-        }
1201
-        return array_shift($items);
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Returns the next x number of items in sequence from the given value as
1208
-     * found in the database matching the given query conditions.
1209
-     *
1210
-     * @param mixed $current_field_value    Value used for the reference point.
1211
-     * @param null  $field_to_order_by      What field is used for the
1212
-     *                                      reference point.
1213
-     * @param int   $limit                  How many to return.
1214
-     * @param array $query_params           Extra conditions on the query.
1215
-     * @param null  $columns_to_select      If left null, then an array of
1216
-     *                                      EE_Base_Class objects is returned,
1217
-     *                                      otherwise you can indicate just the
1218
-     *                                      columns you want returned.
1219
-     * @return EE_Base_Class[]|array
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function next_x(
1223
-        $current_field_value,
1224
-        $field_to_order_by = null,
1225
-        $limit = 1,
1226
-        $query_params = array(),
1227
-        $columns_to_select = null
1228
-    ) {
1229
-        return $this->_get_consecutive(
1230
-            $current_field_value,
1231
-            '>',
1232
-            $field_to_order_by,
1233
-            $limit,
1234
-            $query_params,
1235
-            $columns_to_select
1236
-        );
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     * Returns the previous x number of items in sequence from the given value
1243
-     * as found in the database matching the given query conditions.
1244
-     *
1245
-     * @param mixed $current_field_value    Value used for the reference point.
1246
-     * @param null  $field_to_order_by      What field is used for the
1247
-     *                                      reference point.
1248
-     * @param int   $limit                  How many to return.
1249
-     * @param array $query_params           Extra conditions on the query.
1250
-     * @param null  $columns_to_select      If left null, then an array of
1251
-     *                                      EE_Base_Class objects is returned,
1252
-     *                                      otherwise you can indicate just the
1253
-     *                                      columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function previous_x(
1258
-        $current_field_value,
1259
-        $field_to_order_by = null,
1260
-        $limit = 1,
1261
-        $query_params = array(),
1262
-        $columns_to_select = null
1263
-    ) {
1264
-        return $this->_get_consecutive(
1265
-            $current_field_value,
1266
-            '<',
1267
-            $field_to_order_by,
1268
-            $limit,
1269
-            $query_params,
1270
-            $columns_to_select
1271
-        );
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * Returns the next item in sequence from the given value as found in the
1278
-     * database matching the given query conditions.
1279
-     *
1280
-     * @param mixed $current_field_value    Value used for the reference point.
1281
-     * @param null  $field_to_order_by      What field is used for the
1282
-     *                                      reference point.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
-     *                                      object is returned, otherwise you
1286
-     *                                      can indicate just the columns you
1287
-     *                                      want and a single array indexed by
1288
-     *                                      the columns will be returned.
1289
-     * @return EE_Base_Class|null|array()
1290
-     * @throws EE_Error
1291
-     */
1292
-    public function next(
1293
-        $current_field_value,
1294
-        $field_to_order_by = null,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        $results = $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            1,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the previous item in sequence from the given value as found in
1313
-     * the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed $current_field_value    Value used for the reference point.
1316
-     * @param null  $field_to_order_by      What field is used for the
1317
-     *                                      reference point.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
-     *                                      object is returned, otherwise you
1321
-     *                                      can indicate just the columns you
1322
-     *                                      want and a single array indexed by
1323
-     *                                      the columns will be returned.
1324
-     * @return EE_Base_Class|null|array()
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function previous(
1328
-        $current_field_value,
1329
-        $field_to_order_by = null,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        $results = $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            1,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-        return empty($results) ? null : reset($results);
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * Returns the a consecutive number of items in sequence from the given
1348
-     * value as found in the database matching the given query conditions.
1349
-     *
1350
-     * @param mixed  $current_field_value   Value used for the reference point.
1351
-     * @param string $operand               What operand is used for the sequence.
1352
-     * @param string $field_to_order_by     What field is used for the reference point.
1353
-     * @param int    $limit                 How many to return.
1354
-     * @param array  $query_params          Extra conditions on the query.
1355
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
-     *                                      otherwise you can indicate just the columns you want returned.
1357
-     * @return EE_Base_Class[]|array
1358
-     * @throws EE_Error
1359
-     */
1360
-    protected function _get_consecutive(
1361
-        $current_field_value,
1362
-        $operand = '>',
1363
-        $field_to_order_by = null,
1364
-        $limit = 1,
1365
-        $query_params = array(),
1366
-        $columns_to_select = null
1367
-    ) {
1368
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
-        if (empty($field_to_order_by)) {
1370
-            if ($this->has_primary_key_field()) {
1371
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1372
-            } else {
1373
-                if (WP_DEBUG) {
1374
-                    throw new EE_Error(__(
1375
-                        '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).',
1376
-                        'event_espresso'
1377
-                    ));
1378
-                }
1379
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1380
-                return array();
1381
-            }
1382
-        }
1383
-        if (! is_array($query_params)) {
1384
-            EE_Error::doing_it_wrong(
1385
-                'EEM_Base::_get_consecutive',
1386
-                sprintf(
1387
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
-                    gettype($query_params)
1389
-                ),
1390
-                '4.6.0'
1391
-            );
1392
-            $query_params = array();
1393
-        }
1394
-        // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
-        $query_params['limit'] = $limit;
1397
-        // set direction
1398
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
-        $query_params['order_by'] = $operand === '>'
1400
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
-        if (empty($columns_to_select)) {
1404
-            return $this->get_all($query_params);
1405
-        }
1406
-        // getting just the fields
1407
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This sets the _timezone property after model object has been instantiated.
1414
-     *
1415
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
-     */
1417
-    public function set_timezone($timezone)
1418
-    {
1419
-        if ($timezone !== null) {
1420
-            $this->_timezone = $timezone;
1421
-        }
1422
-        // note we need to loop through relations and set the timezone on those objects as well.
1423
-        foreach ($this->_model_relations as $relation) {
1424
-            $relation->set_timezone($timezone);
1425
-        }
1426
-        // and finally we do the same for any datetime fields
1427
-        foreach ($this->_fields as $field) {
1428
-            if ($field instanceof EE_Datetime_Field) {
1429
-                $field->set_timezone($timezone);
1430
-            }
1431
-        }
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * This just returns whatever is set for the current timezone.
1438
-     *
1439
-     * @access public
1440
-     * @return string
1441
-     */
1442
-    public function get_timezone()
1443
-    {
1444
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
-        if (empty($this->_timezone)) {
1446
-            foreach ($this->_fields as $field) {
1447
-                if ($field instanceof EE_Datetime_Field) {
1448
-                    $this->set_timezone($field->get_timezone());
1449
-                    break;
1450
-                }
1451
-            }
1452
-        }
1453
-        // if timezone STILL empty then return the default timezone for the site.
1454
-        if (empty($this->_timezone)) {
1455
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
-        }
1457
-        return $this->_timezone;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This returns the date formats set for the given field name and also ensures that
1464
-     * $this->_timezone property is set correctly.
1465
-     *
1466
-     * @since 4.6.x
1467
-     * @param string $field_name The name of the field the formats are being retrieved for.
1468
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
-     * @return array formats in an array with the date format first, and the time format last.
1471
-     */
1472
-    public function get_formats_for($field_name, $pretty = false)
1473
-    {
1474
-        $field_settings = $this->field_settings_for($field_name);
1475
-        // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1477
-            throw new EE_Error(sprintf(__(
1478
-                '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.',
1479
-                'event_espresso'
1480
-            ), $field_name));
1481
-        }
1482
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
-        // the field.
1484
-        $this->_timezone = $field_settings->get_timezone();
1485
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * This returns the current time in a format setup for a query on this model.
1492
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
-     * it will return:
1494
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
-     *  NOW
1496
-     *  - or a unix timestamp (equivalent to time())
1497
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
-     * @since 4.6.x
1501
-     * @param string $field_name       The field the current time is needed for.
1502
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
-     *                                 formatted string matching the set format for the field in the set timezone will
1504
-     *                                 be returned.
1505
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
-     *                                 exception is triggered.
1509
-     */
1510
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
-    {
1512
-        $formats = $this->get_formats_for($field_name);
1513
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
-        if ($timestamp) {
1515
-            return $DateTime->format('U');
1516
-        }
1517
-        // not returning timestamp, so return formatted string in timezone.
1518
-        switch ($what) {
1519
-            case 'time':
1520
-                return $DateTime->format($formats[1]);
1521
-                break;
1522
-            case 'date':
1523
-                return $DateTime->format($formats[0]);
1524
-                break;
1525
-            default:
1526
-                return $DateTime->format(implode(' ', $formats));
1527
-                break;
1528
-        }
1529
-    }
1530
-
1531
-
1532
-
1533
-    /**
1534
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
-     * for the model are.  Returns a DateTime object.
1536
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
-     * ignored.
1539
-     *
1540
-     * @param string $field_name      The field being setup.
1541
-     * @param string $timestring      The date time string being used.
1542
-     * @param string $incoming_format The format for the time string.
1543
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
-     *                                format is
1546
-     *                                'U', this is ignored.
1547
-     * @return DateTime
1548
-     * @throws EE_Error
1549
-     */
1550
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
-    {
1552
-        // just using this to ensure the timezone is set correctly internally
1553
-        $this->get_formats_for($field_name);
1554
-        // load EEH_DTT_Helper
1555
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
-     *
1566
-     * @return EE_Table_Base[]
1567
-     */
1568
-    public function get_tables()
1569
-    {
1570
-        return $this->_tables;
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
-     * model object with EVT_ID = 1
1582
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
-     * are not specified)
1587
-     *
1588
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1593
-     *                                         ID=34, we'd use this method as follows:
1594
-     *                                         EEM_Transaction::instance()->update(
1595
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
-     *                                         array(array('TXN_ID'=>34)));
1597
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
-     *                                         TRUE, it is assumed that you've already called
1604
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
-     *                                         malicious javascript. However, if
1606
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
-     *                                         and every other field, before insertion. We provide this parameter
1609
-     *                                         because model objects perform their prepare_for_set function on all
1610
-     *                                         their values, and so don't need to be called again (and in many cases,
1611
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
-     *                                         prepare_for_set method...)
1613
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
-     *                                         in this model's entity map according to $fields_n_values that match
1615
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1616
-     *                                         by setting this to FALSE, but be aware that model objects being used
1617
-     *                                         could get out-of-sync with the database
1618
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
-     *                                         bad)
1621
-     * @throws EE_Error
1622
-     */
1623
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
-    {
1625
-        if (! is_array($query_params)) {
1626
-            EE_Error::doing_it_wrong(
1627
-                'EEM_Base::update',
1628
-                sprintf(
1629
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
-                    gettype($query_params)
1631
-                ),
1632
-                '4.6.0'
1633
-            );
1634
-            $query_params = array();
1635
-        }
1636
-        /**
1637
-         * Action called before a model update call has been made.
1638
-         *
1639
-         * @param EEM_Base $model
1640
-         * @param array    $fields_n_values the updated fields and their new values
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
-        /**
1645
-         * Filters the fields about to be updated given the query parameters. You can provide the
1646
-         * $query_params to $this->get_all() to find exactly which records will be updated
1647
-         *
1648
-         * @param array    $fields_n_values fields and their new values
1649
-         * @param EEM_Base $model           the model being queried
1650
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
-         */
1652
-        $fields_n_values = (array) apply_filters(
1653
-            'FHEE__EEM_Base__update__fields_n_values',
1654
-            $fields_n_values,
1655
-            $this,
1656
-            $query_params
1657
-        );
1658
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
-        // to do that, for each table, verify that it's PK isn't null.
1660
-        $tables = $this->get_tables();
1661
-        // 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
1662
-        // NOTE: we should make this code more efficient by NOT querying twice
1663
-        // before the real update, but that needs to first go through ALPHA testing
1664
-        // as it's dangerous. says Mike August 8 2014
1665
-        // we want to make sure the default_where strategy is ignored
1666
-        $this->_ignore_where_strategy = true;
1667
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
-        foreach ($wpdb_select_results as $wpdb_result) {
1669
-            // type cast stdClass as array
1670
-            $wpdb_result = (array) $wpdb_result;
1671
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
-            if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
-            } else {
1675
-                // 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)
1676
-                $main_table_pk_value = null;
1677
-            }
1678
-            // 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
1679
-            // 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
1680
-            if (count($tables) > 1) {
1681
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
-                // in that table, and so we'll want to insert one
1683
-                foreach ($tables as $table_obj) {
1684
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
-                    // if there is no private key for this table on the results, it means there's no entry
1686
-                    // in this table, right? so insert a row in the current table, using any fields available
1687
-                    if (
1688
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1690
-                    ) {
1691
-                        $success = $this->_insert_into_specific_table(
1692
-                            $table_obj,
1693
-                            $fields_n_values,
1694
-                            $main_table_pk_value
1695
-                        );
1696
-                        // if we died here, report the error
1697
-                        if (! $success) {
1698
-                            return false;
1699
-                        }
1700
-                    }
1701
-                }
1702
-            }
1703
-            //              //and now check that if we have cached any models by that ID on the model, that
1704
-            //              //they also get updated properly
1705
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
-            //              if( $model_object ){
1707
-            //                  foreach( $fields_n_values as $field => $value ){
1708
-            //                      $model_object->set($field, $value);
1709
-            // let's make sure default_where strategy is followed now
1710
-            $this->_ignore_where_strategy = false;
1711
-        }
1712
-        // if we want to keep model objects in sync, AND
1713
-        // if this wasn't called from a model object (to update itself)
1714
-        // then we want to make sure we keep all the existing
1715
-        // model objects in sync with the db
1716
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
-            if ($this->has_primary_key_field()) {
1718
-                $model_objs_affected_ids = $this->get_col($query_params);
1719
-            } else {
1720
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
-                $model_objs_affected_ids = array();
1723
-                foreach ($models_affected_key_columns as $row) {
1724
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
-                }
1727
-            }
1728
-            if (! $model_objs_affected_ids) {
1729
-                // wait wait wait- if nothing was affected let's stop here
1730
-                return 0;
1731
-            }
1732
-            foreach ($model_objs_affected_ids as $id) {
1733
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
-                if ($model_obj_in_entity_map) {
1735
-                    foreach ($fields_n_values as $field => $new_value) {
1736
-                        $model_obj_in_entity_map->set($field, $new_value);
1737
-                    }
1738
-                }
1739
-            }
1740
-            // if there is a primary key on this model, we can now do a slight optimization
1741
-            if ($this->has_primary_key_field()) {
1742
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
-                $query_params = array(
1744
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
-                    'limit'                    => count($model_objs_affected_ids),
1746
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
-                );
1748
-            }
1749
-        }
1750
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
-        $SQL = "UPDATE "
1752
-               . $model_query_info->get_full_join_sql()
1753
-               . " SET "
1754
-               . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
-        /**
1758
-         * Action called after a model update call has been made.
1759
-         *
1760
-         * @param EEM_Base $model
1761
-         * @param array    $fields_n_values the updated fields and their new values
1762
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
-         * @param int      $rows_affected
1764
-         */
1765
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
-     * are teh values of the field specified (or by default the primary key field)
1774
-     * that matched the query params. Note that you should pass the name of the
1775
-     * model FIELD, not the database table's column name.
1776
-     *
1777
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
-     * @param string $field_to_select
1779
-     * @return array just like $wpdb->get_col()
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function get_col($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        if ($field_to_select) {
1785
-            $field = $this->field_settings_for($field_to_select);
1786
-        } elseif ($this->has_primary_key_field()) {
1787
-            $field = $this->get_primary_key_field();
1788
-        } else {
1789
-            // no primary key, just grab the first column
1790
-            $field = reset($this->field_settings());
1791
-        }
1792
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
-        $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
-        return $this->_do_wpdb_query('get_col', array($SQL));
1796
-    }
1797
-
1798
-
1799
-
1800
-    /**
1801
-     * Returns a single column value for a single row from the database
1802
-     *
1803
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
-     * @param string $field_to_select @see EEM_Base::get_col()
1805
-     * @return string
1806
-     * @throws EE_Error
1807
-     */
1808
-    public function get_var($query_params = array(), $field_to_select = null)
1809
-    {
1810
-        $query_params['limit'] = 1;
1811
-        $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1813
-            return reset($col);
1814
-        }
1815
-        return null;
1816
-    }
1817
-
1818
-
1819
-
1820
-    /**
1821
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
-     * injection, but currently no further filtering is done
1824
-     *
1825
-     * @global      $wpdb
1826
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
-     *                               be updated to in the DB
1828
-     * @return string of SQL
1829
-     * @throws EE_Error
1830
-     */
1831
-    public function _construct_update_sql($fields_n_values)
1832
-    {
1833
-        /** @type WPDB $wpdb */
1834
-        global $wpdb;
1835
-        $cols_n_values = array();
1836
-        foreach ($fields_n_values as $field_name => $value) {
1837
-            $field_obj = $this->field_settings_for($field_name);
1838
-            // if the value is NULL, we want to assign the value to that.
1839
-            // wpdb->prepare doesn't really handle that properly
1840
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
-            $value_sql = $prepared_value === null ? 'NULL'
1842
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
-        }
1845
-        return implode(",", $cols_n_values);
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
-     * Performs a HARD delete, meaning the database row should always be removed,
1853
-     * not just have a flag field on it switched
1854
-     * Wrapper for EEM_Base::delete_permanently()
1855
-     *
1856
-     * @param mixed $id
1857
-     * @param boolean $allow_blocking
1858
-     * @return int the number of rows deleted
1859
-     * @throws EE_Error
1860
-     */
1861
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
-    {
1863
-        return $this->delete_permanently(
1864
-            array(
1865
-                array($this->get_primary_key_field()->get_name() => $id),
1866
-                'limit' => 1,
1867
-            ),
1868
-            $allow_blocking
1869
-        );
1870
-    }
1871
-
1872
-
1873
-
1874
-    /**
1875
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
-     * Wrapper for EEM_Base::delete()
1877
-     *
1878
-     * @param mixed $id
1879
-     * @param boolean $allow_blocking
1880
-     * @return int the number of rows deleted
1881
-     * @throws EE_Error
1882
-     */
1883
-    public function delete_by_ID($id, $allow_blocking = true)
1884
-    {
1885
-        return $this->delete(
1886
-            array(
1887
-                array($this->get_primary_key_field()->get_name() => $id),
1888
-                'limit' => 1,
1889
-            ),
1890
-            $allow_blocking
1891
-        );
1892
-    }
1893
-
1894
-
1895
-
1896
-    /**
1897
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1898
-     * meaning if the model has a field that indicates its been "trashed" or
1899
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1900
-     *
1901
-     * @see EEM_Base::delete_permanently
1902
-     * @param array   $query_params
1903
-     * @param boolean $allow_blocking
1904
-     * @return int how many rows got deleted
1905
-     * @throws EE_Error
1906
-     */
1907
-    public function delete($query_params, $allow_blocking = true)
1908
-    {
1909
-        return $this->delete_permanently($query_params, $allow_blocking);
1910
-    }
1911
-
1912
-
1913
-
1914
-    /**
1915
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1916
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
-     * as archived, not actually deleted
1918
-     *
1919
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
-     *                                deletes regardless of other objects which may depend on it. Its generally
1923
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
-     *                                DB
1925
-     * @return int how many rows got deleted
1926
-     * @throws EE_Error
1927
-     */
1928
-    public function delete_permanently($query_params, $allow_blocking = true)
1929
-    {
1930
-        /**
1931
-         * Action called just before performing a real deletion query. You can use the
1932
-         * model and its $query_params to find exactly which items will be deleted
1933
-         *
1934
-         * @param EEM_Base $model
1935
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1937
-         *                                 to block (prevent) this deletion
1938
-         */
1939
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
-        // some MySQL databases may be running safe mode, which may restrict
1941
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
-        // to delete them
1944
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
-            $columns_and_ids_for_deleting
1948
-        );
1949
-        /**
1950
-         * Allows client code to act on the items being deleted before the query is actually executed.
1951
-         *
1952
-         * @param EEM_Base $this  The model instance being acted on.
1953
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
-         *                                                  derived from the incoming query parameters.
1957
-         *                                                  @see details on the structure of this array in the phpdocs
1958
-         *                                                  for the `_get_ids_for_delete_method`
1959
-         *
1960
-         */
1961
-        do_action(
1962
-            'AHEE__EEM_Base__delete__before_query',
1963
-            $this,
1964
-            $query_params,
1965
-            $allow_blocking,
1966
-            $columns_and_ids_for_deleting
1967
-        );
1968
-        if ($deletion_where_query_part) {
1969
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
-            $table_aliases = array_keys($this->_tables);
1971
-            $SQL = "DELETE "
1972
-                   . implode(", ", $table_aliases)
1973
-                   . " FROM "
1974
-                   . $model_query_info->get_full_join_sql()
1975
-                   . " WHERE "
1976
-                   . $deletion_where_query_part;
1977
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
-        } else {
1979
-            $rows_deleted = 0;
1980
-        }
1981
-
1982
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
-        // there was no error with the delete query.
1984
-        if (
1985
-            $this->has_primary_key_field()
1986
-            && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
-        ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
-            foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
-                }
1994
-            }
1995
-
1996
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
-            // (although it is possible).
2000
-            // Note this can be skipped by using the provided filter and returning false.
2001
-            if (
2002
-                apply_filters(
2003
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
-                    ! $this instanceof EEM_Extra_Meta,
2005
-                    $this
2006
-                )
2007
-            ) {
2008
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2009
-                    0 => array(
2010
-                        'EXM_type' => $this->get_this_model_name(),
2011
-                        'OBJ_ID'   => array(
2012
-                            'IN',
2013
-                            $ids_for_removal
2014
-                        )
2015
-                    )
2016
-                ));
2017
-            }
2018
-        }
2019
-
2020
-        /**
2021
-         * Action called just after performing a real deletion query. Although at this point the
2022
-         * items should have been deleted
2023
-         *
2024
-         * @param EEM_Base $model
2025
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
-         * @param int      $rows_deleted
2027
-         */
2028
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Checks all the relations that throw error messages when there are blocking related objects
2036
-     * for related model objects. If there are any related model objects on those relations,
2037
-     * adds an EE_Error, and return true
2038
-     *
2039
-     * @param EE_Base_Class|int $this_model_obj_or_id
2040
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
-     *                                                 should be ignored when determining whether there are related
2042
-     *                                                 model objects which block this model object's deletion. Useful
2043
-     *                                                 if you know A is related to B and are considering deleting A,
2044
-     *                                                 but want to see if A has any other objects blocking its deletion
2045
-     *                                                 before removing the relation between A and B
2046
-     * @return boolean
2047
-     * @throws EE_Error
2048
-     */
2049
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
-    {
2051
-        // first, if $ignore_this_model_obj was supplied, get its model
2052
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
-            $ignored_model = $ignore_this_model_obj->get_model();
2054
-        } else {
2055
-            $ignored_model = null;
2056
-        }
2057
-        // now check all the relations of $this_model_obj_or_id and see if there
2058
-        // are any related model objects blocking it?
2059
-        $is_blocked = false;
2060
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2062
-                // if $ignore_this_model_obj was supplied, then for the query
2063
-                // on that model needs to be told to ignore $ignore_this_model_obj
2064
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
-                        array(
2067
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2068
-                                '!=',
2069
-                                $ignore_this_model_obj->ID(),
2070
-                            ),
2071
-                        ),
2072
-                    ));
2073
-                } else {
2074
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
-                }
2076
-                if ($related_model_objects) {
2077
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
-                    $is_blocked = true;
2079
-                }
2080
-            }
2081
-        }
2082
-        return $is_blocked;
2083
-    }
2084
-
2085
-
2086
-    /**
2087
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
-     * @param array $row_results_for_deleting
2089
-     * @param bool  $allow_blocking
2090
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
-     *                 deleted. Example:
2094
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2095
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
-     *                 where each element is a group of columns and values that get deleted. Example:
2097
-     *                      array(
2098
-     *                          0 => array(
2099
-     *                              'Term_Relationship.object_id' => 1
2100
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2101
-     *                          ),
2102
-     *                          1 => array(
2103
-     *                              'Term_Relationship.object_id' => 1
2104
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2105
-     *                          )
2106
-     *                      )
2107
-     * @throws EE_Error
2108
-     */
2109
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
-    {
2111
-        $ids_to_delete_indexed_by_column = array();
2112
-        if ($this->has_primary_key_field()) {
2113
-            $primary_table = $this->_get_main_table();
2114
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
-            $other_tables = $this->_get_other_tables();
2116
-            $ids_to_delete_indexed_by_column = $query = array();
2117
-            foreach ($row_results_for_deleting as $item_to_delete) {
2118
-                // before we mark this item for deletion,
2119
-                // make sure there's no related entities blocking its deletion (if we're checking)
2120
-                if (
2121
-                    $allow_blocking
2122
-                    && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
-                    )
2125
-                ) {
2126
-                    continue;
2127
-                }
2128
-                // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
-                }
2133
-            }
2134
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
-            $fields = $this->get_combined_primary_key_fields();
2136
-            foreach ($row_results_for_deleting as $item_to_delete) {
2137
-                $ids_to_delete_indexed_by_column_for_row = array();
2138
-                foreach ($fields as $cpk_field) {
2139
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2142
-                    }
2143
-                }
2144
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
-            }
2146
-        } else {
2147
-            // so there's no primary key and no combined key...
2148
-            // sorry, can't help you
2149
-            throw new EE_Error(
2150
-                sprintf(
2151
-                    __(
2152
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
-                        "event_espresso"
2154
-                    ),
2155
-                    get_class($this)
2156
-                )
2157
-            );
2158
-        }
2159
-        return $ids_to_delete_indexed_by_column;
2160
-    }
2161
-
2162
-
2163
-    /**
2164
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
-     * the corresponding query_part for the query performing the delete.
2166
-     *
2167
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
-     * @return string
2169
-     * @throws EE_Error
2170
-     */
2171
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
-    {
2173
-        $query_part = '';
2174
-        if (empty($ids_to_delete_indexed_by_column)) {
2175
-            return $query_part;
2176
-        } elseif ($this->has_primary_key_field()) {
2177
-            $query = array();
2178
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
-                // make sure we have unique $ids
2180
-                $ids = array_unique($ids);
2181
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2182
-            }
2183
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
-            $ways_to_identify_a_row = array();
2186
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187
-                $values_for_each_combined_primary_key_for_a_row = array();
2188
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2190
-                }
2191
-                $ways_to_identify_a_row[] = '('
2192
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2193
-                                            . ')';
2194
-            }
2195
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2196
-        }
2197
-        return $query_part;
2198
-    }
2199
-
2200
-
2201
-
2202
-    /**
2203
-     * Gets the model field by the fully qualified name
2204
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2205
-     * @return EE_Model_Field_Base
2206
-     */
2207
-    public function get_field_by_column($qualified_column_name)
2208
-    {
2209
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2210
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2211
-                return $field_obj;
2212
-            }
2213
-        }
2214
-        throw new EE_Error(
2215
-            sprintf(
2216
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2217
-                $this->get_this_model_name(),
2218
-                $qualified_column_name
2219
-            )
2220
-        );
2221
-    }
2222
-
2223
-
2224
-
2225
-    /**
2226
-     * Count all the rows that match criteria the model query params.
2227
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2228
-     * column
2229
-     *
2230
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2231
-     * @param string $field_to_count field on model to count by (not column name)
2232
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2233
-     *                               that by the setting $distinct to TRUE;
2234
-     * @return int
2235
-     * @throws EE_Error
2236
-     */
2237
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2238
-    {
2239
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2240
-        if ($field_to_count) {
2241
-            $field_obj = $this->field_settings_for($field_to_count);
2242
-            $column_to_count = $field_obj->get_qualified_column();
2243
-        } elseif ($this->has_primary_key_field()) {
2244
-            $pk_field_obj = $this->get_primary_key_field();
2245
-            $column_to_count = $pk_field_obj->get_qualified_column();
2246
-        } else {
2247
-            // there's no primary key
2248
-            // if we're counting distinct items, and there's no primary key,
2249
-            // we need to list out the columns for distinction;
2250
-            // otherwise we can just use star
2251
-            if ($distinct) {
2252
-                $columns_to_use = array();
2253
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2254
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2255
-                }
2256
-                $column_to_count = implode(',', $columns_to_use);
2257
-            } else {
2258
-                $column_to_count = '*';
2259
-            }
2260
-        }
2261
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2263
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264
-    }
2265
-
2266
-
2267
-
2268
-    /**
2269
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2270
-     *
2271
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
-     * @param string $field_to_sum name of field (array key in $_fields array)
2273
-     * @return float
2274
-     * @throws EE_Error
2275
-     */
2276
-    public function sum($query_params, $field_to_sum = null)
2277
-    {
2278
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2279
-        if ($field_to_sum) {
2280
-            $field_obj = $this->field_settings_for($field_to_sum);
2281
-        } else {
2282
-            $field_obj = $this->get_primary_key_field();
2283
-        }
2284
-        $column_to_count = $field_obj->get_qualified_column();
2285
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287
-        $data_type = $field_obj->get_wpdb_data_type();
2288
-        if ($data_type === '%d' || $data_type === '%s') {
2289
-            return (float) $return_value;
2290
-        }
2291
-        // must be %f
2292
-        return (float) $return_value;
2293
-    }
2294
-
2295
-
2296
-
2297
-    /**
2298
-     * Just calls the specified method on $wpdb with the given arguments
2299
-     * Consolidates a little extra error handling code
2300
-     *
2301
-     * @param string $wpdb_method
2302
-     * @param array  $arguments_to_provide
2303
-     * @throws EE_Error
2304
-     * @global wpdb  $wpdb
2305
-     * @return mixed
2306
-     */
2307
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2308
-    {
2309
-        // if we're in maintenance mode level 2, DON'T run any queries
2310
-        // because level 2 indicates the database needs updating and
2311
-        // is probably out of sync with the code
2312
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2313
-            throw new EE_Error(sprintf(__(
2314
-                "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.",
2315
-                "event_espresso"
2316
-            )));
2317
-        }
2318
-        /** @type WPDB $wpdb */
2319
-        global $wpdb;
2320
-        if (! method_exists($wpdb, $wpdb_method)) {
2321
-            throw new EE_Error(sprintf(__(
2322
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2323
-                'event_espresso'
2324
-            ), $wpdb_method));
2325
-        }
2326
-        if (WP_DEBUG) {
2327
-            $old_show_errors_value = $wpdb->show_errors;
2328
-            $wpdb->show_errors(false);
2329
-        }
2330
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2332
-        if (WP_DEBUG) {
2333
-            $wpdb->show_errors($old_show_errors_value);
2334
-            if (! empty($wpdb->last_error)) {
2335
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336
-            }
2337
-            if ($result === false) {
2338
-                throw new EE_Error(sprintf(__(
2339
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2340
-                    'event_espresso'
2341
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2342
-            }
2343
-        } elseif ($result === false) {
2344
-            EE_Error::add_error(
2345
-                sprintf(
2346
-                    __(
2347
-                        '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"',
2348
-                        'event_espresso'
2349
-                    ),
2350
-                    $wpdb_method,
2351
-                    var_export($arguments_to_provide, true),
2352
-                    $wpdb->last_error
2353
-                ),
2354
-                __FILE__,
2355
-                __FUNCTION__,
2356
-                __LINE__
2357
-            );
2358
-        }
2359
-        return $result;
2360
-    }
2361
-
2362
-
2363
-
2364
-    /**
2365
-     * Attempts to run the indicated WPDB method with the provided arguments,
2366
-     * and if there's an error tries to verify the DB is correct. Uses
2367
-     * the static property EEM_Base::$_db_verification_level to determine whether
2368
-     * we should try to fix the EE core db, the addons, or just give up
2369
-     *
2370
-     * @param string $wpdb_method
2371
-     * @param array  $arguments_to_provide
2372
-     * @return mixed
2373
-     */
2374
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2375
-    {
2376
-        /** @type WPDB $wpdb */
2377
-        global $wpdb;
2378
-        $wpdb->last_error = null;
2379
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2380
-        // was there an error running the query? but we don't care on new activations
2381
-        // (we're going to setup the DB anyway on new activations)
2382
-        if (
2383
-            ($result === false || ! empty($wpdb->last_error))
2384
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2385
-        ) {
2386
-            switch (EEM_Base::$_db_verification_level) {
2387
-                case EEM_Base::db_verified_none:
2388
-                    // let's double-check core's DB
2389
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2390
-                    break;
2391
-                case EEM_Base::db_verified_core:
2392
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2393
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2394
-                    break;
2395
-                case EEM_Base::db_verified_addons:
2396
-                    // ummmm... you in trouble
2397
-                    return $result;
2398
-                    break;
2399
-            }
2400
-            if (! empty($error_message)) {
2401
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402
-                trigger_error($error_message);
2403
-            }
2404
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2405
-        }
2406
-        return $result;
2407
-    }
2408
-
2409
-
2410
-
2411
-    /**
2412
-     * Verifies the EE core database is up-to-date and records that we've done it on
2413
-     * EEM_Base::$_db_verification_level
2414
-     *
2415
-     * @param string $wpdb_method
2416
-     * @param array  $arguments_to_provide
2417
-     * @return string
2418
-     */
2419
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2420
-    {
2421
-        /** @type WPDB $wpdb */
2422
-        global $wpdb;
2423
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2424
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2425
-        $error_message = sprintf(
2426
-            __(
2427
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
-                'event_espresso'
2429
-            ),
2430
-            $wpdb->last_error,
2431
-            $wpdb_method,
2432
-            wp_json_encode($arguments_to_provide)
2433
-        );
2434
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2435
-        return $error_message;
2436
-    }
2437
-
2438
-
2439
-
2440
-    /**
2441
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2442
-     * EEM_Base::$_db_verification_level
2443
-     *
2444
-     * @param $wpdb_method
2445
-     * @param $arguments_to_provide
2446
-     * @return string
2447
-     */
2448
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2449
-    {
2450
-        /** @type WPDB $wpdb */
2451
-        global $wpdb;
2452
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2453
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2454
-        $error_message = sprintf(
2455
-            __(
2456
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2457
-                'event_espresso'
2458
-            ),
2459
-            $wpdb->last_error,
2460
-            $wpdb_method,
2461
-            wp_json_encode($arguments_to_provide)
2462
-        );
2463
-        EE_System::instance()->initialize_addons();
2464
-        return $error_message;
2465
-    }
2466
-
2467
-
2468
-
2469
-    /**
2470
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2471
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2472
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2473
-     * ..."
2474
-     *
2475
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2476
-     * @return string
2477
-     */
2478
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479
-    {
2480
-        return " FROM " . $model_query_info->get_full_join_sql() .
2481
-               $model_query_info->get_where_sql() .
2482
-               $model_query_info->get_group_by_sql() .
2483
-               $model_query_info->get_having_sql() .
2484
-               $model_query_info->get_order_by_sql() .
2485
-               $model_query_info->get_limit_sql();
2486
-    }
2487
-
2488
-
2489
-
2490
-    /**
2491
-     * Set to easily debug the next X queries ran from this model.
2492
-     *
2493
-     * @param int $count
2494
-     */
2495
-    public function show_next_x_db_queries($count = 1)
2496
-    {
2497
-        $this->_show_next_x_db_queries = $count;
2498
-    }
2499
-
2500
-
2501
-
2502
-    /**
2503
-     * @param $sql_query
2504
-     */
2505
-    public function show_db_query_if_previously_requested($sql_query)
2506
-    {
2507
-        if ($this->_show_next_x_db_queries > 0) {
2508
-            echo $sql_query;
2509
-            $this->_show_next_x_db_queries--;
2510
-        }
2511
-    }
2512
-
2513
-
2514
-
2515
-    /**
2516
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2517
-     * There are the 3 cases:
2518
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2519
-     * $otherModelObject has no ID, it is first saved.
2520
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2521
-     * has no ID, it is first saved.
2522
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2523
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2524
-     * join table
2525
-     *
2526
-     * @param        EE_Base_Class                     /int $thisModelObject
2527
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2528
-     * @param string $relationName                     , key in EEM_Base::_relations
2529
-     *                                                 an attendee to a group, you also want to specify which role they
2530
-     *                                                 will have in that group. So you would use this parameter to
2531
-     *                                                 specify array('role-column-name'=>'role-id')
2532
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2533
-     *                                                 to for relation to methods that allow you to further specify
2534
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2535
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2536
-     *                                                 because these will be inserted in any new rows created as well.
2537
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2538
-     * @throws EE_Error
2539
-     */
2540
-    public function add_relationship_to(
2541
-        $id_or_obj,
2542
-        $other_model_id_or_obj,
2543
-        $relationName,
2544
-        $extra_join_model_fields_n_values = array()
2545
-    ) {
2546
-        $relation_obj = $this->related_settings_for($relationName);
2547
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2548
-    }
2549
-
2550
-
2551
-
2552
-    /**
2553
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2554
-     * There are the 3 cases:
2555
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2556
-     * error
2557
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2558
-     * an error
2559
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2560
-     *
2561
-     * @param        EE_Base_Class /int $id_or_obj
2562
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2563
-     * @param string $relationName key in EEM_Base::_relations
2564
-     * @return boolean of success
2565
-     * @throws EE_Error
2566
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2567
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2568
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2569
-     *                             because these will be inserted in any new rows created as well.
2570
-     */
2571
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2572
-    {
2573
-        $relation_obj = $this->related_settings_for($relationName);
2574
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * @param mixed           $id_or_obj
2581
-     * @param string          $relationName
2582
-     * @param array           $where_query_params
2583
-     * @param EE_Base_Class[] objects to which relations were removed
2584
-     * @return \EE_Base_Class[]
2585
-     * @throws EE_Error
2586
-     */
2587
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2588
-    {
2589
-        $relation_obj = $this->related_settings_for($relationName);
2590
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2591
-    }
2592
-
2593
-
2594
-
2595
-    /**
2596
-     * Gets all the related items of the specified $model_name, using $query_params.
2597
-     * Note: by default, we remove the "default query params"
2598
-     * because we want to get even deleted items etc.
2599
-     *
2600
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2601
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2602
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
-     * @return EE_Base_Class[]
2604
-     * @throws EE_Error
2605
-     */
2606
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2607
-    {
2608
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2609
-        $relation_settings = $this->related_settings_for($model_name);
2610
-        return $relation_settings->get_all_related($model_obj, $query_params);
2611
-    }
2612
-
2613
-
2614
-
2615
-    /**
2616
-     * Deletes all the model objects across the relation indicated by $model_name
2617
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2618
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2619
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2620
-     *
2621
-     * @param EE_Base_Class|int|string $id_or_obj
2622
-     * @param string                   $model_name
2623
-     * @param array                    $query_params
2624
-     * @return int how many deleted
2625
-     * @throws EE_Error
2626
-     */
2627
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2628
-    {
2629
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2630
-        $relation_settings = $this->related_settings_for($model_name);
2631
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2632
-    }
2633
-
2634
-
2635
-
2636
-    /**
2637
-     * Hard deletes all the model objects across the relation indicated by $model_name
2638
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2639
-     * the model objects can't be hard deleted because of blocking related model objects,
2640
-     * just does a soft-delete on them instead.
2641
-     *
2642
-     * @param EE_Base_Class|int|string $id_or_obj
2643
-     * @param string                   $model_name
2644
-     * @param array                    $query_params
2645
-     * @return int how many deleted
2646
-     * @throws EE_Error
2647
-     */
2648
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2649
-    {
2650
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2651
-        $relation_settings = $this->related_settings_for($model_name);
2652
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2653
-    }
2654
-
2655
-
2656
-
2657
-    /**
2658
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2659
-     * unless otherwise specified in the $query_params
2660
-     *
2661
-     * @param        int             /EE_Base_Class $id_or_obj
2662
-     * @param string $model_name     like 'Event', or 'Registration'
2663
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2664
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2665
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2666
-     *                               that by the setting $distinct to TRUE;
2667
-     * @return int
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function count_related(
2671
-        $id_or_obj,
2672
-        $model_name,
2673
-        $query_params = array(),
2674
-        $field_to_count = null,
2675
-        $distinct = false
2676
-    ) {
2677
-        $related_model = $this->get_related_model_obj($model_name);
2678
-        // we're just going to use the query params on the related model's normal get_all query,
2679
-        // except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2681
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
-        }
2683
-        $this_model_name = $this->get_this_model_name();
2684
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2686
-        return $related_model->count($query_params, $field_to_count, $distinct);
2687
-    }
2688
-
2689
-
2690
-
2691
-    /**
2692
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2693
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2694
-     *
2695
-     * @param        int           /EE_Base_Class $id_or_obj
2696
-     * @param string $model_name   like 'Event', or 'Registration'
2697
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2698
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2699
-     * @return float
2700
-     * @throws EE_Error
2701
-     */
2702
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703
-    {
2704
-        $related_model = $this->get_related_model_obj($model_name);
2705
-        if (! is_array($query_params)) {
2706
-            EE_Error::doing_it_wrong(
2707
-                'EEM_Base::sum_related',
2708
-                sprintf(
2709
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2710
-                    gettype($query_params)
2711
-                ),
2712
-                '4.6.0'
2713
-            );
2714
-            $query_params = array();
2715
-        }
2716
-        // we're just going to use the query params on the related model's normal get_all query,
2717
-        // except add a condition to say to match the current mod
2718
-        if (! isset($query_params['default_where_conditions'])) {
2719
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720
-        }
2721
-        $this_model_name = $this->get_this_model_name();
2722
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2724
-        return $related_model->sum($query_params, $field_to_sum);
2725
-    }
2726
-
2727
-
2728
-
2729
-    /**
2730
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2731
-     * $modelObject
2732
-     *
2733
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2734
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2735
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
-     * @return EE_Base_Class
2737
-     * @throws EE_Error
2738
-     */
2739
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2740
-    {
2741
-        $query_params['limit'] = 1;
2742
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2743
-        if ($results) {
2744
-            return array_shift($results);
2745
-        }
2746
-        return null;
2747
-    }
2748
-
2749
-
2750
-
2751
-    /**
2752
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2753
-     *
2754
-     * @return string
2755
-     */
2756
-    public function get_this_model_name()
2757
-    {
2758
-        return str_replace("EEM_", "", get_class($this));
2759
-    }
2760
-
2761
-
2762
-
2763
-    /**
2764
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2765
-     *
2766
-     * @return EE_Any_Foreign_Model_Name_Field
2767
-     * @throws EE_Error
2768
-     */
2769
-    public function get_field_containing_related_model_name()
2770
-    {
2771
-        foreach ($this->field_settings(true) as $field) {
2772
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2773
-                $field_with_model_name = $field;
2774
-            }
2775
-        }
2776
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2777
-            throw new EE_Error(sprintf(
2778
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779
-                $this->get_this_model_name()
2780
-            ));
2781
-        }
2782
-        return $field_with_model_name;
2783
-    }
2784
-
2785
-
2786
-
2787
-    /**
2788
-     * Inserts a new entry into the database, for each table.
2789
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2790
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2791
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2792
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2793
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2794
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2795
-     *
2796
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2797
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2798
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2799
-     *                              of EEM_Base)
2800
-     * @return int|string new primary key on main table that got inserted
2801
-     * @throws EE_Error
2802
-     */
2803
-    public function insert($field_n_values)
2804
-    {
2805
-        /**
2806
-         * Filters the fields and their values before inserting an item using the models
2807
-         *
2808
-         * @param array    $fields_n_values keys are the fields and values are their new values
2809
-         * @param EEM_Base $model           the model used
2810
-         */
2811
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2812
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2813
-            $main_table = $this->_get_main_table();
2814
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2815
-            if ($new_id !== false) {
2816
-                foreach ($this->_get_other_tables() as $other_table) {
2817
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2818
-                }
2819
-            }
2820
-            /**
2821
-             * Done just after attempting to insert a new model object
2822
-             *
2823
-             * @param EEM_Base   $model           used
2824
-             * @param array      $fields_n_values fields and their values
2825
-             * @param int|string the              ID of the newly-inserted model object
2826
-             */
2827
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2828
-            return $new_id;
2829
-        }
2830
-        return false;
2831
-    }
2832
-
2833
-
2834
-
2835
-    /**
2836
-     * Checks that the result would satisfy the unique indexes on this model
2837
-     *
2838
-     * @param array  $field_n_values
2839
-     * @param string $action
2840
-     * @return boolean
2841
-     * @throws EE_Error
2842
-     */
2843
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2844
-    {
2845
-        foreach ($this->unique_indexes() as $index_name => $index) {
2846
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2847
-            if ($this->exists(array($uniqueness_where_params))) {
2848
-                EE_Error::add_error(
2849
-                    sprintf(
2850
-                        __(
2851
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2852
-                            "event_espresso"
2853
-                        ),
2854
-                        $action,
2855
-                        $this->_get_class_name(),
2856
-                        $index_name,
2857
-                        implode(",", $index->field_names()),
2858
-                        http_build_query($uniqueness_where_params)
2859
-                    ),
2860
-                    __FILE__,
2861
-                    __FUNCTION__,
2862
-                    __LINE__
2863
-                );
2864
-                return false;
2865
-            }
2866
-        }
2867
-        return true;
2868
-    }
2869
-
2870
-
2871
-
2872
-    /**
2873
-     * Checks the database for an item that conflicts (ie, if this item were
2874
-     * saved to the DB would break some uniqueness requirement, like a primary key
2875
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2876
-     * can be either an EE_Base_Class or an array of fields n values
2877
-     *
2878
-     * @param EE_Base_Class|array $obj_or_fields_array
2879
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2880
-     *                                                 when looking for conflicts
2881
-     *                                                 (ie, if false, we ignore the model object's primary key
2882
-     *                                                 when finding "conflicts". If true, it's also considered).
2883
-     *                                                 Only works for INT primary key,
2884
-     *                                                 STRING primary keys cannot be ignored
2885
-     * @throws EE_Error
2886
-     * @return EE_Base_Class|array
2887
-     */
2888
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2889
-    {
2890
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2891
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2892
-        } elseif (is_array($obj_or_fields_array)) {
2893
-            $fields_n_values = $obj_or_fields_array;
2894
-        } else {
2895
-            throw new EE_Error(
2896
-                sprintf(
2897
-                    __(
2898
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2899
-                        "event_espresso"
2900
-                    ),
2901
-                    get_class($this),
2902
-                    $obj_or_fields_array
2903
-                )
2904
-            );
2905
-        }
2906
-        $query_params = array();
2907
-        if (
2908
-            $this->has_primary_key_field()
2909
-            && ($include_primary_key
2910
-                || $this->get_primary_key_field()
2911
-                   instanceof
2912
-                   EE_Primary_Key_String_Field)
2913
-            && isset($fields_n_values[ $this->primary_key_name() ])
2914
-        ) {
2915
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2916
-        }
2917
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2920
-        }
2921
-        // if there is nothing to base this search on, then we shouldn't find anything
2922
-        if (empty($query_params)) {
2923
-            return array();
2924
-        }
2925
-        return $this->get_one($query_params);
2926
-    }
2927
-
2928
-
2929
-
2930
-    /**
2931
-     * Like count, but is optimized and returns a boolean instead of an int
2932
-     *
2933
-     * @param array $query_params
2934
-     * @return boolean
2935
-     * @throws EE_Error
2936
-     */
2937
-    public function exists($query_params)
2938
-    {
2939
-        $query_params['limit'] = 1;
2940
-        return $this->count($query_params) > 0;
2941
-    }
2942
-
2943
-
2944
-
2945
-    /**
2946
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2947
-     *
2948
-     * @param int|string $id
2949
-     * @return boolean
2950
-     * @throws EE_Error
2951
-     */
2952
-    public function exists_by_ID($id)
2953
-    {
2954
-        return $this->exists(
2955
-            array(
2956
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2957
-                array(
2958
-                    $this->primary_key_name() => $id,
2959
-                ),
2960
-            )
2961
-        );
2962
-    }
2963
-
2964
-
2965
-
2966
-    /**
2967
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2968
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2969
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2970
-     * on the main table)
2971
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2972
-     * cases where we want to call it directly rather than via insert().
2973
-     *
2974
-     * @access   protected
2975
-     * @param EE_Table_Base $table
2976
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2977
-     *                                       float
2978
-     * @param int           $new_id          for now we assume only int keys
2979
-     * @throws EE_Error
2980
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2981
-     * @return int ID of new row inserted, or FALSE on failure
2982
-     */
2983
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2984
-    {
2985
-        global $wpdb;
2986
-        $insertion_col_n_values = array();
2987
-        $format_for_insertion = array();
2988
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2989
-        foreach ($fields_on_table as $field_name => $field_obj) {
2990
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2991
-            if ($field_obj->is_auto_increment()) {
2992
-                continue;
2993
-            }
2994
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2996
-            if ($prepared_value !== null) {
2997
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2998
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999
-            }
3000
-        }
3001
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3002
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3003
-            // so add the fk to the main table as a column
3004
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3006
-        }
3007
-        // insert the new entry
3008
-        $result = $this->_do_wpdb_query(
3009
-            'insert',
3010
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3011
-        );
3012
-        if ($result === false) {
3013
-            return false;
3014
-        }
3015
-        // ok, now what do we return for the ID of the newly-inserted thing?
3016
-        if ($this->has_primary_key_field()) {
3017
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3018
-                return $wpdb->insert_id;
3019
-            }
3020
-            // it's not an auto-increment primary key, so
3021
-            // it must have been supplied
3022
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3023
-        }
3024
-        // we can't return a  primary key because there is none. instead return
3025
-        // a unique string indicating this model
3026
-        return $this->get_index_primary_key_string($fields_n_values);
3027
-    }
3028
-
3029
-
3030
-
3031
-    /**
3032
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3033
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3034
-     * and there is no default, we pass it along. WPDB will take care of it)
3035
-     *
3036
-     * @param EE_Model_Field_Base $field_obj
3037
-     * @param array               $fields_n_values
3038
-     * @return mixed string|int|float depending on what the table column will be expecting
3039
-     * @throws EE_Error
3040
-     */
3041
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3042
-    {
3043
-        // if this field doesn't allow nullable, don't allow it
3044
-        if (
3045
-            ! $field_obj->is_nullable()
3046
-            && (
3047
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3048
-                || $fields_n_values[ $field_obj->get_name() ] === null
3049
-            )
3050
-        ) {
3051
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3052
-        }
3053
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
-            ? $fields_n_values[ $field_obj->get_name() ]
3055
-            : null;
3056
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057
-    }
3058
-
3059
-
3060
-
3061
-    /**
3062
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3063
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3064
-     * the field's prepare_for_set() method.
3065
-     *
3066
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3067
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3068
-     *                                   top of file)
3069
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3070
-     *                                   $value is a custom selection
3071
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3072
-     */
3073
-    private function _prepare_value_for_use_in_db($value, $field)
3074
-    {
3075
-        if ($field && $field instanceof EE_Model_Field_Base) {
3076
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3077
-            switch ($this->_values_already_prepared_by_model_object) {
3078
-                /** @noinspection PhpMissingBreakStatementInspection */
3079
-                case self::not_prepared_by_model_object:
3080
-                    $value = $field->prepare_for_set($value);
3081
-                // purposefully left out "return"
3082
-                case self::prepared_by_model_object:
3083
-                    /** @noinspection SuspiciousAssignmentsInspection */
3084
-                    $value = $field->prepare_for_use_in_db($value);
3085
-                case self::prepared_for_use_in_db:
3086
-                    // leave the value alone
3087
-            }
3088
-            return $value;
3089
-            // phpcs:enable
3090
-        }
3091
-        return $value;
3092
-    }
3093
-
3094
-
3095
-
3096
-    /**
3097
-     * Returns the main table on this model
3098
-     *
3099
-     * @return EE_Primary_Table
3100
-     * @throws EE_Error
3101
-     */
3102
-    protected function _get_main_table()
3103
-    {
3104
-        foreach ($this->_tables as $table) {
3105
-            if ($table instanceof EE_Primary_Table) {
3106
-                return $table;
3107
-            }
3108
-        }
3109
-        throw new EE_Error(sprintf(__(
3110
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3111
-            'event_espresso'
3112
-        ), get_class($this)));
3113
-    }
3114
-
3115
-
3116
-
3117
-    /**
3118
-     * table
3119
-     * returns EE_Primary_Table table name
3120
-     *
3121
-     * @return string
3122
-     * @throws EE_Error
3123
-     */
3124
-    public function table()
3125
-    {
3126
-        return $this->_get_main_table()->get_table_name();
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * table
3133
-     * returns first EE_Secondary_Table table name
3134
-     *
3135
-     * @return string
3136
-     */
3137
-    public function second_table()
3138
-    {
3139
-        // grab second table from tables array
3140
-        $second_table = end($this->_tables);
3141
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * get_table_obj_by_alias
3148
-     * returns table name given it's alias
3149
-     *
3150
-     * @param string $table_alias
3151
-     * @return EE_Primary_Table | EE_Secondary_Table
3152
-     */
3153
-    public function get_table_obj_by_alias($table_alias = '')
3154
-    {
3155
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
-     *
3163
-     * @return EE_Secondary_Table[]
3164
-     */
3165
-    protected function _get_other_tables()
3166
-    {
3167
-        $other_tables = array();
3168
-        foreach ($this->_tables as $table_alias => $table) {
3169
-            if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[ $table_alias ] = $table;
3171
-            }
3172
-        }
3173
-        return $other_tables;
3174
-    }
3175
-
3176
-
3177
-
3178
-    /**
3179
-     * Finds all the fields that correspond to the given table
3180
-     *
3181
-     * @param string $table_alias , array key in EEM_Base::_tables
3182
-     * @return EE_Model_Field_Base[]
3183
-     */
3184
-    public function _get_fields_for_table($table_alias)
3185
-    {
3186
-        return $this->_fields[ $table_alias ];
3187
-    }
3188
-
3189
-
3190
-
3191
-    /**
3192
-     * Recurses through all the where parameters, and finds all the related models we'll need
3193
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
-     * related Registration, Transaction, and Payment models.
3197
-     *
3198
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     * @throws EE_Error
3201
-     */
3202
-    public function _extract_related_models_from_query($query_params)
3203
-    {
3204
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
-        if (array_key_exists(0, $query_params)) {
3206
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
-        }
3208
-        if (array_key_exists('group_by', $query_params)) {
3209
-            if (is_array($query_params['group_by'])) {
3210
-                $this->_extract_related_models_from_sub_params_array_values(
3211
-                    $query_params['group_by'],
3212
-                    $query_info_carrier,
3213
-                    'group_by'
3214
-                );
3215
-            } elseif (! empty($query_params['group_by'])) {
3216
-                $this->_extract_related_model_info_from_query_param(
3217
-                    $query_params['group_by'],
3218
-                    $query_info_carrier,
3219
-                    'group_by'
3220
-                );
3221
-            }
3222
-        }
3223
-        if (array_key_exists('having', $query_params)) {
3224
-            $this->_extract_related_models_from_sub_params_array_keys(
3225
-                $query_params[0],
3226
-                $query_info_carrier,
3227
-                'having'
3228
-            );
3229
-        }
3230
-        if (array_key_exists('order_by', $query_params)) {
3231
-            if (is_array($query_params['order_by'])) {
3232
-                $this->_extract_related_models_from_sub_params_array_keys(
3233
-                    $query_params['order_by'],
3234
-                    $query_info_carrier,
3235
-                    'order_by'
3236
-                );
3237
-            } elseif (! empty($query_params['order_by'])) {
3238
-                $this->_extract_related_model_info_from_query_param(
3239
-                    $query_params['order_by'],
3240
-                    $query_info_carrier,
3241
-                    'order_by'
3242
-                );
3243
-            }
3244
-        }
3245
-        if (array_key_exists('force_join', $query_params)) {
3246
-            $this->_extract_related_models_from_sub_params_array_values(
3247
-                $query_params['force_join'],
3248
-                $query_info_carrier,
3249
-                'force_join'
3250
-            );
3251
-        }
3252
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
-        return $query_info_carrier;
3254
-    }
3255
-
3256
-
3257
-
3258
-    /**
3259
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
-     *
3261
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3262
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3264
-     * @throws EE_Error
3265
-     * @return \EE_Model_Query_Info_Carrier
3266
-     */
3267
-    private function _extract_related_models_from_sub_params_array_keys(
3268
-        $sub_query_params,
3269
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
-        $query_param_type
3271
-    ) {
3272
-        if (! empty($sub_query_params)) {
3273
-            $sub_query_params = (array) $sub_query_params;
3274
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
-                $this->_extract_related_model_info_from_query_param(
3277
-                    $param,
3278
-                    $model_query_info_carrier,
3279
-                    $query_param_type
3280
-                );
3281
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3282
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3283
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3284
-                // of array('Registration.TXN_ID'=>23)
3285
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
-                    if (! is_array($possibly_array_of_params)) {
3288
-                        throw new EE_Error(sprintf(
3289
-                            __(
3290
-                                "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'))",
3291
-                                "event_espresso"
3292
-                            ),
3293
-                            $param,
3294
-                            $possibly_array_of_params
3295
-                        ));
3296
-                    }
3297
-                    $this->_extract_related_models_from_sub_params_array_keys(
3298
-                        $possibly_array_of_params,
3299
-                        $model_query_info_carrier,
3300
-                        $query_param_type
3301
-                    );
3302
-                } elseif (
3303
-                    $query_param_type === 0 // ie WHERE
3304
-                          && is_array($possibly_array_of_params)
3305
-                          && isset($possibly_array_of_params[2])
3306
-                          && $possibly_array_of_params[2] == true
3307
-                ) {
3308
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3310
-                    // from which we should extract query parameters!
3311
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312
-                        throw new EE_Error(sprintf(__(
3313
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314
-                            "event_espresso"
3315
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3316
-                    }
3317
-                    $this->_extract_related_model_info_from_query_param(
3318
-                        $possibly_array_of_params[1],
3319
-                        $model_query_info_carrier,
3320
-                        $query_param_type
3321
-                    );
3322
-                }
3323
-            }
3324
-        }
3325
-        return $model_query_info_carrier;
3326
-    }
3327
-
3328
-
3329
-
3330
-    /**
3331
-     * For extracting related models from forced_joins, where the array values contain the info about what
3332
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3333
-     *
3334
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3335
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3336
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3337
-     * @throws EE_Error
3338
-     * @return \EE_Model_Query_Info_Carrier
3339
-     */
3340
-    private function _extract_related_models_from_sub_params_array_values(
3341
-        $sub_query_params,
3342
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343
-        $query_param_type
3344
-    ) {
3345
-        if (! empty($sub_query_params)) {
3346
-            if (! is_array($sub_query_params)) {
3347
-                throw new EE_Error(sprintf(
3348
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349
-                    $sub_query_params
3350
-                ));
3351
-            }
3352
-            foreach ($sub_query_params as $param) {
3353
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3354
-                $this->_extract_related_model_info_from_query_param(
3355
-                    $param,
3356
-                    $model_query_info_carrier,
3357
-                    $query_param_type
3358
-                );
3359
-            }
3360
-        }
3361
-        return $model_query_info_carrier;
3362
-    }
3363
-
3364
-
3365
-    /**
3366
-     * Extract all the query parts from  model query params
3367
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3368
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3369
-     * but use them in a different order. Eg, we need to know what models we are querying
3370
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3371
-     * other models before we can finalize the where clause SQL.
3372
-     *
3373
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3374
-     * @throws EE_Error
3375
-     * @return EE_Model_Query_Info_Carrier
3376
-     * @throws ModelConfigurationException
3377
-     */
3378
-    public function _create_model_query_info_carrier($query_params)
3379
-    {
3380
-        if (! is_array($query_params)) {
3381
-            EE_Error::doing_it_wrong(
3382
-                'EEM_Base::_create_model_query_info_carrier',
3383
-                sprintf(
3384
-                    __(
3385
-                        '$query_params should be an array, you passed a variable of type %s',
3386
-                        'event_espresso'
3387
-                    ),
3388
-                    gettype($query_params)
3389
-                ),
3390
-                '4.6.0'
3391
-            );
3392
-            $query_params = array();
3393
-        }
3394
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3395
-        // first check if we should alter the query to account for caps or not
3396
-        // because the caps might require us to do extra joins
3397
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3398
-            $query_params[0] = array_replace_recursive(
3399
-                $query_params[0],
3400
-                $this->caps_where_conditions(
3401
-                    $query_params['caps']
3402
-                )
3403
-            );
3404
-        }
3405
-
3406
-        // check if we should alter the query to remove data related to protected
3407
-        // custom post types
3408
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3409
-            $where_param_key_for_password = $this->modelChainAndPassword();
3410
-            // only include if related to a cpt where no password has been set
3411
-            $query_params[0]['OR*nopassword'] = array(
3412
-                $where_param_key_for_password => '',
3413
-                $where_param_key_for_password . '*' => array('IS_NULL')
3414
-            );
3415
-        }
3416
-        $query_object = $this->_extract_related_models_from_query($query_params);
3417
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3418
-        foreach ($query_params[0] as $key => $value) {
3419
-            if (is_int($key)) {
3420
-                throw new EE_Error(
3421
-                    sprintf(
3422
-                        __(
3423
-                            "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.",
3424
-                            "event_espresso"
3425
-                        ),
3426
-                        $key,
3427
-                        var_export($value, true),
3428
-                        var_export($query_params, true),
3429
-                        get_class($this)
3430
-                    )
3431
-                );
3432
-            }
3433
-        }
3434
-        if (
3435
-            array_key_exists('default_where_conditions', $query_params)
3436
-            && ! empty($query_params['default_where_conditions'])
3437
-        ) {
3438
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3439
-        } else {
3440
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3441
-        }
3442
-        $query_params[0] = array_merge(
3443
-            $this->_get_default_where_conditions_for_models_in_query(
3444
-                $query_object,
3445
-                $use_default_where_conditions,
3446
-                $query_params[0]
3447
-            ),
3448
-            $query_params[0]
3449
-        );
3450
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3451
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3452
-        // So we need to setup a subquery and use that for the main join.
3453
-        // Note for now this only works on the primary table for the model.
3454
-        // So for instance, you could set the limit array like this:
3455
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3456
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3457
-            $query_object->set_main_model_join_sql(
3458
-                $this->_construct_limit_join_select(
3459
-                    $query_params['on_join_limit'][0],
3460
-                    $query_params['on_join_limit'][1]
3461
-                )
3462
-            );
3463
-        }
3464
-        // set limit
3465
-        if (array_key_exists('limit', $query_params)) {
3466
-            if (is_array($query_params['limit'])) {
3467
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468
-                    $e = sprintf(
3469
-                        __(
3470
-                            "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)",
3471
-                            "event_espresso"
3472
-                        ),
3473
-                        http_build_query($query_params['limit'])
3474
-                    );
3475
-                    throw new EE_Error($e . "|" . $e);
3476
-                }
3477
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
-            } elseif (! empty($query_params['limit'])) {
3480
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3481
-            }
3482
-        }
3483
-        // set order by
3484
-        if (array_key_exists('order_by', $query_params)) {
3485
-            if (is_array($query_params['order_by'])) {
3486
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3487
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3488
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3489
-                if (array_key_exists('order', $query_params)) {
3490
-                    throw new EE_Error(
3491
-                        sprintf(
3492
-                            __(
3493
-                                "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 ",
3494
-                                "event_espresso"
3495
-                            ),
3496
-                            get_class($this),
3497
-                            implode(", ", array_keys($query_params['order_by'])),
3498
-                            implode(", ", $query_params['order_by']),
3499
-                            $query_params['order']
3500
-                        )
3501
-                    );
3502
-                }
3503
-                $this->_extract_related_models_from_sub_params_array_keys(
3504
-                    $query_params['order_by'],
3505
-                    $query_object,
3506
-                    'order_by'
3507
-                );
3508
-                // assume it's an array of fields to order by
3509
-                $order_array = array();
3510
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511
-                    $order = $this->_extract_order($order);
3512
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3513
-                }
3514
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
-            } elseif (! empty($query_params['order_by'])) {
3516
-                $this->_extract_related_model_info_from_query_param(
3517
-                    $query_params['order_by'],
3518
-                    $query_object,
3519
-                    'order',
3520
-                    $query_params['order_by']
3521
-                );
3522
-                $order = isset($query_params['order'])
3523
-                    ? $this->_extract_order($query_params['order'])
3524
-                    : 'DESC';
3525
-                $query_object->set_order_by_sql(
3526
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3527
-                );
3528
-            }
3529
-        }
3530
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3531
-        if (
3532
-            ! array_key_exists('order_by', $query_params)
3533
-            && array_key_exists('order', $query_params)
3534
-            && ! empty($query_params['order'])
3535
-        ) {
3536
-            $pk_field = $this->get_primary_key_field();
3537
-            $order = $this->_extract_order($query_params['order']);
3538
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3539
-        }
3540
-        // set group by
3541
-        if (array_key_exists('group_by', $query_params)) {
3542
-            if (is_array($query_params['group_by'])) {
3543
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3544
-                $group_by_array = array();
3545
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547
-                }
3548
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
-            } elseif (! empty($query_params['group_by'])) {
3550
-                $query_object->set_group_by_sql(
3551
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3552
-                );
3553
-            }
3554
-        }
3555
-        // set having
3556
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3557
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3558
-        }
3559
-        // now, just verify they didn't pass anything wack
3560
-        foreach ($query_params as $query_key => $query_value) {
3561
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3562
-                throw new EE_Error(
3563
-                    sprintf(
3564
-                        __(
3565
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3566
-                            'event_espresso'
3567
-                        ),
3568
-                        $query_key,
3569
-                        get_class($this),
3570
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3571
-                        implode(',', $this->_allowed_query_params)
3572
-                    )
3573
-                );
3574
-            }
3575
-        }
3576
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3577
-        if (empty($main_model_join_sql)) {
3578
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3579
-        }
3580
-        return $query_object;
3581
-    }
3582
-
3583
-
3584
-
3585
-    /**
3586
-     * Gets the where conditions that should be imposed on the query based on the
3587
-     * context (eg reading frontend, backend, edit or delete).
3588
-     *
3589
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3590
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3591
-     * @throws EE_Error
3592
-     */
3593
-    public function caps_where_conditions($context = self::caps_read)
3594
-    {
3595
-        EEM_Base::verify_is_valid_cap_context($context);
3596
-        $cap_where_conditions = array();
3597
-        $cap_restrictions = $this->caps_missing($context);
3598
-        /**
3599
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3600
-         */
3601
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3602
-            $cap_where_conditions = array_replace_recursive(
3603
-                $cap_where_conditions,
3604
-                $restriction_if_no_cap->get_default_where_conditions()
3605
-            );
3606
-        }
3607
-        return apply_filters(
3608
-            'FHEE__EEM_Base__caps_where_conditions__return',
3609
-            $cap_where_conditions,
3610
-            $this,
3611
-            $context,
3612
-            $cap_restrictions
3613
-        );
3614
-    }
3615
-
3616
-
3617
-
3618
-    /**
3619
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3620
-     * otherwise throws an exception
3621
-     *
3622
-     * @param string $should_be_order_string
3623
-     * @return string either ASC, asc, DESC or desc
3624
-     * @throws EE_Error
3625
-     */
3626
-    private function _extract_order($should_be_order_string)
3627
-    {
3628
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3629
-            return $should_be_order_string;
3630
-        }
3631
-        throw new EE_Error(
3632
-            sprintf(
3633
-                __(
3634
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3635
-                    "event_espresso"
3636
-                ),
3637
-                get_class($this),
3638
-                $should_be_order_string
3639
-            )
3640
-        );
3641
-    }
3642
-
3643
-
3644
-
3645
-    /**
3646
-     * Looks at all the models which are included in this query, and asks each
3647
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3648
-     * so they can be merged
3649
-     *
3650
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3651
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3652
-     *                                                                  'none' means NO default where conditions will
3653
-     *                                                                  be used AT ALL during this query.
3654
-     *                                                                  'other_models_only' means default where
3655
-     *                                                                  conditions from other models will be used, but
3656
-     *                                                                  not for this primary model. 'all', the default,
3657
-     *                                                                  means default where conditions will apply as
3658
-     *                                                                  normal
3659
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
-     * @throws EE_Error
3661
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3662
-     */
3663
-    private function _get_default_where_conditions_for_models_in_query(
3664
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3665
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3666
-        $where_query_params = array()
3667
-    ) {
3668
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670
-            throw new EE_Error(sprintf(
3671
-                __(
3672
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3673
-                    "event_espresso"
3674
-                ),
3675
-                $use_default_where_conditions,
3676
-                implode(", ", $allowed_used_default_where_conditions_values)
3677
-            ));
3678
-        }
3679
-        $universal_query_params = array();
3680
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_default_where_conditions();
3682
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3683
-            $universal_query_params = $this->_get_minimum_where_conditions();
3684
-        }
3685
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3686
-            $related_model = $this->get_related_model_obj($model_name);
3687
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3689
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3690
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3691
-            } else {
3692
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3693
-                continue;
3694
-            }
3695
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3696
-                $related_model_universal_where_params,
3697
-                $where_query_params,
3698
-                $related_model,
3699
-                $model_relation_path
3700
-            );
3701
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3702
-                $universal_query_params,
3703
-                $overrides
3704
-            );
3705
-        }
3706
-        return $universal_query_params;
3707
-    }
3708
-
3709
-
3710
-
3711
-    /**
3712
-     * Determines whether or not we should use default where conditions for the model in question
3713
-     * (this model, or other related models).
3714
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3715
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3716
-     * We should use default where conditions on related models when they requested to use default where conditions
3717
-     * on all models, or specifically just on other related models
3718
-     * @param      $default_where_conditions_value
3719
-     * @param bool $for_this_model false means this is for OTHER related models
3720
-     * @return bool
3721
-     */
3722
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3723
-    {
3724
-        return (
3725
-                   $for_this_model
3726
-                   && in_array(
3727
-                       $default_where_conditions_value,
3728
-                       array(
3729
-                           EEM_Base::default_where_conditions_all,
3730
-                           EEM_Base::default_where_conditions_this_only,
3731
-                           EEM_Base::default_where_conditions_minimum_others,
3732
-                       ),
3733
-                       true
3734
-                   )
3735
-               )
3736
-               || (
3737
-                   ! $for_this_model
3738
-                   && in_array(
3739
-                       $default_where_conditions_value,
3740
-                       array(
3741
-                           EEM_Base::default_where_conditions_all,
3742
-                           EEM_Base::default_where_conditions_others_only,
3743
-                       ),
3744
-                       true
3745
-                   )
3746
-               );
3747
-    }
3748
-
3749
-    /**
3750
-     * Determines whether or not we should use default minimum conditions for the model in question
3751
-     * (this model, or other related models).
3752
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3753
-     * where conditions.
3754
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3755
-     * on this model or others
3756
-     * @param      $default_where_conditions_value
3757
-     * @param bool $for_this_model false means this is for OTHER related models
3758
-     * @return bool
3759
-     */
3760
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3761
-    {
3762
-        return (
3763
-                   $for_this_model
3764
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3765
-               )
3766
-               || (
3767
-                   ! $for_this_model
3768
-                   && in_array(
3769
-                       $default_where_conditions_value,
3770
-                       array(
3771
-                           EEM_Base::default_where_conditions_minimum_others,
3772
-                           EEM_Base::default_where_conditions_minimum_all,
3773
-                       ),
3774
-                       true
3775
-                   )
3776
-               );
3777
-    }
3778
-
3779
-
3780
-    /**
3781
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3782
-     * then we also add a special where condition which allows for that model's primary key
3783
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3784
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3785
-     *
3786
-     * @param array    $default_where_conditions
3787
-     * @param array    $provided_where_conditions
3788
-     * @param EEM_Base $model
3789
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3790
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3791
-     * @throws EE_Error
3792
-     */
3793
-    private function _override_defaults_or_make_null_friendly(
3794
-        $default_where_conditions,
3795
-        $provided_where_conditions,
3796
-        $model,
3797
-        $model_relation_path
3798
-    ) {
3799
-        $null_friendly_where_conditions = array();
3800
-        $none_overridden = true;
3801
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3802
-        foreach ($default_where_conditions as $key => $val) {
3803
-            if (isset($provided_where_conditions[ $key ])) {
3804
-                $none_overridden = false;
3805
-            } else {
3806
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3807
-            }
3808
-        }
3809
-        if ($none_overridden && $default_where_conditions) {
3810
-            if ($model->has_primary_key_field()) {
3811
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3812
-                                                                                . "."
3813
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3814
-            }/*else{
40
+	/**
41
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
44
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
+	 *
46
+	 * @var boolean
47
+	 */
48
+	private $_values_already_prepared_by_model_object = 0;
49
+
50
+	/**
51
+	 * when $_values_already_prepared_by_model_object equals this, we assume
52
+	 * the data is just like form input that needs to have the model fields'
53
+	 * prepare_for_set and prepare_for_use_in_db called on it
54
+	 */
55
+	const not_prepared_by_model_object = 0;
56
+
57
+	/**
58
+	 * when $_values_already_prepared_by_model_object equals this, we
59
+	 * assume this value is coming from a model object and doesn't need to have
60
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
61
+	 */
62
+	const prepared_by_model_object = 1;
63
+
64
+	/**
65
+	 * when $_values_already_prepared_by_model_object equals this, we assume
66
+	 * the values are already to be used in the database (ie no processing is done
67
+	 * on them by the model's fields)
68
+	 */
69
+	const prepared_for_use_in_db = 2;
70
+
71
+
72
+	protected $singular_item = 'Item';
73
+
74
+	protected $plural_item   = 'Items';
75
+
76
+	/**
77
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
+	 */
79
+	protected $_tables;
80
+
81
+	/**
82
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
+	 *
86
+	 * @var \EE_Model_Field_Base[][] $_fields
87
+	 */
88
+	protected $_fields;
89
+
90
+	/**
91
+	 * array of different kinds of relations
92
+	 *
93
+	 * @var \EE_Model_Relation_Base[] $_model_relations
94
+	 */
95
+	protected $_model_relations;
96
+
97
+	/**
98
+	 * @var \EE_Index[] $_indexes
99
+	 */
100
+	protected $_indexes = array();
101
+
102
+	/**
103
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
104
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
+	 * by setting the same columns as used in these queries in the query yourself.
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_default_where_conditions_strategy;
110
+
111
+	/**
112
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
+	 * This is particularly useful when you want something between 'none' and 'default'
114
+	 *
115
+	 * @var EE_Default_Where_Conditions
116
+	 */
117
+	protected $_minimum_where_conditions_strategy;
118
+
119
+	/**
120
+	 * String describing how to find the "owner" of this model's objects.
121
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
+	 * But when there isn't, this indicates which related model, or transiently-related model,
123
+	 * has the foreign key to the wp_users table.
124
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
+	 * related to events, and events have a foreign key to wp_users.
126
+	 * On EEM_Transaction, this would be 'Transaction.Event'
127
+	 *
128
+	 * @var string
129
+	 */
130
+	protected $_model_chain_to_wp_user = '';
131
+
132
+	/**
133
+	 * String describing how to find the model with a password controlling access to this model. This property has the
134
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
+	 * This value is the path of models to follow to arrive at the model with the password field.
136
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
+	 * model with a password that should affect reading this on the front-end.
138
+	 * Eg this is an empty string for the Event model because it has a password.
139
+	 * This is null for the Registration model, because its event's password has no bearing on whether
140
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
+	 * should hide tickets for datetimes for events that have a password set.
143
+	 * @var string |null
144
+	 */
145
+	protected $model_chain_to_password = null;
146
+
147
+	/**
148
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
+	 * don't need it (particularly CPT models)
150
+	 *
151
+	 * @var bool
152
+	 */
153
+	protected $_ignore_where_strategy = false;
154
+
155
+	/**
156
+	 * String used in caps relating to this model. Eg, if the caps relating to this
157
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
+	 *
159
+	 * @var string. If null it hasn't been initialized yet. If false then we
160
+	 * have indicated capabilities don't apply to this
161
+	 */
162
+	protected $_caps_slug = null;
163
+
164
+	/**
165
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
+	 * and next-level keys are capability names, and each's value is a
167
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
169
+	 * and then each capability in the corresponding sub-array that they're missing
170
+	 * adds the where conditions onto the query.
171
+	 *
172
+	 * @var array
173
+	 */
174
+	protected $_cap_restrictions = array(
175
+		self::caps_read       => array(),
176
+		self::caps_read_admin => array(),
177
+		self::caps_edit       => array(),
178
+		self::caps_delete     => array(),
179
+	);
180
+
181
+	/**
182
+	 * Array defining which cap restriction generators to use to create default
183
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
184
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
+	 * automatically set this to false (not just null).
187
+	 *
188
+	 * @var EE_Restriction_Generator_Base[]
189
+	 */
190
+	protected $_cap_restriction_generators = array();
191
+
192
+	/**
193
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
+	 */
195
+	const caps_read       = 'read';
196
+
197
+	const caps_read_admin = 'read_admin';
198
+
199
+	const caps_edit       = 'edit';
200
+
201
+	const caps_delete     = 'delete';
202
+
203
+	/**
204
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
+	 * maps to 'read' because when looking for relevant permissions we're going to use
207
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
208
+	 *
209
+	 * @var array
210
+	 */
211
+	protected $_cap_contexts_to_cap_action_map = array(
212
+		self::caps_read       => 'read',
213
+		self::caps_read_admin => 'read',
214
+		self::caps_edit       => 'edit',
215
+		self::caps_delete     => 'delete',
216
+	);
217
+
218
+	/**
219
+	 * Timezone
220
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
+	 * EE_Datetime_Field data type will have access to it.
224
+	 *
225
+	 * @var string
226
+	 */
227
+	protected $_timezone;
228
+
229
+
230
+	/**
231
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
+	 * multisite.
233
+	 *
234
+	 * @var int
235
+	 */
236
+	protected static $_model_query_blog_id;
237
+
238
+	/**
239
+	 * A copy of _fields, except the array keys are the model names pointed to by
240
+	 * the field
241
+	 *
242
+	 * @var EE_Model_Field_Base[]
243
+	 */
244
+	private $_cache_foreign_key_to_fields = array();
245
+
246
+	/**
247
+	 * Cached list of all the fields on the model, indexed by their name
248
+	 *
249
+	 * @var EE_Model_Field_Base[]
250
+	 */
251
+	private $_cached_fields = null;
252
+
253
+	/**
254
+	 * Cached list of all the fields on the model, except those that are
255
+	 * marked as only pertinent to the database
256
+	 *
257
+	 * @var EE_Model_Field_Base[]
258
+	 */
259
+	private $_cached_fields_non_db_only = null;
260
+
261
+	/**
262
+	 * A cached reference to the primary key for quick lookup
263
+	 *
264
+	 * @var EE_Model_Field_Base
265
+	 */
266
+	private $_primary_key_field = null;
267
+
268
+	/**
269
+	 * Flag indicating whether this model has a primary key or not
270
+	 *
271
+	 * @var boolean
272
+	 */
273
+	protected $_has_primary_key_field = null;
274
+
275
+	/**
276
+	 * array in the format:  [ FK alias => full PK ]
277
+	 * where keys are local column name aliases for foreign keys
278
+	 * and values are the fully qualified column name for the primary key they represent
279
+	 *  ex:
280
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
281
+	 *
282
+	 * @var array $foreign_key_aliases
283
+	 */
284
+	protected $foreign_key_aliases = [];
285
+
286
+	/**
287
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
288
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
289
+	 * This should be true for models that deal with data that should exist independent of EE.
290
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
291
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
292
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
293
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
294
+	 * @var boolean
295
+	 */
296
+	protected $_wp_core_model = false;
297
+
298
+	/**
299
+	 * @var bool stores whether this model has a password field or not.
300
+	 * null until initialized by hasPasswordField()
301
+	 */
302
+	protected $has_password_field;
303
+
304
+	/**
305
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
306
+	 */
307
+	protected $password_field;
308
+
309
+	/**
310
+	 *    List of valid operators that can be used for querying.
311
+	 * The keys are all operators we'll accept, the values are the real SQL
312
+	 * operators used
313
+	 *
314
+	 * @var array
315
+	 */
316
+	protected $_valid_operators = array(
317
+		'='           => '=',
318
+		'<='          => '<=',
319
+		'<'           => '<',
320
+		'>='          => '>=',
321
+		'>'           => '>',
322
+		'!='          => '!=',
323
+		'LIKE'        => 'LIKE',
324
+		'like'        => 'LIKE',
325
+		'NOT_LIKE'    => 'NOT LIKE',
326
+		'not_like'    => 'NOT LIKE',
327
+		'NOT LIKE'    => 'NOT LIKE',
328
+		'not like'    => 'NOT LIKE',
329
+		'IN'          => 'IN',
330
+		'in'          => 'IN',
331
+		'NOT_IN'      => 'NOT IN',
332
+		'not_in'      => 'NOT IN',
333
+		'NOT IN'      => 'NOT IN',
334
+		'not in'      => 'NOT IN',
335
+		'between'     => 'BETWEEN',
336
+		'BETWEEN'     => 'BETWEEN',
337
+		'IS_NOT_NULL' => 'IS NOT NULL',
338
+		'is_not_null' => 'IS NOT NULL',
339
+		'IS NOT NULL' => 'IS NOT NULL',
340
+		'is not null' => 'IS NOT NULL',
341
+		'IS_NULL'     => 'IS NULL',
342
+		'is_null'     => 'IS NULL',
343
+		'IS NULL'     => 'IS NULL',
344
+		'is null'     => 'IS NULL',
345
+		'REGEXP'      => 'REGEXP',
346
+		'regexp'      => 'REGEXP',
347
+		'NOT_REGEXP'  => 'NOT REGEXP',
348
+		'not_regexp'  => 'NOT REGEXP',
349
+		'NOT REGEXP'  => 'NOT REGEXP',
350
+		'not regexp'  => 'NOT REGEXP',
351
+	);
352
+
353
+	/**
354
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
355
+	 *
356
+	 * @var array
357
+	 */
358
+	protected $_in_style_operators = array('IN', 'NOT IN');
359
+
360
+	/**
361
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
362
+	 * '12-31-2012'"
363
+	 *
364
+	 * @var array
365
+	 */
366
+	protected $_between_style_operators = array('BETWEEN');
367
+
368
+	/**
369
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
370
+	 * @var array
371
+	 */
372
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
373
+	/**
374
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
375
+	 * on a join table.
376
+	 *
377
+	 * @var array
378
+	 */
379
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
380
+
381
+	/**
382
+	 * Allowed values for $query_params['order'] for ordering in queries
383
+	 *
384
+	 * @var array
385
+	 */
386
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
387
+
388
+	/**
389
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
390
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
391
+	 *
392
+	 * @var array
393
+	 */
394
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
395
+
396
+	/**
397
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
398
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
399
+	 *
400
+	 * @var array
401
+	 */
402
+	private $_allowed_query_params = array(
403
+		0,
404
+		'limit',
405
+		'order_by',
406
+		'group_by',
407
+		'having',
408
+		'force_join',
409
+		'order',
410
+		'on_join_limit',
411
+		'default_where_conditions',
412
+		'caps',
413
+		'extra_selects',
414
+		'exclude_protected',
415
+	);
416
+
417
+	/**
418
+	 * All the data types that can be used in $wpdb->prepare statements.
419
+	 *
420
+	 * @var array
421
+	 */
422
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
423
+
424
+	/**
425
+	 * @var EE_Registry $EE
426
+	 */
427
+	protected $EE = null;
428
+
429
+
430
+	/**
431
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
432
+	 *
433
+	 * @var int
434
+	 */
435
+	protected $_show_next_x_db_queries = 0;
436
+
437
+	/**
438
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
439
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
440
+	 * WHERE, GROUP_BY, etc.
441
+	 *
442
+	 * @var CustomSelects
443
+	 */
444
+	protected $_custom_selections = array();
445
+
446
+	/**
447
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
448
+	 * caches every model object we've fetched from the DB on this request
449
+	 *
450
+	 * @var array
451
+	 */
452
+	protected $_entity_map;
453
+
454
+	/**
455
+	 * @var LoaderInterface
456
+	 */
457
+	private static $loader;
458
+
459
+
460
+	/**
461
+	 * constant used to show EEM_Base has not yet verified the db on this http request
462
+	 */
463
+	const db_verified_none = 0;
464
+
465
+	/**
466
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
467
+	 * but not the addons' dbs
468
+	 */
469
+	const db_verified_core = 1;
470
+
471
+	/**
472
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
473
+	 * the EE core db too)
474
+	 */
475
+	const db_verified_addons = 2;
476
+
477
+	/**
478
+	 * indicates whether an EEM_Base child has already re-verified the DB
479
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
480
+	 * looking like EEM_Base::db_verified_*
481
+	 *
482
+	 * @var int - 0 = none, 1 = core, 2 = addons
483
+	 */
484
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
485
+
486
+	/**
487
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
488
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
489
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
490
+	 */
491
+	const default_where_conditions_all = 'all';
492
+
493
+	/**
494
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
495
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
496
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
497
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
498
+	 *        models which share tables with other models, this can return data for the wrong model.
499
+	 */
500
+	const default_where_conditions_this_only = 'this_model_only';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
504
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
506
+	 */
507
+	const default_where_conditions_others_only = 'other_models_only';
508
+
509
+	/**
510
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
511
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
512
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
513
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
514
+	 *        (regardless of whether those events and venues are trashed)
515
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
516
+	 *        events.
517
+	 */
518
+	const default_where_conditions_minimum_all = 'minimum';
519
+
520
+	/**
521
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
522
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
523
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
524
+	 *        not)
525
+	 */
526
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
527
+
528
+	/**
529
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
530
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
531
+	 *        it's possible it will return table entries for other models. You should use
532
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
533
+	 */
534
+	const default_where_conditions_none = 'none';
535
+
536
+
537
+
538
+	/**
539
+	 * About all child constructors:
540
+	 * they should define the _tables, _fields and _model_relations arrays.
541
+	 * Should ALWAYS be called after child constructor.
542
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
543
+	 * finalizes constructing all the object's attributes.
544
+	 * Generally, rather than requiring a child to code
545
+	 * $this->_tables = array(
546
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
547
+	 *        ...);
548
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
549
+	 * each EE_Table has a function to set the table's alias after the constructor, using
550
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
551
+	 * do something similar.
552
+	 *
553
+	 * @param null $timezone
554
+	 * @throws EE_Error
555
+	 */
556
+	protected function __construct($timezone = null)
557
+	{
558
+		// check that the model has not been loaded too soon
559
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
560
+			throw new EE_Error(
561
+				sprintf(
562
+					__(
563
+						'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.',
564
+						'event_espresso'
565
+					),
566
+					get_class($this)
567
+				)
568
+			);
569
+		}
570
+		/**
571
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
572
+		 */
573
+		if (empty(EEM_Base::$_model_query_blog_id)) {
574
+			EEM_Base::set_model_query_blog_id();
575
+		}
576
+		/**
577
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
578
+		 * just use EE_Register_Model_Extension
579
+		 *
580
+		 * @var EE_Table_Base[] $_tables
581
+		 */
582
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
583
+		foreach ($this->_tables as $table_alias => $table_obj) {
584
+			/** @var $table_obj EE_Table_Base */
585
+			$table_obj->_construct_finalize_with_alias($table_alias);
586
+			if ($table_obj instanceof EE_Secondary_Table) {
587
+				/** @var $table_obj EE_Secondary_Table */
588
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
589
+			}
590
+		}
591
+		/**
592
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
593
+		 * EE_Register_Model_Extension
594
+		 *
595
+		 * @param EE_Model_Field_Base[] $_fields
596
+		 */
597
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
598
+		$this->_invalidate_field_caches();
599
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
600
+			if (! array_key_exists($table_alias, $this->_tables)) {
601
+				throw new EE_Error(sprintf(__(
602
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
603
+					'event_espresso'
604
+				), $table_alias, implode(",", $this->_fields)));
605
+			}
606
+			foreach ($fields_for_table as $field_name => $field_obj) {
607
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
608
+				// primary key field base has a slightly different _construct_finalize
609
+				/** @var $field_obj EE_Model_Field_Base */
610
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
611
+			}
612
+		}
613
+		// everything is related to Extra_Meta
614
+		if (get_class($this) !== 'EEM_Extra_Meta') {
615
+			// make extra meta related to everything, but don't block deleting things just
616
+			// because they have related extra meta info. For now just orphan those extra meta
617
+			// in the future we should automatically delete them
618
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
619
+		}
620
+		// and change logs
621
+		if (get_class($this) !== 'EEM_Change_Log') {
622
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
623
+		}
624
+		/**
625
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
626
+		 * EE_Register_Model_Extension
627
+		 *
628
+		 * @param EE_Model_Relation_Base[] $_model_relations
629
+		 */
630
+		$this->_model_relations = (array) apply_filters(
631
+			'FHEE__' . get_class($this) . '__construct__model_relations',
632
+			$this->_model_relations
633
+		);
634
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
635
+			/** @var $relation_obj EE_Model_Relation_Base */
636
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
637
+		}
638
+		foreach ($this->_indexes as $index_name => $index_obj) {
639
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
+		}
641
+		$this->set_timezone($timezone);
642
+		// finalize default where condition strategy, or set default
643
+		if (! $this->_default_where_conditions_strategy) {
644
+			// nothing was set during child constructor, so set default
645
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
+		}
647
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
648
+		if (! $this->_minimum_where_conditions_strategy) {
649
+			// nothing was set during child constructor, so set default
650
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
+		}
652
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
654
+		// to indicate to NOT set it, set it to the logical default
655
+		if ($this->_caps_slug === null) {
656
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
+		}
658
+		// initialize the standard cap restriction generators if none were specified by the child constructor
659
+		if (! empty($this->_cap_restriction_generators)) {
660
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
+						new EE_Restriction_Generator_Protected(),
665
+						$cap_context,
666
+						$this
667
+					);
668
+				}
669
+			}
670
+		}
671
+		// if there are cap restriction generators, use them to make the default cap restrictions
672
+		if (! empty($this->_cap_restriction_generators)) {
673
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
+				if (! $generator_object) {
675
+					continue;
676
+				}
677
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
+					throw new EE_Error(
679
+						sprintf(
680
+							__(
681
+								'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.',
682
+								'event_espresso'
683
+							),
684
+							$context,
685
+							$this->get_this_model_name()
686
+						)
687
+					);
688
+				}
689
+				$action = $this->cap_action_for_context($context);
690
+				if (! $generator_object->construction_finalized()) {
691
+					$generator_object->_construct_finalize($this, $action);
692
+				}
693
+			}
694
+		}
695
+		do_action('AHEE__' . get_class($this) . '__construct__end');
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * Used to set the $_model_query_blog_id static property.
702
+	 *
703
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
+	 *                      value for get_current_blog_id() will be used.
705
+	 */
706
+	public static function set_model_query_blog_id($blog_id = 0)
707
+	{
708
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * Returns whatever is set as the internal $model_query_blog_id.
715
+	 *
716
+	 * @return int
717
+	 */
718
+	public static function get_model_query_blog_id()
719
+	{
720
+		return EEM_Base::$_model_query_blog_id;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * This function is a singleton method used to instantiate the Espresso_model object
727
+	 *
728
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
+	 *                                (and any incoming timezone data that gets saved).
730
+	 *                                Note this just sends the timezone info to the date time model field objects.
731
+	 *                                Default is NULL
732
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
+	 * @return static (as in the concrete child class)
734
+	 * @throws EE_Error
735
+	 * @throws InvalidArgumentException
736
+	 * @throws InvalidDataTypeException
737
+	 * @throws InvalidInterfaceException
738
+	 */
739
+	public static function instance($timezone = null)
740
+	{
741
+		// check if instance of Espresso_model already exists
742
+		if (! static::$_instance instanceof static) {
743
+			// instantiate Espresso_model
744
+			static::$_instance = new static(
745
+				$timezone,
746
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
+			);
748
+		}
749
+		// we might have a timezone set, let set_timezone decide what to do with it
750
+		static::$_instance->set_timezone($timezone);
751
+		// Espresso_model object
752
+		return static::$_instance;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * resets the model and returns it
759
+	 *
760
+	 * @param null | string $timezone
761
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
+	 * all its properties reset; if it wasn't instantiated, returns null)
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 */
769
+	public static function reset($timezone = null)
770
+	{
771
+		if (static::$_instance instanceof EEM_Base) {
772
+			// let's try to NOT swap out the current instance for a new one
773
+			// because if someone has a reference to it, we can't remove their reference
774
+			// so it's best to keep using the same reference, but change the original object
775
+			// reset all its properties to their original values as defined in the class
776
+			$r = new ReflectionClass(get_class(static::$_instance));
777
+			$static_properties = $r->getStaticProperties();
778
+			foreach ($r->getDefaultProperties() as $property => $value) {
779
+				// don't set instance to null like it was originally,
780
+				// but it's static anyways, and we're ignoring static properties (for now at least)
781
+				if (! isset($static_properties[ $property ])) {
782
+					static::$_instance->{$property} = $value;
783
+				}
784
+			}
785
+			// and then directly call its constructor again, like we would if we were creating a new one
786
+			static::$_instance->__construct(
787
+				$timezone,
788
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
+			);
790
+			return self::instance();
791
+		}
792
+		return null;
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * @return LoaderInterface
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 */
803
+	protected static function getLoader(): LoaderInterface
804
+	{
805
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
806
+			EEM_Base::$loader = LoaderFactory::getLoader();
807
+		}
808
+		return EEM_Base::$loader;
809
+	}
810
+
811
+
812
+
813
+	/**
814
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
+	 *
816
+	 * @param  boolean $translated return localized strings or JUST the array.
817
+	 * @return array
818
+	 * @throws EE_Error
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 */
823
+	public function status_array($translated = false)
824
+	{
825
+		if (! array_key_exists('Status', $this->_model_relations)) {
826
+			return array();
827
+		}
828
+		$model_name = $this->get_this_model_name();
829
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
+		$status_array = array();
832
+		foreach ($stati as $status) {
833
+			$status_array[ $status->ID() ] = $status->get('STS_code');
834
+		}
835
+		return $translated
836
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
+			: $status_array;
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
+	 *
845
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
+	 *                             or if you have the development copy of EE you can view this at the path:
847
+	 *                             /docs/G--Model-System/model-query-params.md
848
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (
873
+			isset($query_params['limit'])
874
+			&& ! isset($query_params['group_by'])
875
+		) {
876
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
+		}
878
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Modifies the query parameters so we only get back model objects
885
+	 * that "belong" to the current user
886
+	 *
887
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
+	 */
890
+	public function alter_query_params_to_only_include_mine($query_params = array())
891
+	{
892
+		$wp_user_field_name = $this->wp_user_field_name();
893
+		if ($wp_user_field_name) {
894
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
+		}
896
+		return $query_params;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * Returns the name of the field's name that points to the WP_User table
903
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
+	 * foreign key to the WP_User table)
905
+	 *
906
+	 * @return string|boolean string on success, boolean false when there is no
907
+	 * foreign key to the WP_User table
908
+	 */
909
+	public function wp_user_field_name()
910
+	{
911
+		try {
912
+			if (! empty($this->_model_chain_to_wp_user)) {
913
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
+				$last_model_name = end($models_to_follow_to_wp_users);
915
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
+			} else {
918
+				$model_with_fk_to_wp_users = $this;
919
+				$model_chain_to_wp_user = '';
920
+			}
921
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
932
+	 * (or transiently-related model) has a foreign key to the wp_users table;
933
+	 * useful for finding if model objects of this type are 'owned' by the current user.
934
+	 * This is an empty string when the foreign key is on this model and when it isn't,
935
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
936
+	 * (or transiently-related model)
937
+	 *
938
+	 * @return string
939
+	 */
940
+	public function model_chain_to_wp_user()
941
+	{
942
+		return $this->_model_chain_to_wp_user;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
+	 * like how registrations don't have a foreign key to wp_users, but the
950
+	 * events they are for are), or is unrelated to wp users.
951
+	 * generally available
952
+	 *
953
+	 * @return boolean
954
+	 */
955
+	public function is_owned()
956
+	{
957
+		if ($this->model_chain_to_wp_user()) {
958
+			return true;
959
+		}
960
+		try {
961
+			$this->get_foreign_key_to('WP_User');
962
+			return true;
963
+		} catch (EE_Error $e) {
964
+			return false;
965
+		}
966
+	}
967
+
968
+
969
+	/**
970
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
+	 * the model)
973
+	 *
974
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
978
+	 *                                  override this and set the select to "*", or a specific column name, like
979
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
+	 *                                  the aliases used to refer to this selection, and values are to be
982
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 */
988
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
+	{
990
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
+		;
992
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
993
+		$select_expressions = $columns_to_select === null
994
+			? $this->_construct_default_select_sql($model_query_info)
995
+			: '';
996
+		if ($this->_custom_selections instanceof CustomSelects) {
997
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
+			$select_expressions .= $select_expressions
999
+				? ', ' . $custom_expressions
1000
+				: $custom_expressions;
1001
+		}
1002
+
1003
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
+	 * method of including extra select information.
1012
+	 *
1013
+	 * @param array             $query_params
1014
+	 * @param null|array|string $columns_to_select
1015
+	 * @return null|CustomSelects
1016
+	 * @throws InvalidArgumentException
1017
+	 */
1018
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
+	{
1020
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
+			return null;
1022
+		}
1023
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
+		return new CustomSelects($selects);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the model query params to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								'event_espresso'
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(', ', $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(', ', $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
+	 * If there is no primary key on this model, $id is treated as primary key string
1121
+	 *
1122
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1123
+	 * @return EE_Base_Class
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		$model_object = $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+		$className = $this->_get_class_name();
1138
+		if ($model_object instanceof $className) {
1139
+			// make sure valid objects get added to the entity map
1140
+			// so that the next call to this method doesn't trigger another trip to the db
1141
+			$this->add_to_entity_map($model_object);
1142
+		}
1143
+		return $model_object;
1144
+	}
1145
+
1146
+
1147
+
1148
+	/**
1149
+	 * Alters query parameters to only get items with this ID are returned.
1150
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
+	 * or could just be a simple primary key ID
1152
+	 *
1153
+	 * @param int   $id
1154
+	 * @param array $query_params
1155
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
+	{
1160
+		if (! isset($query_params[0])) {
1161
+			$query_params[0] = array();
1162
+		}
1163
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1164
+		if ($conditions_from_id === null) {
1165
+			$query_params[0][ $this->primary_key_name() ] = $id;
1166
+		} else {
1167
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1168
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
+		}
1170
+		return $query_params;
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
+	 * array. If no item is found, null is returned.
1178
+	 *
1179
+	 * @param array $query_params like EEM_Base's $query_params variable.
1180
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_one($query_params = array())
1184
+	{
1185
+		if (! is_array($query_params)) {
1186
+			EE_Error::doing_it_wrong(
1187
+				'EEM_Base::get_one',
1188
+				sprintf(
1189
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
+					gettype($query_params)
1191
+				),
1192
+				'4.6.0'
1193
+			);
1194
+			$query_params = array();
1195
+		}
1196
+		$query_params['limit'] = 1;
1197
+		$items = $this->get_all($query_params);
1198
+		if (empty($items)) {
1199
+			return null;
1200
+		}
1201
+		return array_shift($items);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the next x number of items in sequence from the given value as
1208
+	 * found in the database matching the given query conditions.
1209
+	 *
1210
+	 * @param mixed $current_field_value    Value used for the reference point.
1211
+	 * @param null  $field_to_order_by      What field is used for the
1212
+	 *                                      reference point.
1213
+	 * @param int   $limit                  How many to return.
1214
+	 * @param array $query_params           Extra conditions on the query.
1215
+	 * @param null  $columns_to_select      If left null, then an array of
1216
+	 *                                      EE_Base_Class objects is returned,
1217
+	 *                                      otherwise you can indicate just the
1218
+	 *                                      columns you want returned.
1219
+	 * @return EE_Base_Class[]|array
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function next_x(
1223
+		$current_field_value,
1224
+		$field_to_order_by = null,
1225
+		$limit = 1,
1226
+		$query_params = array(),
1227
+		$columns_to_select = null
1228
+	) {
1229
+		return $this->_get_consecutive(
1230
+			$current_field_value,
1231
+			'>',
1232
+			$field_to_order_by,
1233
+			$limit,
1234
+			$query_params,
1235
+			$columns_to_select
1236
+		);
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Returns the previous x number of items in sequence from the given value
1243
+	 * as found in the database matching the given query conditions.
1244
+	 *
1245
+	 * @param mixed $current_field_value    Value used for the reference point.
1246
+	 * @param null  $field_to_order_by      What field is used for the
1247
+	 *                                      reference point.
1248
+	 * @param int   $limit                  How many to return.
1249
+	 * @param array $query_params           Extra conditions on the query.
1250
+	 * @param null  $columns_to_select      If left null, then an array of
1251
+	 *                                      EE_Base_Class objects is returned,
1252
+	 *                                      otherwise you can indicate just the
1253
+	 *                                      columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function previous_x(
1258
+		$current_field_value,
1259
+		$field_to_order_by = null,
1260
+		$limit = 1,
1261
+		$query_params = array(),
1262
+		$columns_to_select = null
1263
+	) {
1264
+		return $this->_get_consecutive(
1265
+			$current_field_value,
1266
+			'<',
1267
+			$field_to_order_by,
1268
+			$limit,
1269
+			$query_params,
1270
+			$columns_to_select
1271
+		);
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * Returns the next item in sequence from the given value as found in the
1278
+	 * database matching the given query conditions.
1279
+	 *
1280
+	 * @param mixed $current_field_value    Value used for the reference point.
1281
+	 * @param null  $field_to_order_by      What field is used for the
1282
+	 *                                      reference point.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
+	 *                                      object is returned, otherwise you
1286
+	 *                                      can indicate just the columns you
1287
+	 *                                      want and a single array indexed by
1288
+	 *                                      the columns will be returned.
1289
+	 * @return EE_Base_Class|null|array()
1290
+	 * @throws EE_Error
1291
+	 */
1292
+	public function next(
1293
+		$current_field_value,
1294
+		$field_to_order_by = null,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		$results = $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			1,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the previous item in sequence from the given value as found in
1313
+	 * the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed $current_field_value    Value used for the reference point.
1316
+	 * @param null  $field_to_order_by      What field is used for the
1317
+	 *                                      reference point.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
+	 *                                      object is returned, otherwise you
1321
+	 *                                      can indicate just the columns you
1322
+	 *                                      want and a single array indexed by
1323
+	 *                                      the columns will be returned.
1324
+	 * @return EE_Base_Class|null|array()
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function previous(
1328
+		$current_field_value,
1329
+		$field_to_order_by = null,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		$results = $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			1,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+		return empty($results) ? null : reset($results);
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Returns the a consecutive number of items in sequence from the given
1348
+	 * value as found in the database matching the given query conditions.
1349
+	 *
1350
+	 * @param mixed  $current_field_value   Value used for the reference point.
1351
+	 * @param string $operand               What operand is used for the sequence.
1352
+	 * @param string $field_to_order_by     What field is used for the reference point.
1353
+	 * @param int    $limit                 How many to return.
1354
+	 * @param array  $query_params          Extra conditions on the query.
1355
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
+	 *                                      otherwise you can indicate just the columns you want returned.
1357
+	 * @return EE_Base_Class[]|array
1358
+	 * @throws EE_Error
1359
+	 */
1360
+	protected function _get_consecutive(
1361
+		$current_field_value,
1362
+		$operand = '>',
1363
+		$field_to_order_by = null,
1364
+		$limit = 1,
1365
+		$query_params = array(),
1366
+		$columns_to_select = null
1367
+	) {
1368
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
+		if (empty($field_to_order_by)) {
1370
+			if ($this->has_primary_key_field()) {
1371
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1372
+			} else {
1373
+				if (WP_DEBUG) {
1374
+					throw new EE_Error(__(
1375
+						'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).',
1376
+						'event_espresso'
1377
+					));
1378
+				}
1379
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1380
+				return array();
1381
+			}
1382
+		}
1383
+		if (! is_array($query_params)) {
1384
+			EE_Error::doing_it_wrong(
1385
+				'EEM_Base::_get_consecutive',
1386
+				sprintf(
1387
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
+					gettype($query_params)
1389
+				),
1390
+				'4.6.0'
1391
+			);
1392
+			$query_params = array();
1393
+		}
1394
+		// let's add the where query param for consecutive look up.
1395
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
+		$query_params['limit'] = $limit;
1397
+		// set direction
1398
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
+		$query_params['order_by'] = $operand === '>'
1400
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
+		if (empty($columns_to_select)) {
1404
+			return $this->get_all($query_params);
1405
+		}
1406
+		// getting just the fields
1407
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This sets the _timezone property after model object has been instantiated.
1414
+	 *
1415
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
+	 */
1417
+	public function set_timezone($timezone)
1418
+	{
1419
+		if ($timezone !== null) {
1420
+			$this->_timezone = $timezone;
1421
+		}
1422
+		// note we need to loop through relations and set the timezone on those objects as well.
1423
+		foreach ($this->_model_relations as $relation) {
1424
+			$relation->set_timezone($timezone);
1425
+		}
1426
+		// and finally we do the same for any datetime fields
1427
+		foreach ($this->_fields as $field) {
1428
+			if ($field instanceof EE_Datetime_Field) {
1429
+				$field->set_timezone($timezone);
1430
+			}
1431
+		}
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * This just returns whatever is set for the current timezone.
1438
+	 *
1439
+	 * @access public
1440
+	 * @return string
1441
+	 */
1442
+	public function get_timezone()
1443
+	{
1444
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
+		if (empty($this->_timezone)) {
1446
+			foreach ($this->_fields as $field) {
1447
+				if ($field instanceof EE_Datetime_Field) {
1448
+					$this->set_timezone($field->get_timezone());
1449
+					break;
1450
+				}
1451
+			}
1452
+		}
1453
+		// if timezone STILL empty then return the default timezone for the site.
1454
+		if (empty($this->_timezone)) {
1455
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
+		}
1457
+		return $this->_timezone;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This returns the date formats set for the given field name and also ensures that
1464
+	 * $this->_timezone property is set correctly.
1465
+	 *
1466
+	 * @since 4.6.x
1467
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1468
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
+	 * @return array formats in an array with the date format first, and the time format last.
1471
+	 */
1472
+	public function get_formats_for($field_name, $pretty = false)
1473
+	{
1474
+		$field_settings = $this->field_settings_for($field_name);
1475
+		// if not a valid EE_Datetime_Field then throw error
1476
+		if (! $field_settings instanceof EE_Datetime_Field) {
1477
+			throw new EE_Error(sprintf(__(
1478
+				'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.',
1479
+				'event_espresso'
1480
+			), $field_name));
1481
+		}
1482
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
+		// the field.
1484
+		$this->_timezone = $field_settings->get_timezone();
1485
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * This returns the current time in a format setup for a query on this model.
1492
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
+	 * it will return:
1494
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
+	 *  NOW
1496
+	 *  - or a unix timestamp (equivalent to time())
1497
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
+	 * @since 4.6.x
1501
+	 * @param string $field_name       The field the current time is needed for.
1502
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
+	 *                                 formatted string matching the set format for the field in the set timezone will
1504
+	 *                                 be returned.
1505
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
+	 *                                 exception is triggered.
1509
+	 */
1510
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
+	{
1512
+		$formats = $this->get_formats_for($field_name);
1513
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
+		if ($timestamp) {
1515
+			return $DateTime->format('U');
1516
+		}
1517
+		// not returning timestamp, so return formatted string in timezone.
1518
+		switch ($what) {
1519
+			case 'time':
1520
+				return $DateTime->format($formats[1]);
1521
+				break;
1522
+			case 'date':
1523
+				return $DateTime->format($formats[0]);
1524
+				break;
1525
+			default:
1526
+				return $DateTime->format(implode(' ', $formats));
1527
+				break;
1528
+		}
1529
+	}
1530
+
1531
+
1532
+
1533
+	/**
1534
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
+	 * for the model are.  Returns a DateTime object.
1536
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
+	 * ignored.
1539
+	 *
1540
+	 * @param string $field_name      The field being setup.
1541
+	 * @param string $timestring      The date time string being used.
1542
+	 * @param string $incoming_format The format for the time string.
1543
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
+	 *                                format is
1546
+	 *                                'U', this is ignored.
1547
+	 * @return DateTime
1548
+	 * @throws EE_Error
1549
+	 */
1550
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
+	{
1552
+		// just using this to ensure the timezone is set correctly internally
1553
+		$this->get_formats_for($field_name);
1554
+		// load EEH_DTT_Helper
1555
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
+	 *
1566
+	 * @return EE_Table_Base[]
1567
+	 */
1568
+	public function get_tables()
1569
+	{
1570
+		return $this->_tables;
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
+	 * model object with EVT_ID = 1
1582
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
+	 * are not specified)
1587
+	 *
1588
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1593
+	 *                                         ID=34, we'd use this method as follows:
1594
+	 *                                         EEM_Transaction::instance()->update(
1595
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
+	 *                                         array(array('TXN_ID'=>34)));
1597
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
+	 *                                         TRUE, it is assumed that you've already called
1604
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
+	 *                                         malicious javascript. However, if
1606
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
+	 *                                         and every other field, before insertion. We provide this parameter
1609
+	 *                                         because model objects perform their prepare_for_set function on all
1610
+	 *                                         their values, and so don't need to be called again (and in many cases,
1611
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
+	 *                                         prepare_for_set method...)
1613
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
+	 *                                         in this model's entity map according to $fields_n_values that match
1615
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1616
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1617
+	 *                                         could get out-of-sync with the database
1618
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
+	 *                                         bad)
1621
+	 * @throws EE_Error
1622
+	 */
1623
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
+	{
1625
+		if (! is_array($query_params)) {
1626
+			EE_Error::doing_it_wrong(
1627
+				'EEM_Base::update',
1628
+				sprintf(
1629
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
+					gettype($query_params)
1631
+				),
1632
+				'4.6.0'
1633
+			);
1634
+			$query_params = array();
1635
+		}
1636
+		/**
1637
+		 * Action called before a model update call has been made.
1638
+		 *
1639
+		 * @param EEM_Base $model
1640
+		 * @param array    $fields_n_values the updated fields and their new values
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
+		/**
1645
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1646
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1647
+		 *
1648
+		 * @param array    $fields_n_values fields and their new values
1649
+		 * @param EEM_Base $model           the model being queried
1650
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
+		 */
1652
+		$fields_n_values = (array) apply_filters(
1653
+			'FHEE__EEM_Base__update__fields_n_values',
1654
+			$fields_n_values,
1655
+			$this,
1656
+			$query_params
1657
+		);
1658
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
+		// to do that, for each table, verify that it's PK isn't null.
1660
+		$tables = $this->get_tables();
1661
+		// 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
1662
+		// NOTE: we should make this code more efficient by NOT querying twice
1663
+		// before the real update, but that needs to first go through ALPHA testing
1664
+		// as it's dangerous. says Mike August 8 2014
1665
+		// we want to make sure the default_where strategy is ignored
1666
+		$this->_ignore_where_strategy = true;
1667
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
+		foreach ($wpdb_select_results as $wpdb_result) {
1669
+			// type cast stdClass as array
1670
+			$wpdb_result = (array) $wpdb_result;
1671
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
+			if ($this->has_primary_key_field()) {
1673
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
+			} else {
1675
+				// 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)
1676
+				$main_table_pk_value = null;
1677
+			}
1678
+			// 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
1679
+			// 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
1680
+			if (count($tables) > 1) {
1681
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
+				// in that table, and so we'll want to insert one
1683
+				foreach ($tables as $table_obj) {
1684
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
+					// if there is no private key for this table on the results, it means there's no entry
1686
+					// in this table, right? so insert a row in the current table, using any fields available
1687
+					if (
1688
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
+						   && $wpdb_result[ $this_table_pk_column ])
1690
+					) {
1691
+						$success = $this->_insert_into_specific_table(
1692
+							$table_obj,
1693
+							$fields_n_values,
1694
+							$main_table_pk_value
1695
+						);
1696
+						// if we died here, report the error
1697
+						if (! $success) {
1698
+							return false;
1699
+						}
1700
+					}
1701
+				}
1702
+			}
1703
+			//              //and now check that if we have cached any models by that ID on the model, that
1704
+			//              //they also get updated properly
1705
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
+			//              if( $model_object ){
1707
+			//                  foreach( $fields_n_values as $field => $value ){
1708
+			//                      $model_object->set($field, $value);
1709
+			// let's make sure default_where strategy is followed now
1710
+			$this->_ignore_where_strategy = false;
1711
+		}
1712
+		// if we want to keep model objects in sync, AND
1713
+		// if this wasn't called from a model object (to update itself)
1714
+		// then we want to make sure we keep all the existing
1715
+		// model objects in sync with the db
1716
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
+			if ($this->has_primary_key_field()) {
1718
+				$model_objs_affected_ids = $this->get_col($query_params);
1719
+			} else {
1720
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
+				$model_objs_affected_ids = array();
1723
+				foreach ($models_affected_key_columns as $row) {
1724
+					$combined_index_key = $this->get_index_primary_key_string($row);
1725
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
+				}
1727
+			}
1728
+			if (! $model_objs_affected_ids) {
1729
+				// wait wait wait- if nothing was affected let's stop here
1730
+				return 0;
1731
+			}
1732
+			foreach ($model_objs_affected_ids as $id) {
1733
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
+				if ($model_obj_in_entity_map) {
1735
+					foreach ($fields_n_values as $field => $new_value) {
1736
+						$model_obj_in_entity_map->set($field, $new_value);
1737
+					}
1738
+				}
1739
+			}
1740
+			// if there is a primary key on this model, we can now do a slight optimization
1741
+			if ($this->has_primary_key_field()) {
1742
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
+				$query_params = array(
1744
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
+					'limit'                    => count($model_objs_affected_ids),
1746
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
+				);
1748
+			}
1749
+		}
1750
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
+		$SQL = "UPDATE "
1752
+			   . $model_query_info->get_full_join_sql()
1753
+			   . " SET "
1754
+			   . $this->_construct_update_sql($fields_n_values)
1755
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
+		/**
1758
+		 * Action called after a model update call has been made.
1759
+		 *
1760
+		 * @param EEM_Base $model
1761
+		 * @param array    $fields_n_values the updated fields and their new values
1762
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
+		 * @param int      $rows_affected
1764
+		 */
1765
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
+		return $rows_affected;// how many supposedly got updated
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
+	 * are teh values of the field specified (or by default the primary key field)
1774
+	 * that matched the query params. Note that you should pass the name of the
1775
+	 * model FIELD, not the database table's column name.
1776
+	 *
1777
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
+	 * @param string $field_to_select
1779
+	 * @return array just like $wpdb->get_col()
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function get_col($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		if ($field_to_select) {
1785
+			$field = $this->field_settings_for($field_to_select);
1786
+		} elseif ($this->has_primary_key_field()) {
1787
+			$field = $this->get_primary_key_field();
1788
+		} else {
1789
+			// no primary key, just grab the first column
1790
+			$field = reset($this->field_settings());
1791
+		}
1792
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
+		$select_expressions = $field->get_qualified_column();
1794
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
+		return $this->_do_wpdb_query('get_col', array($SQL));
1796
+	}
1797
+
1798
+
1799
+
1800
+	/**
1801
+	 * Returns a single column value for a single row from the database
1802
+	 *
1803
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
+	 * @param string $field_to_select @see EEM_Base::get_col()
1805
+	 * @return string
1806
+	 * @throws EE_Error
1807
+	 */
1808
+	public function get_var($query_params = array(), $field_to_select = null)
1809
+	{
1810
+		$query_params['limit'] = 1;
1811
+		$col = $this->get_col($query_params, $field_to_select);
1812
+		if (! empty($col)) {
1813
+			return reset($col);
1814
+		}
1815
+		return null;
1816
+	}
1817
+
1818
+
1819
+
1820
+	/**
1821
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
+	 * injection, but currently no further filtering is done
1824
+	 *
1825
+	 * @global      $wpdb
1826
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
+	 *                               be updated to in the DB
1828
+	 * @return string of SQL
1829
+	 * @throws EE_Error
1830
+	 */
1831
+	public function _construct_update_sql($fields_n_values)
1832
+	{
1833
+		/** @type WPDB $wpdb */
1834
+		global $wpdb;
1835
+		$cols_n_values = array();
1836
+		foreach ($fields_n_values as $field_name => $value) {
1837
+			$field_obj = $this->field_settings_for($field_name);
1838
+			// if the value is NULL, we want to assign the value to that.
1839
+			// wpdb->prepare doesn't really handle that properly
1840
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
+			$value_sql = $prepared_value === null ? 'NULL'
1842
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
+		}
1845
+		return implode(",", $cols_n_values);
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
+	 * Performs a HARD delete, meaning the database row should always be removed,
1853
+	 * not just have a flag field on it switched
1854
+	 * Wrapper for EEM_Base::delete_permanently()
1855
+	 *
1856
+	 * @param mixed $id
1857
+	 * @param boolean $allow_blocking
1858
+	 * @return int the number of rows deleted
1859
+	 * @throws EE_Error
1860
+	 */
1861
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
+	{
1863
+		return $this->delete_permanently(
1864
+			array(
1865
+				array($this->get_primary_key_field()->get_name() => $id),
1866
+				'limit' => 1,
1867
+			),
1868
+			$allow_blocking
1869
+		);
1870
+	}
1871
+
1872
+
1873
+
1874
+	/**
1875
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
+	 * Wrapper for EEM_Base::delete()
1877
+	 *
1878
+	 * @param mixed $id
1879
+	 * @param boolean $allow_blocking
1880
+	 * @return int the number of rows deleted
1881
+	 * @throws EE_Error
1882
+	 */
1883
+	public function delete_by_ID($id, $allow_blocking = true)
1884
+	{
1885
+		return $this->delete(
1886
+			array(
1887
+				array($this->get_primary_key_field()->get_name() => $id),
1888
+				'limit' => 1,
1889
+			),
1890
+			$allow_blocking
1891
+		);
1892
+	}
1893
+
1894
+
1895
+
1896
+	/**
1897
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1898
+	 * meaning if the model has a field that indicates its been "trashed" or
1899
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1900
+	 *
1901
+	 * @see EEM_Base::delete_permanently
1902
+	 * @param array   $query_params
1903
+	 * @param boolean $allow_blocking
1904
+	 * @return int how many rows got deleted
1905
+	 * @throws EE_Error
1906
+	 */
1907
+	public function delete($query_params, $allow_blocking = true)
1908
+	{
1909
+		return $this->delete_permanently($query_params, $allow_blocking);
1910
+	}
1911
+
1912
+
1913
+
1914
+	/**
1915
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1916
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
+	 * as archived, not actually deleted
1918
+	 *
1919
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1923
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
+	 *                                DB
1925
+	 * @return int how many rows got deleted
1926
+	 * @throws EE_Error
1927
+	 */
1928
+	public function delete_permanently($query_params, $allow_blocking = true)
1929
+	{
1930
+		/**
1931
+		 * Action called just before performing a real deletion query. You can use the
1932
+		 * model and its $query_params to find exactly which items will be deleted
1933
+		 *
1934
+		 * @param EEM_Base $model
1935
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1937
+		 *                                 to block (prevent) this deletion
1938
+		 */
1939
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
+		// some MySQL databases may be running safe mode, which may restrict
1941
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
+		// to delete them
1944
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
+			$columns_and_ids_for_deleting
1948
+		);
1949
+		/**
1950
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1951
+		 *
1952
+		 * @param EEM_Base $this  The model instance being acted on.
1953
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
+		 *                                                  derived from the incoming query parameters.
1957
+		 *                                                  @see details on the structure of this array in the phpdocs
1958
+		 *                                                  for the `_get_ids_for_delete_method`
1959
+		 *
1960
+		 */
1961
+		do_action(
1962
+			'AHEE__EEM_Base__delete__before_query',
1963
+			$this,
1964
+			$query_params,
1965
+			$allow_blocking,
1966
+			$columns_and_ids_for_deleting
1967
+		);
1968
+		if ($deletion_where_query_part) {
1969
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
+			$table_aliases = array_keys($this->_tables);
1971
+			$SQL = "DELETE "
1972
+				   . implode(", ", $table_aliases)
1973
+				   . " FROM "
1974
+				   . $model_query_info->get_full_join_sql()
1975
+				   . " WHERE "
1976
+				   . $deletion_where_query_part;
1977
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
+		} else {
1979
+			$rows_deleted = 0;
1980
+		}
1981
+
1982
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
+		// there was no error with the delete query.
1984
+		if (
1985
+			$this->has_primary_key_field()
1986
+			&& $rows_deleted !== false
1987
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
+		) {
1989
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
+			foreach ($ids_for_removal as $id) {
1991
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
+				}
1994
+			}
1995
+
1996
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
+			// (although it is possible).
2000
+			// Note this can be skipped by using the provided filter and returning false.
2001
+			if (
2002
+				apply_filters(
2003
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
+					! $this instanceof EEM_Extra_Meta,
2005
+					$this
2006
+				)
2007
+			) {
2008
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2009
+					0 => array(
2010
+						'EXM_type' => $this->get_this_model_name(),
2011
+						'OBJ_ID'   => array(
2012
+							'IN',
2013
+							$ids_for_removal
2014
+						)
2015
+					)
2016
+				));
2017
+			}
2018
+		}
2019
+
2020
+		/**
2021
+		 * Action called just after performing a real deletion query. Although at this point the
2022
+		 * items should have been deleted
2023
+		 *
2024
+		 * @param EEM_Base $model
2025
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
+		 * @param int      $rows_deleted
2027
+		 */
2028
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
+		return $rows_deleted;// how many supposedly got deleted
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Checks all the relations that throw error messages when there are blocking related objects
2036
+	 * for related model objects. If there are any related model objects on those relations,
2037
+	 * adds an EE_Error, and return true
2038
+	 *
2039
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2040
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
+	 *                                                 should be ignored when determining whether there are related
2042
+	 *                                                 model objects which block this model object's deletion. Useful
2043
+	 *                                                 if you know A is related to B and are considering deleting A,
2044
+	 *                                                 but want to see if A has any other objects blocking its deletion
2045
+	 *                                                 before removing the relation between A and B
2046
+	 * @return boolean
2047
+	 * @throws EE_Error
2048
+	 */
2049
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
+	{
2051
+		// first, if $ignore_this_model_obj was supplied, get its model
2052
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
+			$ignored_model = $ignore_this_model_obj->get_model();
2054
+		} else {
2055
+			$ignored_model = null;
2056
+		}
2057
+		// now check all the relations of $this_model_obj_or_id and see if there
2058
+		// are any related model objects blocking it?
2059
+		$is_blocked = false;
2060
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2062
+				// if $ignore_this_model_obj was supplied, then for the query
2063
+				// on that model needs to be told to ignore $ignore_this_model_obj
2064
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
+						array(
2067
+							$ignored_model->get_primary_key_field()->get_name() => array(
2068
+								'!=',
2069
+								$ignore_this_model_obj->ID(),
2070
+							),
2071
+						),
2072
+					));
2073
+				} else {
2074
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
+				}
2076
+				if ($related_model_objects) {
2077
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
+					$is_blocked = true;
2079
+				}
2080
+			}
2081
+		}
2082
+		return $is_blocked;
2083
+	}
2084
+
2085
+
2086
+	/**
2087
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
+	 * @param array $row_results_for_deleting
2089
+	 * @param bool  $allow_blocking
2090
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
+	 *                 deleted. Example:
2094
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2095
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
+	 *                 where each element is a group of columns and values that get deleted. Example:
2097
+	 *                      array(
2098
+	 *                          0 => array(
2099
+	 *                              'Term_Relationship.object_id' => 1
2100
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2101
+	 *                          ),
2102
+	 *                          1 => array(
2103
+	 *                              'Term_Relationship.object_id' => 1
2104
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2105
+	 *                          )
2106
+	 *                      )
2107
+	 * @throws EE_Error
2108
+	 */
2109
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
+	{
2111
+		$ids_to_delete_indexed_by_column = array();
2112
+		if ($this->has_primary_key_field()) {
2113
+			$primary_table = $this->_get_main_table();
2114
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
+			$other_tables = $this->_get_other_tables();
2116
+			$ids_to_delete_indexed_by_column = $query = array();
2117
+			foreach ($row_results_for_deleting as $item_to_delete) {
2118
+				// before we mark this item for deletion,
2119
+				// make sure there's no related entities blocking its deletion (if we're checking)
2120
+				if (
2121
+					$allow_blocking
2122
+					&& $this->delete_is_blocked_by_related_models(
2123
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
+					)
2125
+				) {
2126
+					continue;
2127
+				}
2128
+				// primary table deletes
2129
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
+				}
2133
+			}
2134
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
+			$fields = $this->get_combined_primary_key_fields();
2136
+			foreach ($row_results_for_deleting as $item_to_delete) {
2137
+				$ids_to_delete_indexed_by_column_for_row = array();
2138
+				foreach ($fields as $cpk_field) {
2139
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2140
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2142
+					}
2143
+				}
2144
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
+			}
2146
+		} else {
2147
+			// so there's no primary key and no combined key...
2148
+			// sorry, can't help you
2149
+			throw new EE_Error(
2150
+				sprintf(
2151
+					__(
2152
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
+						"event_espresso"
2154
+					),
2155
+					get_class($this)
2156
+				)
2157
+			);
2158
+		}
2159
+		return $ids_to_delete_indexed_by_column;
2160
+	}
2161
+
2162
+
2163
+	/**
2164
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
+	 * the corresponding query_part for the query performing the delete.
2166
+	 *
2167
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
+	 * @return string
2169
+	 * @throws EE_Error
2170
+	 */
2171
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
+	{
2173
+		$query_part = '';
2174
+		if (empty($ids_to_delete_indexed_by_column)) {
2175
+			return $query_part;
2176
+		} elseif ($this->has_primary_key_field()) {
2177
+			$query = array();
2178
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
+				// make sure we have unique $ids
2180
+				$ids = array_unique($ids);
2181
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2182
+			}
2183
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
+			$ways_to_identify_a_row = array();
2186
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187
+				$values_for_each_combined_primary_key_for_a_row = array();
2188
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2190
+				}
2191
+				$ways_to_identify_a_row[] = '('
2192
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2193
+											. ')';
2194
+			}
2195
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2196
+		}
2197
+		return $query_part;
2198
+	}
2199
+
2200
+
2201
+
2202
+	/**
2203
+	 * Gets the model field by the fully qualified name
2204
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2205
+	 * @return EE_Model_Field_Base
2206
+	 */
2207
+	public function get_field_by_column($qualified_column_name)
2208
+	{
2209
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2210
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2211
+				return $field_obj;
2212
+			}
2213
+		}
2214
+		throw new EE_Error(
2215
+			sprintf(
2216
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2217
+				$this->get_this_model_name(),
2218
+				$qualified_column_name
2219
+			)
2220
+		);
2221
+	}
2222
+
2223
+
2224
+
2225
+	/**
2226
+	 * Count all the rows that match criteria the model query params.
2227
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2228
+	 * column
2229
+	 *
2230
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2231
+	 * @param string $field_to_count field on model to count by (not column name)
2232
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2233
+	 *                               that by the setting $distinct to TRUE;
2234
+	 * @return int
2235
+	 * @throws EE_Error
2236
+	 */
2237
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2238
+	{
2239
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2240
+		if ($field_to_count) {
2241
+			$field_obj = $this->field_settings_for($field_to_count);
2242
+			$column_to_count = $field_obj->get_qualified_column();
2243
+		} elseif ($this->has_primary_key_field()) {
2244
+			$pk_field_obj = $this->get_primary_key_field();
2245
+			$column_to_count = $pk_field_obj->get_qualified_column();
2246
+		} else {
2247
+			// there's no primary key
2248
+			// if we're counting distinct items, and there's no primary key,
2249
+			// we need to list out the columns for distinction;
2250
+			// otherwise we can just use star
2251
+			if ($distinct) {
2252
+				$columns_to_use = array();
2253
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2254
+					$columns_to_use[] = $field_obj->get_qualified_column();
2255
+				}
2256
+				$column_to_count = implode(',', $columns_to_use);
2257
+			} else {
2258
+				$column_to_count = '*';
2259
+			}
2260
+		}
2261
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2263
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264
+	}
2265
+
2266
+
2267
+
2268
+	/**
2269
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2270
+	 *
2271
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2273
+	 * @return float
2274
+	 * @throws EE_Error
2275
+	 */
2276
+	public function sum($query_params, $field_to_sum = null)
2277
+	{
2278
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2279
+		if ($field_to_sum) {
2280
+			$field_obj = $this->field_settings_for($field_to_sum);
2281
+		} else {
2282
+			$field_obj = $this->get_primary_key_field();
2283
+		}
2284
+		$column_to_count = $field_obj->get_qualified_column();
2285
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287
+		$data_type = $field_obj->get_wpdb_data_type();
2288
+		if ($data_type === '%d' || $data_type === '%s') {
2289
+			return (float) $return_value;
2290
+		}
2291
+		// must be %f
2292
+		return (float) $return_value;
2293
+	}
2294
+
2295
+
2296
+
2297
+	/**
2298
+	 * Just calls the specified method on $wpdb with the given arguments
2299
+	 * Consolidates a little extra error handling code
2300
+	 *
2301
+	 * @param string $wpdb_method
2302
+	 * @param array  $arguments_to_provide
2303
+	 * @throws EE_Error
2304
+	 * @global wpdb  $wpdb
2305
+	 * @return mixed
2306
+	 */
2307
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2308
+	{
2309
+		// if we're in maintenance mode level 2, DON'T run any queries
2310
+		// because level 2 indicates the database needs updating and
2311
+		// is probably out of sync with the code
2312
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2313
+			throw new EE_Error(sprintf(__(
2314
+				"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.",
2315
+				"event_espresso"
2316
+			)));
2317
+		}
2318
+		/** @type WPDB $wpdb */
2319
+		global $wpdb;
2320
+		if (! method_exists($wpdb, $wpdb_method)) {
2321
+			throw new EE_Error(sprintf(__(
2322
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2323
+				'event_espresso'
2324
+			), $wpdb_method));
2325
+		}
2326
+		if (WP_DEBUG) {
2327
+			$old_show_errors_value = $wpdb->show_errors;
2328
+			$wpdb->show_errors(false);
2329
+		}
2330
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2332
+		if (WP_DEBUG) {
2333
+			$wpdb->show_errors($old_show_errors_value);
2334
+			if (! empty($wpdb->last_error)) {
2335
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336
+			}
2337
+			if ($result === false) {
2338
+				throw new EE_Error(sprintf(__(
2339
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2340
+					'event_espresso'
2341
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2342
+			}
2343
+		} elseif ($result === false) {
2344
+			EE_Error::add_error(
2345
+				sprintf(
2346
+					__(
2347
+						'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"',
2348
+						'event_espresso'
2349
+					),
2350
+					$wpdb_method,
2351
+					var_export($arguments_to_provide, true),
2352
+					$wpdb->last_error
2353
+				),
2354
+				__FILE__,
2355
+				__FUNCTION__,
2356
+				__LINE__
2357
+			);
2358
+		}
2359
+		return $result;
2360
+	}
2361
+
2362
+
2363
+
2364
+	/**
2365
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2366
+	 * and if there's an error tries to verify the DB is correct. Uses
2367
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2368
+	 * we should try to fix the EE core db, the addons, or just give up
2369
+	 *
2370
+	 * @param string $wpdb_method
2371
+	 * @param array  $arguments_to_provide
2372
+	 * @return mixed
2373
+	 */
2374
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2375
+	{
2376
+		/** @type WPDB $wpdb */
2377
+		global $wpdb;
2378
+		$wpdb->last_error = null;
2379
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2380
+		// was there an error running the query? but we don't care on new activations
2381
+		// (we're going to setup the DB anyway on new activations)
2382
+		if (
2383
+			($result === false || ! empty($wpdb->last_error))
2384
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2385
+		) {
2386
+			switch (EEM_Base::$_db_verification_level) {
2387
+				case EEM_Base::db_verified_none:
2388
+					// let's double-check core's DB
2389
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2390
+					break;
2391
+				case EEM_Base::db_verified_core:
2392
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2393
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2394
+					break;
2395
+				case EEM_Base::db_verified_addons:
2396
+					// ummmm... you in trouble
2397
+					return $result;
2398
+					break;
2399
+			}
2400
+			if (! empty($error_message)) {
2401
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402
+				trigger_error($error_message);
2403
+			}
2404
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2405
+		}
2406
+		return $result;
2407
+	}
2408
+
2409
+
2410
+
2411
+	/**
2412
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2413
+	 * EEM_Base::$_db_verification_level
2414
+	 *
2415
+	 * @param string $wpdb_method
2416
+	 * @param array  $arguments_to_provide
2417
+	 * @return string
2418
+	 */
2419
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2420
+	{
2421
+		/** @type WPDB $wpdb */
2422
+		global $wpdb;
2423
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2424
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2425
+		$error_message = sprintf(
2426
+			__(
2427
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
+				'event_espresso'
2429
+			),
2430
+			$wpdb->last_error,
2431
+			$wpdb_method,
2432
+			wp_json_encode($arguments_to_provide)
2433
+		);
2434
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2435
+		return $error_message;
2436
+	}
2437
+
2438
+
2439
+
2440
+	/**
2441
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2442
+	 * EEM_Base::$_db_verification_level
2443
+	 *
2444
+	 * @param $wpdb_method
2445
+	 * @param $arguments_to_provide
2446
+	 * @return string
2447
+	 */
2448
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2449
+	{
2450
+		/** @type WPDB $wpdb */
2451
+		global $wpdb;
2452
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2453
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2454
+		$error_message = sprintf(
2455
+			__(
2456
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2457
+				'event_espresso'
2458
+			),
2459
+			$wpdb->last_error,
2460
+			$wpdb_method,
2461
+			wp_json_encode($arguments_to_provide)
2462
+		);
2463
+		EE_System::instance()->initialize_addons();
2464
+		return $error_message;
2465
+	}
2466
+
2467
+
2468
+
2469
+	/**
2470
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2471
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2472
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2473
+	 * ..."
2474
+	 *
2475
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2476
+	 * @return string
2477
+	 */
2478
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479
+	{
2480
+		return " FROM " . $model_query_info->get_full_join_sql() .
2481
+			   $model_query_info->get_where_sql() .
2482
+			   $model_query_info->get_group_by_sql() .
2483
+			   $model_query_info->get_having_sql() .
2484
+			   $model_query_info->get_order_by_sql() .
2485
+			   $model_query_info->get_limit_sql();
2486
+	}
2487
+
2488
+
2489
+
2490
+	/**
2491
+	 * Set to easily debug the next X queries ran from this model.
2492
+	 *
2493
+	 * @param int $count
2494
+	 */
2495
+	public function show_next_x_db_queries($count = 1)
2496
+	{
2497
+		$this->_show_next_x_db_queries = $count;
2498
+	}
2499
+
2500
+
2501
+
2502
+	/**
2503
+	 * @param $sql_query
2504
+	 */
2505
+	public function show_db_query_if_previously_requested($sql_query)
2506
+	{
2507
+		if ($this->_show_next_x_db_queries > 0) {
2508
+			echo $sql_query;
2509
+			$this->_show_next_x_db_queries--;
2510
+		}
2511
+	}
2512
+
2513
+
2514
+
2515
+	/**
2516
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2517
+	 * There are the 3 cases:
2518
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2519
+	 * $otherModelObject has no ID, it is first saved.
2520
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2521
+	 * has no ID, it is first saved.
2522
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2523
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2524
+	 * join table
2525
+	 *
2526
+	 * @param        EE_Base_Class                     /int $thisModelObject
2527
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2528
+	 * @param string $relationName                     , key in EEM_Base::_relations
2529
+	 *                                                 an attendee to a group, you also want to specify which role they
2530
+	 *                                                 will have in that group. So you would use this parameter to
2531
+	 *                                                 specify array('role-column-name'=>'role-id')
2532
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2533
+	 *                                                 to for relation to methods that allow you to further specify
2534
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2535
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2536
+	 *                                                 because these will be inserted in any new rows created as well.
2537
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2538
+	 * @throws EE_Error
2539
+	 */
2540
+	public function add_relationship_to(
2541
+		$id_or_obj,
2542
+		$other_model_id_or_obj,
2543
+		$relationName,
2544
+		$extra_join_model_fields_n_values = array()
2545
+	) {
2546
+		$relation_obj = $this->related_settings_for($relationName);
2547
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2548
+	}
2549
+
2550
+
2551
+
2552
+	/**
2553
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2554
+	 * There are the 3 cases:
2555
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2556
+	 * error
2557
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2558
+	 * an error
2559
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2560
+	 *
2561
+	 * @param        EE_Base_Class /int $id_or_obj
2562
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2563
+	 * @param string $relationName key in EEM_Base::_relations
2564
+	 * @return boolean of success
2565
+	 * @throws EE_Error
2566
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2567
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2568
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2569
+	 *                             because these will be inserted in any new rows created as well.
2570
+	 */
2571
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2572
+	{
2573
+		$relation_obj = $this->related_settings_for($relationName);
2574
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * @param mixed           $id_or_obj
2581
+	 * @param string          $relationName
2582
+	 * @param array           $where_query_params
2583
+	 * @param EE_Base_Class[] objects to which relations were removed
2584
+	 * @return \EE_Base_Class[]
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2588
+	{
2589
+		$relation_obj = $this->related_settings_for($relationName);
2590
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2591
+	}
2592
+
2593
+
2594
+
2595
+	/**
2596
+	 * Gets all the related items of the specified $model_name, using $query_params.
2597
+	 * Note: by default, we remove the "default query params"
2598
+	 * because we want to get even deleted items etc.
2599
+	 *
2600
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2601
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2602
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
+	 * @return EE_Base_Class[]
2604
+	 * @throws EE_Error
2605
+	 */
2606
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2607
+	{
2608
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2609
+		$relation_settings = $this->related_settings_for($model_name);
2610
+		return $relation_settings->get_all_related($model_obj, $query_params);
2611
+	}
2612
+
2613
+
2614
+
2615
+	/**
2616
+	 * Deletes all the model objects across the relation indicated by $model_name
2617
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2618
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2619
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2620
+	 *
2621
+	 * @param EE_Base_Class|int|string $id_or_obj
2622
+	 * @param string                   $model_name
2623
+	 * @param array                    $query_params
2624
+	 * @return int how many deleted
2625
+	 * @throws EE_Error
2626
+	 */
2627
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2628
+	{
2629
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2630
+		$relation_settings = $this->related_settings_for($model_name);
2631
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2632
+	}
2633
+
2634
+
2635
+
2636
+	/**
2637
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2638
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2639
+	 * the model objects can't be hard deleted because of blocking related model objects,
2640
+	 * just does a soft-delete on them instead.
2641
+	 *
2642
+	 * @param EE_Base_Class|int|string $id_or_obj
2643
+	 * @param string                   $model_name
2644
+	 * @param array                    $query_params
2645
+	 * @return int how many deleted
2646
+	 * @throws EE_Error
2647
+	 */
2648
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2649
+	{
2650
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2651
+		$relation_settings = $this->related_settings_for($model_name);
2652
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2653
+	}
2654
+
2655
+
2656
+
2657
+	/**
2658
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2659
+	 * unless otherwise specified in the $query_params
2660
+	 *
2661
+	 * @param        int             /EE_Base_Class $id_or_obj
2662
+	 * @param string $model_name     like 'Event', or 'Registration'
2663
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2664
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2665
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2666
+	 *                               that by the setting $distinct to TRUE;
2667
+	 * @return int
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function count_related(
2671
+		$id_or_obj,
2672
+		$model_name,
2673
+		$query_params = array(),
2674
+		$field_to_count = null,
2675
+		$distinct = false
2676
+	) {
2677
+		$related_model = $this->get_related_model_obj($model_name);
2678
+		// we're just going to use the query params on the related model's normal get_all query,
2679
+		// except add a condition to say to match the current mod
2680
+		if (! isset($query_params['default_where_conditions'])) {
2681
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
+		}
2683
+		$this_model_name = $this->get_this_model_name();
2684
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2686
+		return $related_model->count($query_params, $field_to_count, $distinct);
2687
+	}
2688
+
2689
+
2690
+
2691
+	/**
2692
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2693
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2694
+	 *
2695
+	 * @param        int           /EE_Base_Class $id_or_obj
2696
+	 * @param string $model_name   like 'Event', or 'Registration'
2697
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2698
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2699
+	 * @return float
2700
+	 * @throws EE_Error
2701
+	 */
2702
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703
+	{
2704
+		$related_model = $this->get_related_model_obj($model_name);
2705
+		if (! is_array($query_params)) {
2706
+			EE_Error::doing_it_wrong(
2707
+				'EEM_Base::sum_related',
2708
+				sprintf(
2709
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2710
+					gettype($query_params)
2711
+				),
2712
+				'4.6.0'
2713
+			);
2714
+			$query_params = array();
2715
+		}
2716
+		// we're just going to use the query params on the related model's normal get_all query,
2717
+		// except add a condition to say to match the current mod
2718
+		if (! isset($query_params['default_where_conditions'])) {
2719
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720
+		}
2721
+		$this_model_name = $this->get_this_model_name();
2722
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2724
+		return $related_model->sum($query_params, $field_to_sum);
2725
+	}
2726
+
2727
+
2728
+
2729
+	/**
2730
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2731
+	 * $modelObject
2732
+	 *
2733
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2734
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2735
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
+	 * @return EE_Base_Class
2737
+	 * @throws EE_Error
2738
+	 */
2739
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2740
+	{
2741
+		$query_params['limit'] = 1;
2742
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2743
+		if ($results) {
2744
+			return array_shift($results);
2745
+		}
2746
+		return null;
2747
+	}
2748
+
2749
+
2750
+
2751
+	/**
2752
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2753
+	 *
2754
+	 * @return string
2755
+	 */
2756
+	public function get_this_model_name()
2757
+	{
2758
+		return str_replace("EEM_", "", get_class($this));
2759
+	}
2760
+
2761
+
2762
+
2763
+	/**
2764
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2765
+	 *
2766
+	 * @return EE_Any_Foreign_Model_Name_Field
2767
+	 * @throws EE_Error
2768
+	 */
2769
+	public function get_field_containing_related_model_name()
2770
+	{
2771
+		foreach ($this->field_settings(true) as $field) {
2772
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2773
+				$field_with_model_name = $field;
2774
+			}
2775
+		}
2776
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2777
+			throw new EE_Error(sprintf(
2778
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779
+				$this->get_this_model_name()
2780
+			));
2781
+		}
2782
+		return $field_with_model_name;
2783
+	}
2784
+
2785
+
2786
+
2787
+	/**
2788
+	 * Inserts a new entry into the database, for each table.
2789
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2790
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2791
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2792
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2793
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2794
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2795
+	 *
2796
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2797
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2798
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2799
+	 *                              of EEM_Base)
2800
+	 * @return int|string new primary key on main table that got inserted
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	public function insert($field_n_values)
2804
+	{
2805
+		/**
2806
+		 * Filters the fields and their values before inserting an item using the models
2807
+		 *
2808
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2809
+		 * @param EEM_Base $model           the model used
2810
+		 */
2811
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2812
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2813
+			$main_table = $this->_get_main_table();
2814
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2815
+			if ($new_id !== false) {
2816
+				foreach ($this->_get_other_tables() as $other_table) {
2817
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2818
+				}
2819
+			}
2820
+			/**
2821
+			 * Done just after attempting to insert a new model object
2822
+			 *
2823
+			 * @param EEM_Base   $model           used
2824
+			 * @param array      $fields_n_values fields and their values
2825
+			 * @param int|string the              ID of the newly-inserted model object
2826
+			 */
2827
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2828
+			return $new_id;
2829
+		}
2830
+		return false;
2831
+	}
2832
+
2833
+
2834
+
2835
+	/**
2836
+	 * Checks that the result would satisfy the unique indexes on this model
2837
+	 *
2838
+	 * @param array  $field_n_values
2839
+	 * @param string $action
2840
+	 * @return boolean
2841
+	 * @throws EE_Error
2842
+	 */
2843
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2844
+	{
2845
+		foreach ($this->unique_indexes() as $index_name => $index) {
2846
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2847
+			if ($this->exists(array($uniqueness_where_params))) {
2848
+				EE_Error::add_error(
2849
+					sprintf(
2850
+						__(
2851
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2852
+							"event_espresso"
2853
+						),
2854
+						$action,
2855
+						$this->_get_class_name(),
2856
+						$index_name,
2857
+						implode(",", $index->field_names()),
2858
+						http_build_query($uniqueness_where_params)
2859
+					),
2860
+					__FILE__,
2861
+					__FUNCTION__,
2862
+					__LINE__
2863
+				);
2864
+				return false;
2865
+			}
2866
+		}
2867
+		return true;
2868
+	}
2869
+
2870
+
2871
+
2872
+	/**
2873
+	 * Checks the database for an item that conflicts (ie, if this item were
2874
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2875
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2876
+	 * can be either an EE_Base_Class or an array of fields n values
2877
+	 *
2878
+	 * @param EE_Base_Class|array $obj_or_fields_array
2879
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2880
+	 *                                                 when looking for conflicts
2881
+	 *                                                 (ie, if false, we ignore the model object's primary key
2882
+	 *                                                 when finding "conflicts". If true, it's also considered).
2883
+	 *                                                 Only works for INT primary key,
2884
+	 *                                                 STRING primary keys cannot be ignored
2885
+	 * @throws EE_Error
2886
+	 * @return EE_Base_Class|array
2887
+	 */
2888
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2889
+	{
2890
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2891
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2892
+		} elseif (is_array($obj_or_fields_array)) {
2893
+			$fields_n_values = $obj_or_fields_array;
2894
+		} else {
2895
+			throw new EE_Error(
2896
+				sprintf(
2897
+					__(
2898
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2899
+						"event_espresso"
2900
+					),
2901
+					get_class($this),
2902
+					$obj_or_fields_array
2903
+				)
2904
+			);
2905
+		}
2906
+		$query_params = array();
2907
+		if (
2908
+			$this->has_primary_key_field()
2909
+			&& ($include_primary_key
2910
+				|| $this->get_primary_key_field()
2911
+				   instanceof
2912
+				   EE_Primary_Key_String_Field)
2913
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2914
+		) {
2915
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2916
+		}
2917
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2920
+		}
2921
+		// if there is nothing to base this search on, then we shouldn't find anything
2922
+		if (empty($query_params)) {
2923
+			return array();
2924
+		}
2925
+		return $this->get_one($query_params);
2926
+	}
2927
+
2928
+
2929
+
2930
+	/**
2931
+	 * Like count, but is optimized and returns a boolean instead of an int
2932
+	 *
2933
+	 * @param array $query_params
2934
+	 * @return boolean
2935
+	 * @throws EE_Error
2936
+	 */
2937
+	public function exists($query_params)
2938
+	{
2939
+		$query_params['limit'] = 1;
2940
+		return $this->count($query_params) > 0;
2941
+	}
2942
+
2943
+
2944
+
2945
+	/**
2946
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2947
+	 *
2948
+	 * @param int|string $id
2949
+	 * @return boolean
2950
+	 * @throws EE_Error
2951
+	 */
2952
+	public function exists_by_ID($id)
2953
+	{
2954
+		return $this->exists(
2955
+			array(
2956
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2957
+				array(
2958
+					$this->primary_key_name() => $id,
2959
+				),
2960
+			)
2961
+		);
2962
+	}
2963
+
2964
+
2965
+
2966
+	/**
2967
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2968
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2969
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2970
+	 * on the main table)
2971
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2972
+	 * cases where we want to call it directly rather than via insert().
2973
+	 *
2974
+	 * @access   protected
2975
+	 * @param EE_Table_Base $table
2976
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2977
+	 *                                       float
2978
+	 * @param int           $new_id          for now we assume only int keys
2979
+	 * @throws EE_Error
2980
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2981
+	 * @return int ID of new row inserted, or FALSE on failure
2982
+	 */
2983
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2984
+	{
2985
+		global $wpdb;
2986
+		$insertion_col_n_values = array();
2987
+		$format_for_insertion = array();
2988
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2989
+		foreach ($fields_on_table as $field_name => $field_obj) {
2990
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2991
+			if ($field_obj->is_auto_increment()) {
2992
+				continue;
2993
+			}
2994
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2996
+			if ($prepared_value !== null) {
2997
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2998
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999
+			}
3000
+		}
3001
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3002
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3003
+			// so add the fk to the main table as a column
3004
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3006
+		}
3007
+		// insert the new entry
3008
+		$result = $this->_do_wpdb_query(
3009
+			'insert',
3010
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3011
+		);
3012
+		if ($result === false) {
3013
+			return false;
3014
+		}
3015
+		// ok, now what do we return for the ID of the newly-inserted thing?
3016
+		if ($this->has_primary_key_field()) {
3017
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3018
+				return $wpdb->insert_id;
3019
+			}
3020
+			// it's not an auto-increment primary key, so
3021
+			// it must have been supplied
3022
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3023
+		}
3024
+		// we can't return a  primary key because there is none. instead return
3025
+		// a unique string indicating this model
3026
+		return $this->get_index_primary_key_string($fields_n_values);
3027
+	}
3028
+
3029
+
3030
+
3031
+	/**
3032
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3033
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3034
+	 * and there is no default, we pass it along. WPDB will take care of it)
3035
+	 *
3036
+	 * @param EE_Model_Field_Base $field_obj
3037
+	 * @param array               $fields_n_values
3038
+	 * @return mixed string|int|float depending on what the table column will be expecting
3039
+	 * @throws EE_Error
3040
+	 */
3041
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3042
+	{
3043
+		// if this field doesn't allow nullable, don't allow it
3044
+		if (
3045
+			! $field_obj->is_nullable()
3046
+			&& (
3047
+				! isset($fields_n_values[ $field_obj->get_name() ])
3048
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3049
+			)
3050
+		) {
3051
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3052
+		}
3053
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
+			? $fields_n_values[ $field_obj->get_name() ]
3055
+			: null;
3056
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057
+	}
3058
+
3059
+
3060
+
3061
+	/**
3062
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3063
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3064
+	 * the field's prepare_for_set() method.
3065
+	 *
3066
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3067
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3068
+	 *                                   top of file)
3069
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3070
+	 *                                   $value is a custom selection
3071
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3072
+	 */
3073
+	private function _prepare_value_for_use_in_db($value, $field)
3074
+	{
3075
+		if ($field && $field instanceof EE_Model_Field_Base) {
3076
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3077
+			switch ($this->_values_already_prepared_by_model_object) {
3078
+				/** @noinspection PhpMissingBreakStatementInspection */
3079
+				case self::not_prepared_by_model_object:
3080
+					$value = $field->prepare_for_set($value);
3081
+				// purposefully left out "return"
3082
+				case self::prepared_by_model_object:
3083
+					/** @noinspection SuspiciousAssignmentsInspection */
3084
+					$value = $field->prepare_for_use_in_db($value);
3085
+				case self::prepared_for_use_in_db:
3086
+					// leave the value alone
3087
+			}
3088
+			return $value;
3089
+			// phpcs:enable
3090
+		}
3091
+		return $value;
3092
+	}
3093
+
3094
+
3095
+
3096
+	/**
3097
+	 * Returns the main table on this model
3098
+	 *
3099
+	 * @return EE_Primary_Table
3100
+	 * @throws EE_Error
3101
+	 */
3102
+	protected function _get_main_table()
3103
+	{
3104
+		foreach ($this->_tables as $table) {
3105
+			if ($table instanceof EE_Primary_Table) {
3106
+				return $table;
3107
+			}
3108
+		}
3109
+		throw new EE_Error(sprintf(__(
3110
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3111
+			'event_espresso'
3112
+		), get_class($this)));
3113
+	}
3114
+
3115
+
3116
+
3117
+	/**
3118
+	 * table
3119
+	 * returns EE_Primary_Table table name
3120
+	 *
3121
+	 * @return string
3122
+	 * @throws EE_Error
3123
+	 */
3124
+	public function table()
3125
+	{
3126
+		return $this->_get_main_table()->get_table_name();
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * table
3133
+	 * returns first EE_Secondary_Table table name
3134
+	 *
3135
+	 * @return string
3136
+	 */
3137
+	public function second_table()
3138
+	{
3139
+		// grab second table from tables array
3140
+		$second_table = end($this->_tables);
3141
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * get_table_obj_by_alias
3148
+	 * returns table name given it's alias
3149
+	 *
3150
+	 * @param string $table_alias
3151
+	 * @return EE_Primary_Table | EE_Secondary_Table
3152
+	 */
3153
+	public function get_table_obj_by_alias($table_alias = '')
3154
+	{
3155
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
+	 *
3163
+	 * @return EE_Secondary_Table[]
3164
+	 */
3165
+	protected function _get_other_tables()
3166
+	{
3167
+		$other_tables = array();
3168
+		foreach ($this->_tables as $table_alias => $table) {
3169
+			if ($table instanceof EE_Secondary_Table) {
3170
+				$other_tables[ $table_alias ] = $table;
3171
+			}
3172
+		}
3173
+		return $other_tables;
3174
+	}
3175
+
3176
+
3177
+
3178
+	/**
3179
+	 * Finds all the fields that correspond to the given table
3180
+	 *
3181
+	 * @param string $table_alias , array key in EEM_Base::_tables
3182
+	 * @return EE_Model_Field_Base[]
3183
+	 */
3184
+	public function _get_fields_for_table($table_alias)
3185
+	{
3186
+		return $this->_fields[ $table_alias ];
3187
+	}
3188
+
3189
+
3190
+
3191
+	/**
3192
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3193
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
+	 * related Registration, Transaction, and Payment models.
3197
+	 *
3198
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 * @throws EE_Error
3201
+	 */
3202
+	public function _extract_related_models_from_query($query_params)
3203
+	{
3204
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
+		if (array_key_exists(0, $query_params)) {
3206
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
+		}
3208
+		if (array_key_exists('group_by', $query_params)) {
3209
+			if (is_array($query_params['group_by'])) {
3210
+				$this->_extract_related_models_from_sub_params_array_values(
3211
+					$query_params['group_by'],
3212
+					$query_info_carrier,
3213
+					'group_by'
3214
+				);
3215
+			} elseif (! empty($query_params['group_by'])) {
3216
+				$this->_extract_related_model_info_from_query_param(
3217
+					$query_params['group_by'],
3218
+					$query_info_carrier,
3219
+					'group_by'
3220
+				);
3221
+			}
3222
+		}
3223
+		if (array_key_exists('having', $query_params)) {
3224
+			$this->_extract_related_models_from_sub_params_array_keys(
3225
+				$query_params[0],
3226
+				$query_info_carrier,
3227
+				'having'
3228
+			);
3229
+		}
3230
+		if (array_key_exists('order_by', $query_params)) {
3231
+			if (is_array($query_params['order_by'])) {
3232
+				$this->_extract_related_models_from_sub_params_array_keys(
3233
+					$query_params['order_by'],
3234
+					$query_info_carrier,
3235
+					'order_by'
3236
+				);
3237
+			} elseif (! empty($query_params['order_by'])) {
3238
+				$this->_extract_related_model_info_from_query_param(
3239
+					$query_params['order_by'],
3240
+					$query_info_carrier,
3241
+					'order_by'
3242
+				);
3243
+			}
3244
+		}
3245
+		if (array_key_exists('force_join', $query_params)) {
3246
+			$this->_extract_related_models_from_sub_params_array_values(
3247
+				$query_params['force_join'],
3248
+				$query_info_carrier,
3249
+				'force_join'
3250
+			);
3251
+		}
3252
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
+		return $query_info_carrier;
3254
+	}
3255
+
3256
+
3257
+
3258
+	/**
3259
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
+	 *
3261
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3262
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3264
+	 * @throws EE_Error
3265
+	 * @return \EE_Model_Query_Info_Carrier
3266
+	 */
3267
+	private function _extract_related_models_from_sub_params_array_keys(
3268
+		$sub_query_params,
3269
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
+		$query_param_type
3271
+	) {
3272
+		if (! empty($sub_query_params)) {
3273
+			$sub_query_params = (array) $sub_query_params;
3274
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
+				$this->_extract_related_model_info_from_query_param(
3277
+					$param,
3278
+					$model_query_info_carrier,
3279
+					$query_param_type
3280
+				);
3281
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3282
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3283
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3284
+				// of array('Registration.TXN_ID'=>23)
3285
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
+					if (! is_array($possibly_array_of_params)) {
3288
+						throw new EE_Error(sprintf(
3289
+							__(
3290
+								"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'))",
3291
+								"event_espresso"
3292
+							),
3293
+							$param,
3294
+							$possibly_array_of_params
3295
+						));
3296
+					}
3297
+					$this->_extract_related_models_from_sub_params_array_keys(
3298
+						$possibly_array_of_params,
3299
+						$model_query_info_carrier,
3300
+						$query_param_type
3301
+					);
3302
+				} elseif (
3303
+					$query_param_type === 0 // ie WHERE
3304
+						  && is_array($possibly_array_of_params)
3305
+						  && isset($possibly_array_of_params[2])
3306
+						  && $possibly_array_of_params[2] == true
3307
+				) {
3308
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309
+					// indicating that $possible_array_of_params[1] is actually a field name,
3310
+					// from which we should extract query parameters!
3311
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312
+						throw new EE_Error(sprintf(__(
3313
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314
+							"event_espresso"
3315
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3316
+					}
3317
+					$this->_extract_related_model_info_from_query_param(
3318
+						$possibly_array_of_params[1],
3319
+						$model_query_info_carrier,
3320
+						$query_param_type
3321
+					);
3322
+				}
3323
+			}
3324
+		}
3325
+		return $model_query_info_carrier;
3326
+	}
3327
+
3328
+
3329
+
3330
+	/**
3331
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3332
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3333
+	 *
3334
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3335
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3336
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3337
+	 * @throws EE_Error
3338
+	 * @return \EE_Model_Query_Info_Carrier
3339
+	 */
3340
+	private function _extract_related_models_from_sub_params_array_values(
3341
+		$sub_query_params,
3342
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343
+		$query_param_type
3344
+	) {
3345
+		if (! empty($sub_query_params)) {
3346
+			if (! is_array($sub_query_params)) {
3347
+				throw new EE_Error(sprintf(
3348
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349
+					$sub_query_params
3350
+				));
3351
+			}
3352
+			foreach ($sub_query_params as $param) {
3353
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3354
+				$this->_extract_related_model_info_from_query_param(
3355
+					$param,
3356
+					$model_query_info_carrier,
3357
+					$query_param_type
3358
+				);
3359
+			}
3360
+		}
3361
+		return $model_query_info_carrier;
3362
+	}
3363
+
3364
+
3365
+	/**
3366
+	 * Extract all the query parts from  model query params
3367
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3368
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3369
+	 * but use them in a different order. Eg, we need to know what models we are querying
3370
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3371
+	 * other models before we can finalize the where clause SQL.
3372
+	 *
3373
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3374
+	 * @throws EE_Error
3375
+	 * @return EE_Model_Query_Info_Carrier
3376
+	 * @throws ModelConfigurationException
3377
+	 */
3378
+	public function _create_model_query_info_carrier($query_params)
3379
+	{
3380
+		if (! is_array($query_params)) {
3381
+			EE_Error::doing_it_wrong(
3382
+				'EEM_Base::_create_model_query_info_carrier',
3383
+				sprintf(
3384
+					__(
3385
+						'$query_params should be an array, you passed a variable of type %s',
3386
+						'event_espresso'
3387
+					),
3388
+					gettype($query_params)
3389
+				),
3390
+				'4.6.0'
3391
+			);
3392
+			$query_params = array();
3393
+		}
3394
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3395
+		// first check if we should alter the query to account for caps or not
3396
+		// because the caps might require us to do extra joins
3397
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3398
+			$query_params[0] = array_replace_recursive(
3399
+				$query_params[0],
3400
+				$this->caps_where_conditions(
3401
+					$query_params['caps']
3402
+				)
3403
+			);
3404
+		}
3405
+
3406
+		// check if we should alter the query to remove data related to protected
3407
+		// custom post types
3408
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3409
+			$where_param_key_for_password = $this->modelChainAndPassword();
3410
+			// only include if related to a cpt where no password has been set
3411
+			$query_params[0]['OR*nopassword'] = array(
3412
+				$where_param_key_for_password => '',
3413
+				$where_param_key_for_password . '*' => array('IS_NULL')
3414
+			);
3415
+		}
3416
+		$query_object = $this->_extract_related_models_from_query($query_params);
3417
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3418
+		foreach ($query_params[0] as $key => $value) {
3419
+			if (is_int($key)) {
3420
+				throw new EE_Error(
3421
+					sprintf(
3422
+						__(
3423
+							"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.",
3424
+							"event_espresso"
3425
+						),
3426
+						$key,
3427
+						var_export($value, true),
3428
+						var_export($query_params, true),
3429
+						get_class($this)
3430
+					)
3431
+				);
3432
+			}
3433
+		}
3434
+		if (
3435
+			array_key_exists('default_where_conditions', $query_params)
3436
+			&& ! empty($query_params['default_where_conditions'])
3437
+		) {
3438
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3439
+		} else {
3440
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3441
+		}
3442
+		$query_params[0] = array_merge(
3443
+			$this->_get_default_where_conditions_for_models_in_query(
3444
+				$query_object,
3445
+				$use_default_where_conditions,
3446
+				$query_params[0]
3447
+			),
3448
+			$query_params[0]
3449
+		);
3450
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3451
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3452
+		// So we need to setup a subquery and use that for the main join.
3453
+		// Note for now this only works on the primary table for the model.
3454
+		// So for instance, you could set the limit array like this:
3455
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3456
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3457
+			$query_object->set_main_model_join_sql(
3458
+				$this->_construct_limit_join_select(
3459
+					$query_params['on_join_limit'][0],
3460
+					$query_params['on_join_limit'][1]
3461
+				)
3462
+			);
3463
+		}
3464
+		// set limit
3465
+		if (array_key_exists('limit', $query_params)) {
3466
+			if (is_array($query_params['limit'])) {
3467
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468
+					$e = sprintf(
3469
+						__(
3470
+							"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)",
3471
+							"event_espresso"
3472
+						),
3473
+						http_build_query($query_params['limit'])
3474
+					);
3475
+					throw new EE_Error($e . "|" . $e);
3476
+				}
3477
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
+			} elseif (! empty($query_params['limit'])) {
3480
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3481
+			}
3482
+		}
3483
+		// set order by
3484
+		if (array_key_exists('order_by', $query_params)) {
3485
+			if (is_array($query_params['order_by'])) {
3486
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3487
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3488
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3489
+				if (array_key_exists('order', $query_params)) {
3490
+					throw new EE_Error(
3491
+						sprintf(
3492
+							__(
3493
+								"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 ",
3494
+								"event_espresso"
3495
+							),
3496
+							get_class($this),
3497
+							implode(", ", array_keys($query_params['order_by'])),
3498
+							implode(", ", $query_params['order_by']),
3499
+							$query_params['order']
3500
+						)
3501
+					);
3502
+				}
3503
+				$this->_extract_related_models_from_sub_params_array_keys(
3504
+					$query_params['order_by'],
3505
+					$query_object,
3506
+					'order_by'
3507
+				);
3508
+				// assume it's an array of fields to order by
3509
+				$order_array = array();
3510
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511
+					$order = $this->_extract_order($order);
3512
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3513
+				}
3514
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
+			} elseif (! empty($query_params['order_by'])) {
3516
+				$this->_extract_related_model_info_from_query_param(
3517
+					$query_params['order_by'],
3518
+					$query_object,
3519
+					'order',
3520
+					$query_params['order_by']
3521
+				);
3522
+				$order = isset($query_params['order'])
3523
+					? $this->_extract_order($query_params['order'])
3524
+					: 'DESC';
3525
+				$query_object->set_order_by_sql(
3526
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3527
+				);
3528
+			}
3529
+		}
3530
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3531
+		if (
3532
+			! array_key_exists('order_by', $query_params)
3533
+			&& array_key_exists('order', $query_params)
3534
+			&& ! empty($query_params['order'])
3535
+		) {
3536
+			$pk_field = $this->get_primary_key_field();
3537
+			$order = $this->_extract_order($query_params['order']);
3538
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3539
+		}
3540
+		// set group by
3541
+		if (array_key_exists('group_by', $query_params)) {
3542
+			if (is_array($query_params['group_by'])) {
3543
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3544
+				$group_by_array = array();
3545
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547
+				}
3548
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
+			} elseif (! empty($query_params['group_by'])) {
3550
+				$query_object->set_group_by_sql(
3551
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3552
+				);
3553
+			}
3554
+		}
3555
+		// set having
3556
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3557
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3558
+		}
3559
+		// now, just verify they didn't pass anything wack
3560
+		foreach ($query_params as $query_key => $query_value) {
3561
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3562
+				throw new EE_Error(
3563
+					sprintf(
3564
+						__(
3565
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3566
+							'event_espresso'
3567
+						),
3568
+						$query_key,
3569
+						get_class($this),
3570
+						//                      print_r( $this->_allowed_query_params, TRUE )
3571
+						implode(',', $this->_allowed_query_params)
3572
+					)
3573
+				);
3574
+			}
3575
+		}
3576
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3577
+		if (empty($main_model_join_sql)) {
3578
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3579
+		}
3580
+		return $query_object;
3581
+	}
3582
+
3583
+
3584
+
3585
+	/**
3586
+	 * Gets the where conditions that should be imposed on the query based on the
3587
+	 * context (eg reading frontend, backend, edit or delete).
3588
+	 *
3589
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3590
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3591
+	 * @throws EE_Error
3592
+	 */
3593
+	public function caps_where_conditions($context = self::caps_read)
3594
+	{
3595
+		EEM_Base::verify_is_valid_cap_context($context);
3596
+		$cap_where_conditions = array();
3597
+		$cap_restrictions = $this->caps_missing($context);
3598
+		/**
3599
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3600
+		 */
3601
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3602
+			$cap_where_conditions = array_replace_recursive(
3603
+				$cap_where_conditions,
3604
+				$restriction_if_no_cap->get_default_where_conditions()
3605
+			);
3606
+		}
3607
+		return apply_filters(
3608
+			'FHEE__EEM_Base__caps_where_conditions__return',
3609
+			$cap_where_conditions,
3610
+			$this,
3611
+			$context,
3612
+			$cap_restrictions
3613
+		);
3614
+	}
3615
+
3616
+
3617
+
3618
+	/**
3619
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3620
+	 * otherwise throws an exception
3621
+	 *
3622
+	 * @param string $should_be_order_string
3623
+	 * @return string either ASC, asc, DESC or desc
3624
+	 * @throws EE_Error
3625
+	 */
3626
+	private function _extract_order($should_be_order_string)
3627
+	{
3628
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3629
+			return $should_be_order_string;
3630
+		}
3631
+		throw new EE_Error(
3632
+			sprintf(
3633
+				__(
3634
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3635
+					"event_espresso"
3636
+				),
3637
+				get_class($this),
3638
+				$should_be_order_string
3639
+			)
3640
+		);
3641
+	}
3642
+
3643
+
3644
+
3645
+	/**
3646
+	 * Looks at all the models which are included in this query, and asks each
3647
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3648
+	 * so they can be merged
3649
+	 *
3650
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3651
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3652
+	 *                                                                  'none' means NO default where conditions will
3653
+	 *                                                                  be used AT ALL during this query.
3654
+	 *                                                                  'other_models_only' means default where
3655
+	 *                                                                  conditions from other models will be used, but
3656
+	 *                                                                  not for this primary model. 'all', the default,
3657
+	 *                                                                  means default where conditions will apply as
3658
+	 *                                                                  normal
3659
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
+	 * @throws EE_Error
3661
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3662
+	 */
3663
+	private function _get_default_where_conditions_for_models_in_query(
3664
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3665
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3666
+		$where_query_params = array()
3667
+	) {
3668
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670
+			throw new EE_Error(sprintf(
3671
+				__(
3672
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3673
+					"event_espresso"
3674
+				),
3675
+				$use_default_where_conditions,
3676
+				implode(", ", $allowed_used_default_where_conditions_values)
3677
+			));
3678
+		}
3679
+		$universal_query_params = array();
3680
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_default_where_conditions();
3682
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3683
+			$universal_query_params = $this->_get_minimum_where_conditions();
3684
+		}
3685
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3686
+			$related_model = $this->get_related_model_obj($model_name);
3687
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3689
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3690
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3691
+			} else {
3692
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3693
+				continue;
3694
+			}
3695
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3696
+				$related_model_universal_where_params,
3697
+				$where_query_params,
3698
+				$related_model,
3699
+				$model_relation_path
3700
+			);
3701
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3702
+				$universal_query_params,
3703
+				$overrides
3704
+			);
3705
+		}
3706
+		return $universal_query_params;
3707
+	}
3708
+
3709
+
3710
+
3711
+	/**
3712
+	 * Determines whether or not we should use default where conditions for the model in question
3713
+	 * (this model, or other related models).
3714
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3715
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3716
+	 * We should use default where conditions on related models when they requested to use default where conditions
3717
+	 * on all models, or specifically just on other related models
3718
+	 * @param      $default_where_conditions_value
3719
+	 * @param bool $for_this_model false means this is for OTHER related models
3720
+	 * @return bool
3721
+	 */
3722
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3723
+	{
3724
+		return (
3725
+				   $for_this_model
3726
+				   && in_array(
3727
+					   $default_where_conditions_value,
3728
+					   array(
3729
+						   EEM_Base::default_where_conditions_all,
3730
+						   EEM_Base::default_where_conditions_this_only,
3731
+						   EEM_Base::default_where_conditions_minimum_others,
3732
+					   ),
3733
+					   true
3734
+				   )
3735
+			   )
3736
+			   || (
3737
+				   ! $for_this_model
3738
+				   && in_array(
3739
+					   $default_where_conditions_value,
3740
+					   array(
3741
+						   EEM_Base::default_where_conditions_all,
3742
+						   EEM_Base::default_where_conditions_others_only,
3743
+					   ),
3744
+					   true
3745
+				   )
3746
+			   );
3747
+	}
3748
+
3749
+	/**
3750
+	 * Determines whether or not we should use default minimum conditions for the model in question
3751
+	 * (this model, or other related models).
3752
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3753
+	 * where conditions.
3754
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3755
+	 * on this model or others
3756
+	 * @param      $default_where_conditions_value
3757
+	 * @param bool $for_this_model false means this is for OTHER related models
3758
+	 * @return bool
3759
+	 */
3760
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3761
+	{
3762
+		return (
3763
+				   $for_this_model
3764
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3765
+			   )
3766
+			   || (
3767
+				   ! $for_this_model
3768
+				   && in_array(
3769
+					   $default_where_conditions_value,
3770
+					   array(
3771
+						   EEM_Base::default_where_conditions_minimum_others,
3772
+						   EEM_Base::default_where_conditions_minimum_all,
3773
+					   ),
3774
+					   true
3775
+				   )
3776
+			   );
3777
+	}
3778
+
3779
+
3780
+	/**
3781
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3782
+	 * then we also add a special where condition which allows for that model's primary key
3783
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3784
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3785
+	 *
3786
+	 * @param array    $default_where_conditions
3787
+	 * @param array    $provided_where_conditions
3788
+	 * @param EEM_Base $model
3789
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3790
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3791
+	 * @throws EE_Error
3792
+	 */
3793
+	private function _override_defaults_or_make_null_friendly(
3794
+		$default_where_conditions,
3795
+		$provided_where_conditions,
3796
+		$model,
3797
+		$model_relation_path
3798
+	) {
3799
+		$null_friendly_where_conditions = array();
3800
+		$none_overridden = true;
3801
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3802
+		foreach ($default_where_conditions as $key => $val) {
3803
+			if (isset($provided_where_conditions[ $key ])) {
3804
+				$none_overridden = false;
3805
+			} else {
3806
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3807
+			}
3808
+		}
3809
+		if ($none_overridden && $default_where_conditions) {
3810
+			if ($model->has_primary_key_field()) {
3811
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3812
+																				. "."
3813
+																				. $model->primary_key_name() ] = array('IS NULL');
3814
+			}/*else{
3815 3815
                 //@todo NO PK, use other defaults
3816 3816
             }*/
3817
-        }
3818
-        return $null_friendly_where_conditions;
3819
-    }
3820
-
3821
-
3822
-
3823
-    /**
3824
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3825
-     * default where conditions on all get_all, update, and delete queries done by this model.
3826
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3827
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3828
-     *
3829
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
-     */
3832
-    private function _get_default_where_conditions($model_relation_path = '')
3833
-    {
3834
-        if ($this->_ignore_where_strategy) {
3835
-            return array();
3836
-        }
3837
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
-    }
3839
-
3840
-
3841
-
3842
-    /**
3843
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3844
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3845
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3846
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3847
-     * Similar to _get_default_where_conditions
3848
-     *
3849
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3850
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
-     */
3852
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3853
-    {
3854
-        if ($this->_ignore_where_strategy) {
3855
-            return array();
3856
-        }
3857
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3858
-    }
3859
-
3860
-
3861
-
3862
-    /**
3863
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3864
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3865
-     *
3866
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3867
-     * @return string
3868
-     * @throws EE_Error
3869
-     */
3870
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3871
-    {
3872
-        $selects = $this->_get_columns_to_select_for_this_model();
3873
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3874
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
-            foreach ($other_model_selects as $key => $value) {
3877
-                $selects[] = $value;
3878
-            }
3879
-        }
3880
-        return implode(", ", $selects);
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
-     * So that's going to be the columns for all the fields on the model
3888
-     *
3889
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
-     */
3892
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
-    {
3894
-        $fields = $this->field_settings();
3895
-        $selects = array();
3896
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
-            $model_relation_chain,
3898
-            $this->get_this_model_name()
3899
-        );
3900
-        foreach ($fields as $field_obj) {
3901
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3902
-                         . $field_obj->get_table_alias()
3903
-                         . "."
3904
-                         . $field_obj->get_table_column()
3905
-                         . " AS '"
3906
-                         . $table_alias_with_model_relation_chain_prefix
3907
-                         . $field_obj->get_table_alias()
3908
-                         . "."
3909
-                         . $field_obj->get_table_column()
3910
-                         . "'";
3911
-        }
3912
-        // make sure we are also getting the PKs of each table
3913
-        $tables = $this->get_tables();
3914
-        if (count($tables) > 1) {
3915
-            foreach ($tables as $table_obj) {
3916
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
-                                       . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3919
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
-                }
3921
-            }
3922
-        }
3923
-        return $selects;
3924
-    }
3925
-
3926
-
3927
-
3928
-    /**
3929
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
-     * SQL for joining, and the data types
3933
-     *
3934
-     * @param null|string                 $original_query_param
3935
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3940
-     *                                                          or 'Registration's
3941
-     * @param string                      $original_query_param what it originally was (eg
3942
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
-     *                                                          matches $query_param
3944
-     * @throws EE_Error
3945
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
-     */
3947
-    private function _extract_related_model_info_from_query_param(
3948
-        $query_param,
3949
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
-        $query_param_type,
3951
-        $original_query_param = null
3952
-    ) {
3953
-        if ($original_query_param === null) {
3954
-            $original_query_param = $query_param;
3955
-        }
3956
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
-        $allow_fields = in_array(
3960
-            $query_param_type,
3961
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
-            true
3963
-        );
3964
-        // check to see if we have a field on this model
3965
-        $this_model_fields = $this->field_settings(true);
3966
-        if (array_key_exists($query_param, $this_model_fields)) {
3967
-            if ($allow_fields) {
3968
-                return;
3969
-            }
3970
-            throw new EE_Error(
3971
-                sprintf(
3972
-                    __(
3973
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
-                        "event_espresso"
3975
-                    ),
3976
-                    $query_param,
3977
-                    get_class($this),
3978
-                    $query_param_type,
3979
-                    $original_query_param
3980
-                )
3981
-            );
3982
-        }
3983
-        // check if this is a special logic query param
3984
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
-            if ($allow_logic_query_params) {
3986
-                return;
3987
-            }
3988
-            throw new EE_Error(
3989
-                sprintf(
3990
-                    __(
3991
-                        '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',
3992
-                        'event_espresso'
3993
-                    ),
3994
-                    implode('", "', $this->_logic_query_param_keys),
3995
-                    $query_param,
3996
-                    get_class($this),
3997
-                    '<br />',
3998
-                    "\t"
3999
-                    . ' $passed_in_query_info = <pre>'
4000
-                    . print_r($passed_in_query_info, true)
4001
-                    . '</pre>'
4002
-                    . "\n\t"
4003
-                    . ' $query_param_type = '
4004
-                    . $query_param_type
4005
-                    . "\n\t"
4006
-                    . ' $original_query_param = '
4007
-                    . $original_query_param
4008
-                )
4009
-            );
4010
-        }
4011
-        // check if it's a custom selection
4012
-        if (
4013
-            $this->_custom_selections instanceof CustomSelects
4014
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
-        ) {
4016
-            return;
4017
-        }
4018
-        // check if has a model name at the beginning
4019
-        // and
4020
-        // check if it's a field on a related model
4021
-        if (
4022
-            $this->extractJoinModelFromQueryParams(
4023
-                $passed_in_query_info,
4024
-                $query_param,
4025
-                $original_query_param,
4026
-                $query_param_type
4027
-            )
4028
-        ) {
4029
-            return;
4030
-        }
4031
-
4032
-        // ok so $query_param didn't start with a model name
4033
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4034
-        // it's wack, that's what it is
4035
-        throw new EE_Error(
4036
-            sprintf(
4037
-                esc_html__(
4038
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
-                    "event_espresso"
4040
-                ),
4041
-                $query_param,
4042
-                get_class($this),
4043
-                $query_param_type,
4044
-                $original_query_param
4045
-            )
4046
-        );
4047
-    }
4048
-
4049
-
4050
-    /**
4051
-     * Extracts any possible join model information from the provided possible_join_string.
4052
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
-     * parts that should be added to the query.
4054
-     *
4055
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
-     * @param null|string                 $original_query_param
4058
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
-     * @return bool  returns true if a join was added and false if not.
4061
-     * @throws EE_Error
4062
-     */
4063
-    private function extractJoinModelFromQueryParams(
4064
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4065
-        $possible_join_string,
4066
-        $original_query_param,
4067
-        $query_parameter_type
4068
-    ) {
4069
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
-                if ($possible_join_string === '') {
4074
-                    // nothing left to $query_param
4075
-                    // we should actually end in a field name, not a model like this!
4076
-                    throw new EE_Error(
4077
-                        sprintf(
4078
-                            esc_html__(
4079
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
-                                "event_espresso"
4081
-                            ),
4082
-                            $possible_join_string,
4083
-                            $query_parameter_type,
4084
-                            get_class($this),
4085
-                            $valid_related_model_name
4086
-                        )
4087
-                    );
4088
-                }
4089
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
-                $related_model_obj->_extract_related_model_info_from_query_param(
4091
-                    $possible_join_string,
4092
-                    $query_info_carrier,
4093
-                    $query_parameter_type,
4094
-                    $original_query_param
4095
-                );
4096
-                return true;
4097
-            }
4098
-            if ($possible_join_string === $valid_related_model_name) {
4099
-                $this->_add_join_to_model(
4100
-                    $valid_related_model_name,
4101
-                    $query_info_carrier,
4102
-                    $original_query_param
4103
-                );
4104
-                return true;
4105
-            }
4106
-        }
4107
-        return false;
4108
-    }
4109
-
4110
-
4111
-    /**
4112
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
-    {
4118
-        if (
4119
-            $this->_custom_selections instanceof CustomSelects
4120
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
-            )
4123
-        ) {
4124
-            $original_selects = $this->_custom_selections->originalSelects();
4125
-            foreach ($original_selects as $alias => $select_configuration) {
4126
-                $this->extractJoinModelFromQueryParams(
4127
-                    $query_info_carrier,
4128
-                    $select_configuration[0],
4129
-                    $select_configuration[0],
4130
-                    'custom_selects'
4131
-                );
4132
-            }
4133
-        }
4134
-    }
4135
-
4136
-
4137
-
4138
-    /**
4139
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
-     * and store it on $passed_in_query_info
4141
-     *
4142
-     * @param string                      $model_name
4143
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4145
-     *                                                          model and $model_name. Eg, if we are querying Event,
4146
-     *                                                          and are adding a join to 'Payment' with the original
4147
-     *                                                          query param key
4148
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4150
-     *                                                          Payment wants to add default query params so that it
4151
-     *                                                          will know what models to prepend onto its default query
4152
-     *                                                          params or in case it wants to rename tables (in case
4153
-     *                                                          there are multiple joins to the same table)
4154
-     * @return void
4155
-     * @throws EE_Error
4156
-     */
4157
-    private function _add_join_to_model(
4158
-        $model_name,
4159
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
-        $original_query_param
4161
-    ) {
4162
-        $relation_obj = $this->related_settings_for($model_name);
4163
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
-        // check if the relation is HABTM, because then we're essentially doing two joins
4165
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4167
-            $join_model_obj = $relation_obj->get_join_model();
4168
-            // replace the model specified with the join model for this relation chain, whi
4169
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
-                $model_name,
4171
-                $join_model_obj->get_this_model_name(),
4172
-                $model_relation_chain
4173
-            );
4174
-            $passed_in_query_info->merge(
4175
-                new EE_Model_Query_Info_Carrier(
4176
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
-                )
4179
-            );
4180
-        }
4181
-        // now just join to the other table pointed to by the relation object, and add its data types
4182
-        $passed_in_query_info->merge(
4183
-            new EE_Model_Query_Info_Carrier(
4184
-                array($model_relation_chain => $model_name),
4185
-                $relation_obj->get_join_statement($model_relation_chain)
4186
-            )
4187
-        );
4188
-    }
4189
-
4190
-
4191
-
4192
-    /**
4193
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
-     *
4195
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
-     * @return string of SQL
4197
-     * @throws EE_Error
4198
-     */
4199
-    private function _construct_where_clause($where_params)
4200
-    {
4201
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
-        if ($SQL) {
4203
-            return " WHERE " . $SQL;
4204
-        }
4205
-        return '';
4206
-    }
4207
-
4208
-
4209
-
4210
-    /**
4211
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
-     * and should be passed HAVING parameters, not WHERE parameters
4213
-     *
4214
-     * @param array $having_params
4215
-     * @return string
4216
-     * @throws EE_Error
4217
-     */
4218
-    private function _construct_having_clause($having_params)
4219
-    {
4220
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
-        if ($SQL) {
4222
-            return " HAVING " . $SQL;
4223
-        }
4224
-        return '';
4225
-    }
4226
-
4227
-
4228
-    /**
4229
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
-     * Event_Meta.meta_value = 'foo'))"
4231
-     *
4232
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
-     * @throws EE_Error
4235
-     * @return string of SQL
4236
-     */
4237
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
-    {
4239
-        $where_clauses = array();
4240
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
-                switch ($query_param) {
4244
-                    case 'not':
4245
-                    case 'NOT':
4246
-                        $where_clauses[] = "! ("
4247
-                                           . $this->_construct_condition_clause_recursive(
4248
-                                               $op_and_value_or_sub_condition,
4249
-                                               $glue
4250
-                                           )
4251
-                                           . ")";
4252
-                        break;
4253
-                    case 'and':
4254
-                    case 'AND':
4255
-                        $where_clauses[] = " ("
4256
-                                           . $this->_construct_condition_clause_recursive(
4257
-                                               $op_and_value_or_sub_condition,
4258
-                                               ' AND '
4259
-                                           )
4260
-                                           . ")";
4261
-                        break;
4262
-                    case 'or':
4263
-                    case 'OR':
4264
-                        $where_clauses[] = " ("
4265
-                                           . $this->_construct_condition_clause_recursive(
4266
-                                               $op_and_value_or_sub_condition,
4267
-                                               ' OR '
4268
-                                           )
4269
-                                           . ")";
4270
-                        break;
4271
-                }
4272
-            } else {
4273
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4274
-                // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4276
-                    if ($this->_custom_selections instanceof CustomSelects) {
4277
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
-                    } else {
4279
-                        throw new EE_Error(sprintf(__(
4280
-                            "%s is neither a valid model field name, nor a custom selection",
4281
-                            "event_espresso"
4282
-                        ), $query_param));
4283
-                    }
4284
-                }
4285
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
-            }
4288
-        }
4289
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4290
-    }
4291
-
4292
-
4293
-
4294
-    /**
4295
-     * Takes the input parameter and extract the table name (alias) and column name
4296
-     *
4297
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
-     * @throws EE_Error
4299
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
-     */
4301
-    private function _deduce_column_name_from_query_param($query_param)
4302
-    {
4303
-        $field = $this->_deduce_field_from_query_param($query_param);
4304
-        if ($field) {
4305
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
-                $field->get_model_name(),
4307
-                $query_param
4308
-            );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4310
-        }
4311
-        if (
4312
-            $this->_custom_selections instanceof CustomSelects
4313
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
-        ) {
4315
-            // maybe it's custom selection item?
4316
-            // if so, just use it as the "column name"
4317
-            return $query_param;
4318
-        }
4319
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
-            ? implode(',', $this->_custom_selections->columnAliases())
4321
-            : '';
4322
-        throw new EE_Error(
4323
-            sprintf(
4324
-                __(
4325
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4326
-                    "event_espresso"
4327
-                ),
4328
-                $query_param,
4329
-                $custom_select_aliases
4330
-            )
4331
-        );
4332
-    }
4333
-
4334
-
4335
-
4336
-    /**
4337
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
-     *
4342
-     * @param string $condition_query_param_key
4343
-     * @return string
4344
-     */
4345
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
-    {
4347
-        $pos_of_star = strpos($condition_query_param_key, '*');
4348
-        if ($pos_of_star === false) {
4349
-            return $condition_query_param_key;
4350
-        }
4351
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
-        return $condition_query_param_sans_star;
4353
-    }
4354
-
4355
-
4356
-
4357
-    /**
4358
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
-     *
4360
-     * @param                            mixed      array | string    $op_and_value
4361
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
-     * @throws EE_Error
4363
-     * @return string
4364
-     */
4365
-    private function _construct_op_and_value($op_and_value, $field_obj)
4366
-    {
4367
-        if (is_array($op_and_value)) {
4368
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4370
-                $php_array_like_string = array();
4371
-                foreach ($op_and_value as $key => $value) {
4372
-                    $php_array_like_string[] = "$key=>$value";
4373
-                }
4374
-                throw new EE_Error(
4375
-                    sprintf(
4376
-                        __(
4377
-                            "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))",
4378
-                            "event_espresso"
4379
-                        ),
4380
-                        implode(",", $php_array_like_string)
4381
-                    )
4382
-                );
4383
-            }
4384
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
-        } else {
4386
-            $operator = '=';
4387
-            $value = $op_and_value;
4388
-        }
4389
-        // check to see if the value is actually another field
4390
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
-        }
4393
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
-            // in this case, the value should be an array, or at least a comma-separated list
4395
-            // it will need to handle a little differently
4396
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4399
-        }
4400
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
-            // the value should be an array with count of two.
4402
-            if (count($value) !== 2) {
4403
-                throw new EE_Error(
4404
-                    sprintf(
4405
-                        __(
4406
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
-                            'event_espresso'
4408
-                        ),
4409
-                        "BETWEEN"
4410
-                    )
4411
-                );
4412
-            }
4413
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4415
-        }
4416
-        if (in_array($operator, $this->valid_null_style_operators())) {
4417
-            if ($value !== null) {
4418
-                throw new EE_Error(
4419
-                    sprintf(
4420
-                        __(
4421
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
-                            "event_espresso"
4423
-                        ),
4424
-                        $value,
4425
-                        $operator
4426
-                    )
4427
-                );
4428
-            }
4429
-            return $operator;
4430
-        }
4431
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
-            // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
-        }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
-        }
4439
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
-            throw new EE_Error(
4441
-                sprintf(
4442
-                    __(
4443
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
-                        'event_espresso'
4445
-                    ),
4446
-                    $operator,
4447
-                    $operator
4448
-                )
4449
-            );
4450
-        }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
-            throw new EE_Error(
4453
-                sprintf(
4454
-                    __(
4455
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
-                        'event_espresso'
4457
-                    ),
4458
-                    $operator,
4459
-                    $operator
4460
-                )
4461
-            );
4462
-        }
4463
-        throw new EE_Error(
4464
-            sprintf(
4465
-                __(
4466
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
-                    "event_espresso"
4468
-                ),
4469
-                http_build_query($op_and_value)
4470
-            )
4471
-        );
4472
-    }
4473
-
4474
-
4475
-
4476
-    /**
4477
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
-     *
4479
-     * @param array                      $values
4480
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
-     *                                              '%s'
4482
-     * @return string
4483
-     * @throws EE_Error
4484
-     */
4485
-    public function _construct_between_value($values, $field_obj)
4486
-    {
4487
-        $cleaned_values = array();
4488
-        foreach ($values as $value) {
4489
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
-        }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
-    }
4493
-
4494
-
4495
-
4496
-    /**
4497
-     * Takes an array or a comma-separated list of $values and cleans them
4498
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4499
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4500
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4501
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4502
-     *
4503
-     * @param mixed                      $values    array or comma-separated string
4504
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4505
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4506
-     * @throws EE_Error
4507
-     */
4508
-    public function _construct_in_value($values, $field_obj)
4509
-    {
4510
-        // check if the value is a CSV list
4511
-        if (is_string($values)) {
4512
-            // in which case, turn it into an array
4513
-            $values = explode(",", $values);
4514
-        }
4515
-        $cleaned_values = array();
4516
-        foreach ($values as $value) {
4517
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4518
-        }
4519
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4520
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4521
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4522
-        if (empty($cleaned_values)) {
4523
-            $all_fields = $this->field_settings();
4524
-            $a_field = array_shift($all_fields);
4525
-            $main_table = $this->_get_main_table();
4526
-            $cleaned_values[] = "SELECT "
4527
-                                . $a_field->get_table_column()
4528
-                                . " FROM "
4529
-                                . $main_table->get_table_name()
4530
-                                . " WHERE FALSE";
4531
-        }
4532
-        return "(" . implode(",", $cleaned_values) . ")";
4533
-    }
4534
-
4535
-
4536
-
4537
-    /**
4538
-     * @param mixed                      $value
4539
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4540
-     * @throws EE_Error
4541
-     * @return false|null|string
4542
-     */
4543
-    private function _wpdb_prepare_using_field($value, $field_obj)
4544
-    {
4545
-        /** @type WPDB $wpdb */
4546
-        global $wpdb;
4547
-        if ($field_obj instanceof EE_Model_Field_Base) {
4548
-            return $wpdb->prepare(
4549
-                $field_obj->get_wpdb_data_type(),
4550
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4551
-            );
4552
-        } //$field_obj should really just be a data type
4553
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4554
-            throw new EE_Error(
4555
-                sprintf(
4556
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4557
-                    $field_obj,
4558
-                    implode(",", $this->_valid_wpdb_data_types)
4559
-                )
4560
-            );
4561
-        }
4562
-        return $wpdb->prepare($field_obj, $value);
4563
-    }
4564
-
4565
-
4566
-
4567
-    /**
4568
-     * Takes the input parameter and finds the model field that it indicates.
4569
-     *
4570
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4571
-     * @throws EE_Error
4572
-     * @return EE_Model_Field_Base
4573
-     */
4574
-    protected function _deduce_field_from_query_param($query_param_name)
4575
-    {
4576
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4577
-        // which will help us find the database table and column
4578
-        $query_param_parts = explode(".", $query_param_name);
4579
-        if (empty($query_param_parts)) {
4580
-            throw new EE_Error(sprintf(__(
4581
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4582
-                'event_espresso'
4583
-            ), $query_param_name));
4584
-        }
4585
-        $number_of_parts = count($query_param_parts);
4586
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4587
-        if ($number_of_parts === 1) {
4588
-            $field_name = $last_query_param_part;
4589
-            $model_obj = $this;
4590
-        } else {// $number_of_parts >= 2
4591
-            // the last part is the column name, and there are only 2parts. therefore...
4592
-            $field_name = $last_query_param_part;
4593
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4594
-        }
4595
-        try {
4596
-            return $model_obj->field_settings_for($field_name);
4597
-        } catch (EE_Error $e) {
4598
-            return null;
4599
-        }
4600
-    }
4601
-
4602
-
4603
-
4604
-    /**
4605
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4606
-     * alias and column which corresponds to it
4607
-     *
4608
-     * @param string $field_name
4609
-     * @throws EE_Error
4610
-     * @return string
4611
-     */
4612
-    public function _get_qualified_column_for_field($field_name)
4613
-    {
4614
-        $all_fields = $this->field_settings();
4615
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4616
-        if ($field) {
4617
-            return $field->get_qualified_column();
4618
-        }
4619
-        throw new EE_Error(
4620
-            sprintf(
4621
-                __(
4622
-                    "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.",
4623
-                    'event_espresso'
4624
-                ),
4625
-                $field_name,
4626
-                get_class($this)
4627
-            )
4628
-        );
4629
-    }
4630
-
4631
-
4632
-
4633
-    /**
4634
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4635
-     * Example usage:
4636
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4637
-     *      array(),
4638
-     *      ARRAY_A,
4639
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4640
-     *  );
4641
-     * is equivalent to
4642
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4643
-     * and
4644
-     *  EEM_Event::instance()->get_all_wpdb_results(
4645
-     *      array(
4646
-     *          array(
4647
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4648
-     *          ),
4649
-     *          ARRAY_A,
4650
-     *          implode(
4651
-     *              ', ',
4652
-     *              array_merge(
4653
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4654
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4655
-     *              )
4656
-     *          )
4657
-     *      )
4658
-     *  );
4659
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4660
-     *
4661
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4662
-     *                                            and the one whose fields you are selecting for example: when querying
4663
-     *                                            tickets model and selecting fields from the tickets model you would
4664
-     *                                            leave this parameter empty, because no models are needed to join
4665
-     *                                            between the queried model and the selected one. Likewise when
4666
-     *                                            querying the datetime model and selecting fields from the tickets
4667
-     *                                            model, it would also be left empty, because there is a direct
4668
-     *                                            relation from datetimes to tickets, so no model is needed to join
4669
-     *                                            them together. However, when querying from the event model and
4670
-     *                                            selecting fields from the ticket model, you should provide the string
4671
-     *                                            'Datetime', indicating that the event model must first join to the
4672
-     *                                            datetime model in order to find its relation to ticket model.
4673
-     *                                            Also, when querying from the venue model and selecting fields from
4674
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4675
-     *                                            indicating you need to join the venue model to the event model,
4676
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4677
-     *                                            This string is used to deduce the prefix that gets added onto the
4678
-     *                                            models' tables qualified columns
4679
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4680
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4681
-     *                                            qualified column names
4682
-     * @return array|string
4683
-     */
4684
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4685
-    {
4686
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4687
-        $qualified_columns = array();
4688
-        foreach ($this->field_settings() as $field_name => $field) {
4689
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4690
-        }
4691
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4692
-    }
4693
-
4694
-
4695
-
4696
-    /**
4697
-     * constructs the select use on special limit joins
4698
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4699
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4700
-     * (as that is typically where the limits would be set).
4701
-     *
4702
-     * @param  string       $table_alias The table the select is being built for
4703
-     * @param  mixed|string $limit       The limit for this select
4704
-     * @return string                The final select join element for the query.
4705
-     */
4706
-    public function _construct_limit_join_select($table_alias, $limit)
4707
-    {
4708
-        $SQL = '';
4709
-        foreach ($this->_tables as $table_obj) {
4710
-            if ($table_obj instanceof EE_Primary_Table) {
4711
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4712
-                    ? $table_obj->get_select_join_limit($limit)
4713
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4714
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4715
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4716
-                    ? $table_obj->get_select_join_limit_join($limit)
4717
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4718
-            }
4719
-        }
4720
-        return $SQL;
4721
-    }
4722
-
4723
-
4724
-
4725
-    /**
4726
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4727
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4728
-     *
4729
-     * @return string SQL
4730
-     * @throws EE_Error
4731
-     */
4732
-    public function _construct_internal_join()
4733
-    {
4734
-        $SQL = $this->_get_main_table()->get_table_sql();
4735
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4736
-        return $SQL;
4737
-    }
4738
-
4739
-
4740
-
4741
-    /**
4742
-     * Constructs the SQL for joining all the tables on this model.
4743
-     * Normally $alias should be the primary table's alias, but in cases where
4744
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4745
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4746
-     * alias, this will construct SQL like:
4747
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4748
-     * With $alias being a secondary table's alias, this will construct SQL like:
4749
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4750
-     *
4751
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4752
-     * @return string
4753
-     */
4754
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4755
-    {
4756
-        $SQL = '';
4757
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4758
-        foreach ($this->_tables as $table_obj) {
4759
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4760
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4761
-                    // so we're joining to this table, meaning the table is already in
4762
-                    // the FROM statement, BUT the primary table isn't. So we want
4763
-                    // to add the inverse join sql
4764
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4765
-                } else {
4766
-                    // just add a regular JOIN to this table from the primary table
4767
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4768
-                }
4769
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4770
-        }
4771
-        return $SQL;
4772
-    }
4773
-
4774
-
4775
-
4776
-    /**
4777
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4778
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4779
-     * their data type (eg, '%s', '%d', etc)
4780
-     *
4781
-     * @return array
4782
-     */
4783
-    public function _get_data_types()
4784
-    {
4785
-        $data_types = array();
4786
-        foreach ($this->field_settings() as $field_obj) {
4787
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4788
-            /** @var $field_obj EE_Model_Field_Base */
4789
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4790
-        }
4791
-        return $data_types;
4792
-    }
4793
-
4794
-
4795
-
4796
-    /**
4797
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4798
-     *
4799
-     * @param string $model_name
4800
-     * @throws EE_Error
4801
-     * @return EEM_Base
4802
-     */
4803
-    public function get_related_model_obj($model_name)
4804
-    {
4805
-        $model_classname = "EEM_" . $model_name;
4806
-        if (! class_exists($model_classname)) {
4807
-            throw new EE_Error(sprintf(__(
4808
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4809
-                'event_espresso'
4810
-            ), $model_name, $model_classname));
4811
-        }
4812
-        return call_user_func($model_classname . "::instance");
4813
-    }
4814
-
4815
-
4816
-
4817
-    /**
4818
-     * Returns the array of EE_ModelRelations for this model.
4819
-     *
4820
-     * @return EE_Model_Relation_Base[]
4821
-     */
4822
-    public function relation_settings()
4823
-    {
4824
-        return $this->_model_relations;
4825
-    }
4826
-
4827
-
4828
-
4829
-    /**
4830
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4831
-     * because without THOSE models, this model probably doesn't have much purpose.
4832
-     * (Eg, without an event, datetimes have little purpose.)
4833
-     *
4834
-     * @return EE_Belongs_To_Relation[]
4835
-     */
4836
-    public function belongs_to_relations()
4837
-    {
4838
-        $belongs_to_relations = array();
4839
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4840
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4841
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4842
-            }
4843
-        }
4844
-        return $belongs_to_relations;
4845
-    }
4846
-
4847
-
4848
-
4849
-    /**
4850
-     * Returns the specified EE_Model_Relation, or throws an exception
4851
-     *
4852
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4853
-     * @throws EE_Error
4854
-     * @return EE_Model_Relation_Base
4855
-     */
4856
-    public function related_settings_for($relation_name)
4857
-    {
4858
-        $relatedModels = $this->relation_settings();
4859
-        if (! array_key_exists($relation_name, $relatedModels)) {
4860
-            throw new EE_Error(
4861
-                sprintf(
4862
-                    __(
4863
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4864
-                        'event_espresso'
4865
-                    ),
4866
-                    $relation_name,
4867
-                    $this->_get_class_name(),
4868
-                    implode(', ', array_keys($relatedModels))
4869
-                )
4870
-            );
4871
-        }
4872
-        return $relatedModels[ $relation_name ];
4873
-    }
4874
-
4875
-
4876
-
4877
-    /**
4878
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4879
-     * fields
4880
-     *
4881
-     * @param string $fieldName
4882
-     * @param boolean $include_db_only_fields
4883
-     * @throws EE_Error
4884
-     * @return EE_Model_Field_Base
4885
-     */
4886
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4887
-    {
4888
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4889
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4890
-            throw new EE_Error(sprintf(
4891
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4892
-                $fieldName,
4893
-                get_class($this)
4894
-            ));
4895
-        }
4896
-        return $fieldSettings[ $fieldName ];
4897
-    }
4898
-
4899
-
4900
-
4901
-    /**
4902
-     * Checks if this field exists on this model
4903
-     *
4904
-     * @param string $fieldName a key in the model's _field_settings array
4905
-     * @return boolean
4906
-     */
4907
-    public function has_field($fieldName)
4908
-    {
4909
-        $fieldSettings = $this->field_settings(true);
4910
-        if (isset($fieldSettings[ $fieldName ])) {
4911
-            return true;
4912
-        }
4913
-        return false;
4914
-    }
4915
-
4916
-
4917
-
4918
-    /**
4919
-     * Returns whether or not this model has a relation to the specified model
4920
-     *
4921
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4922
-     * @return boolean
4923
-     */
4924
-    public function has_relation($relation_name)
4925
-    {
4926
-        $relations = $this->relation_settings();
4927
-        if (isset($relations[ $relation_name ])) {
4928
-            return true;
4929
-        }
4930
-        return false;
4931
-    }
4932
-
4933
-
4934
-
4935
-    /**
4936
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4937
-     * Eg, on EE_Answer that would be ANS_ID field object
4938
-     *
4939
-     * @param $field_obj
4940
-     * @return boolean
4941
-     */
4942
-    public function is_primary_key_field($field_obj)
4943
-    {
4944
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4945
-    }
4946
-
4947
-
4948
-
4949
-    /**
4950
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4951
-     * Eg, on EE_Answer that would be ANS_ID field object
4952
-     *
4953
-     * @return EE_Model_Field_Base
4954
-     * @throws EE_Error
4955
-     */
4956
-    public function get_primary_key_field()
4957
-    {
4958
-        if ($this->_primary_key_field === null) {
4959
-            foreach ($this->field_settings(true) as $field_obj) {
4960
-                if ($this->is_primary_key_field($field_obj)) {
4961
-                    $this->_primary_key_field = $field_obj;
4962
-                    break;
4963
-                }
4964
-            }
4965
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4966
-                throw new EE_Error(sprintf(
4967
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4968
-                    get_class($this)
4969
-                ));
4970
-            }
4971
-        }
4972
-        return $this->_primary_key_field;
4973
-    }
4974
-
4975
-
4976
-
4977
-    /**
4978
-     * Returns whether or not not there is a primary key on this model.
4979
-     * Internally does some caching.
4980
-     *
4981
-     * @return boolean
4982
-     */
4983
-    public function has_primary_key_field()
4984
-    {
4985
-        if ($this->_has_primary_key_field === null) {
4986
-            try {
4987
-                $this->get_primary_key_field();
4988
-                $this->_has_primary_key_field = true;
4989
-            } catch (EE_Error $e) {
4990
-                $this->_has_primary_key_field = false;
4991
-            }
4992
-        }
4993
-        return $this->_has_primary_key_field;
4994
-    }
4995
-
4996
-
4997
-
4998
-    /**
4999
-     * Finds the first field of type $field_class_name.
5000
-     *
5001
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5002
-     *                                 EE_Foreign_Key_Field, etc
5003
-     * @return EE_Model_Field_Base or null if none is found
5004
-     */
5005
-    public function get_a_field_of_type($field_class_name)
5006
-    {
5007
-        foreach ($this->field_settings() as $field) {
5008
-            if ($field instanceof $field_class_name) {
5009
-                return $field;
5010
-            }
5011
-        }
5012
-        return null;
5013
-    }
5014
-
5015
-
5016
-
5017
-    /**
5018
-     * Gets a foreign key field pointing to model.
5019
-     *
5020
-     * @param string $model_name eg Event, Registration, not EEM_Event
5021
-     * @return EE_Foreign_Key_Field_Base
5022
-     * @throws EE_Error
5023
-     */
5024
-    public function get_foreign_key_to($model_name)
5025
-    {
5026
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5027
-            foreach ($this->field_settings() as $field) {
5028
-                if (
5029
-                    $field instanceof EE_Foreign_Key_Field_Base
5030
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5031
-                ) {
5032
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5033
-                    break;
5034
-                }
5035
-            }
5036
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5037
-                throw new EE_Error(sprintf(__(
5038
-                    "There is no foreign key field pointing to model %s on model %s",
5039
-                    'event_espresso'
5040
-                ), $model_name, get_class($this)));
5041
-            }
5042
-        }
5043
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5044
-    }
5045
-
5046
-
5047
-
5048
-    /**
5049
-     * Gets the table name (including $wpdb->prefix) for the table alias
5050
-     *
5051
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5052
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5053
-     *                            Either one works
5054
-     * @return string
5055
-     */
5056
-    public function get_table_for_alias($table_alias)
5057
-    {
5058
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5059
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5060
-    }
5061
-
5062
-
5063
-
5064
-    /**
5065
-     * Returns a flat array of all field son this model, instead of organizing them
5066
-     * by table_alias as they are in the constructor.
5067
-     *
5068
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5069
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5070
-     */
5071
-    public function field_settings($include_db_only_fields = false)
5072
-    {
5073
-        if ($include_db_only_fields) {
5074
-            if ($this->_cached_fields === null) {
5075
-                $this->_cached_fields = array();
5076
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5077
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5078
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5079
-                    }
5080
-                }
5081
-            }
5082
-            return $this->_cached_fields;
5083
-        }
5084
-        if ($this->_cached_fields_non_db_only === null) {
5085
-            $this->_cached_fields_non_db_only = array();
5086
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5087
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5088
-                    /** @var $field_obj EE_Model_Field_Base */
5089
-                    if (! $field_obj->is_db_only_field()) {
5090
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5091
-                    }
5092
-                }
5093
-            }
5094
-        }
5095
-        return $this->_cached_fields_non_db_only;
5096
-    }
5097
-
5098
-
5099
-
5100
-    /**
5101
-     *        cycle though array of attendees and create objects out of each item
5102
-     *
5103
-     * @access        private
5104
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5105
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5106
-     *                           numerically indexed)
5107
-     * @throws EE_Error
5108
-     */
5109
-    protected function _create_objects($rows = array())
5110
-    {
5111
-        $array_of_objects = array();
5112
-        if (empty($rows)) {
5113
-            return array();
5114
-        }
5115
-        $count_if_model_has_no_primary_key = 0;
5116
-        $has_primary_key = $this->has_primary_key_field();
5117
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5118
-        foreach ((array) $rows as $row) {
5119
-            if (empty($row)) {
5120
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5121
-                return array();
5122
-            }
5123
-            // check if we've already set this object in the results array,
5124
-            // in which case there's no need to process it further (again)
5125
-            if ($has_primary_key) {
5126
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5127
-                    $row,
5128
-                    $primary_key_field->get_qualified_column(),
5129
-                    $primary_key_field->get_table_column()
5130
-                );
5131
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5132
-                    continue;
5133
-                }
5134
-            }
5135
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5136
-            if (! $classInstance) {
5137
-                throw new EE_Error(
5138
-                    sprintf(
5139
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5140
-                        $this->get_this_model_name(),
5141
-                        http_build_query($row)
5142
-                    )
5143
-                );
5144
-            }
5145
-            // set the timezone on the instantiated objects
5146
-            $classInstance->set_timezone($this->_timezone);
5147
-            // make sure if there is any timezone setting present that we set the timezone for the object
5148
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5149
-            $array_of_objects[ $key ] = $classInstance;
5150
-            // also, for all the relations of type BelongsTo, see if we can cache
5151
-            // those related models
5152
-            // (we could do this for other relations too, but if there are conditions
5153
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5154
-            // so it requires a little more thought than just caching them immediately...)
5155
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5156
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5157
-                    // check if this model's INFO is present. If so, cache it on the model
5158
-                    $other_model = $relation_obj->get_other_model();
5159
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5160
-                    // if we managed to make a model object from the results, cache it on the main model object
5161
-                    if ($other_model_obj_maybe) {
5162
-                        // set timezone on these other model objects if they are present
5163
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5164
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5165
-                    }
5166
-                }
5167
-            }
5168
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5169
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5170
-            // the field in the CustomSelects object
5171
-            if ($this->_custom_selections instanceof CustomSelects) {
5172
-                $classInstance->setCustomSelectsValues(
5173
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5174
-                );
5175
-            }
5176
-        }
5177
-        return $array_of_objects;
5178
-    }
5179
-
5180
-
5181
-    /**
5182
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5183
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5184
-     *
5185
-     * @param array $db_results_row
5186
-     * @return array
5187
-     */
5188
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5189
-    {
5190
-        $results = array();
5191
-        if ($this->_custom_selections instanceof CustomSelects) {
5192
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5193
-                if (isset($db_results_row[ $alias ])) {
5194
-                    $results[ $alias ] = $this->convertValueToDataType(
5195
-                        $db_results_row[ $alias ],
5196
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5197
-                    );
5198
-                }
5199
-            }
5200
-        }
5201
-        return $results;
5202
-    }
5203
-
5204
-
5205
-    /**
5206
-     * This will set the value for the given alias
5207
-     * @param string $value
5208
-     * @param string $datatype (one of %d, %s, %f)
5209
-     * @return int|string|float (int for %d, string for %s, float for %f)
5210
-     */
5211
-    protected function convertValueToDataType($value, $datatype)
5212
-    {
5213
-        switch ($datatype) {
5214
-            case '%f':
5215
-                return (float) $value;
5216
-            case '%d':
5217
-                return (int) $value;
5218
-            default:
5219
-                return (string) $value;
5220
-        }
5221
-    }
5222
-
5223
-
5224
-    /**
5225
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5226
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5227
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5228
-     * object (as set in the model_field!).
5229
-     *
5230
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5231
-     */
5232
-    public function create_default_object()
5233
-    {
5234
-        $this_model_fields_and_values = array();
5235
-        // setup the row using default values;
5236
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5237
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5238
-        }
5239
-        $className = $this->_get_class_name();
5240
-        $classInstance = EE_Registry::instance()
5241
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5242
-        return $classInstance;
5243
-    }
5244
-
5245
-
5246
-
5247
-    /**
5248
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5249
-     *                             or an stdClass where each property is the name of a column,
5250
-     * @return EE_Base_Class
5251
-     * @throws EE_Error
5252
-     */
5253
-    public function instantiate_class_from_array_or_object($cols_n_values)
5254
-    {
5255
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5256
-            $cols_n_values = get_object_vars($cols_n_values);
5257
-        }
5258
-        $primary_key = null;
5259
-        // make sure the array only has keys that are fields/columns on this model
5260
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5261
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5262
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5263
-        }
5264
-        $className = $this->_get_class_name();
5265
-        // check we actually found results that we can use to build our model object
5266
-        // if not, return null
5267
-        if ($this->has_primary_key_field()) {
5268
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5269
-                return null;
5270
-            }
5271
-        } elseif ($this->unique_indexes()) {
5272
-            $first_column = reset($this_model_fields_n_values);
5273
-            if (empty($first_column)) {
5274
-                return null;
5275
-            }
5276
-        }
5277
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5278
-        if ($primary_key) {
5279
-            $classInstance = $this->get_from_entity_map($primary_key);
5280
-            if (! $classInstance) {
5281
-                $classInstance = EE_Registry::instance()
5282
-                                            ->load_class(
5283
-                                                $className,
5284
-                                                array($this_model_fields_n_values, $this->_timezone),
5285
-                                                true,
5286
-                                                false
5287
-                                            );
5288
-                // add this new object to the entity map
5289
-                $classInstance = $this->add_to_entity_map($classInstance);
5290
-            }
5291
-        } else {
5292
-            $classInstance = EE_Registry::instance()
5293
-                                        ->load_class(
5294
-                                            $className,
5295
-                                            array($this_model_fields_n_values, $this->_timezone),
5296
-                                            true,
5297
-                                            false
5298
-                                        );
5299
-        }
5300
-        return $classInstance;
5301
-    }
5302
-
5303
-
5304
-
5305
-    /**
5306
-     * Gets the model object from the  entity map if it exists
5307
-     *
5308
-     * @param int|string $id the ID of the model object
5309
-     * @return EE_Base_Class
5310
-     */
5311
-    public function get_from_entity_map($id)
5312
-    {
5313
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5314
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5315
-    }
5316
-
5317
-
5318
-
5319
-    /**
5320
-     * add_to_entity_map
5321
-     * Adds the object to the model's entity mappings
5322
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5323
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5324
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5325
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5326
-     *        then this method should be called immediately after the update query
5327
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5328
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5329
-     *
5330
-     * @param    EE_Base_Class $object
5331
-     * @throws EE_Error
5332
-     * @return \EE_Base_Class
5333
-     */
5334
-    public function add_to_entity_map(EE_Base_Class $object)
5335
-    {
5336
-        $className = $this->_get_class_name();
5337
-        if (! $object instanceof $className) {
5338
-            throw new EE_Error(sprintf(
5339
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5340
-                is_object($object) ? get_class($object) : $object,
5341
-                $className
5342
-            ));
5343
-        }
5344
-        /** @var $object EE_Base_Class */
5345
-        if (! $object->ID()) {
5346
-            throw new EE_Error(sprintf(__(
5347
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5348
-                "event_espresso"
5349
-            ), get_class($this)));
5350
-        }
5351
-        // double check it's not already there
5352
-        $classInstance = $this->get_from_entity_map($object->ID());
5353
-        if ($classInstance) {
5354
-            return $classInstance;
5355
-        }
5356
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5357
-        return $object;
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5364
-     * if no identifier is provided, then the entire entity map is emptied
5365
-     *
5366
-     * @param int|string $id the ID of the model object
5367
-     * @return boolean
5368
-     */
5369
-    public function clear_entity_map($id = null)
5370
-    {
5371
-        if (empty($id)) {
5372
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5373
-            return true;
5374
-        }
5375
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5376
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5377
-            return true;
5378
-        }
5379
-        return false;
5380
-    }
5381
-
5382
-
5383
-
5384
-    /**
5385
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5386
-     * Given an array where keys are column (or column alias) names and values,
5387
-     * returns an array of their corresponding field names and database values
5388
-     *
5389
-     * @param array $cols_n_values
5390
-     * @return array
5391
-     */
5392
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5393
-    {
5394
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5395
-    }
5396
-
5397
-
5398
-
5399
-    /**
5400
-     * _deduce_fields_n_values_from_cols_n_values
5401
-     * Given an array where keys are column (or column alias) names and values,
5402
-     * returns an array of their corresponding field names and database values
5403
-     *
5404
-     * @param string $cols_n_values
5405
-     * @return array
5406
-     */
5407
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5408
-    {
5409
-        $this_model_fields_n_values = array();
5410
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5411
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5412
-                $cols_n_values,
5413
-                $table_obj->get_fully_qualified_pk_column(),
5414
-                $table_obj->get_pk_column()
5415
-            );
5416
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5417
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5418
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5419
-                    if (! $field_obj->is_db_only_field()) {
5420
-                        // prepare field as if its coming from db
5421
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5422
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5423
-                    }
5424
-                }
5425
-            } else {
5426
-                // the table's rows existed. Use their values
5427
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5428
-                    if (! $field_obj->is_db_only_field()) {
5429
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5430
-                            $cols_n_values,
5431
-                            $field_obj->get_qualified_column(),
5432
-                            $field_obj->get_table_column()
5433
-                        );
5434
-                    }
5435
-                }
5436
-            }
5437
-        }
5438
-        return $this_model_fields_n_values;
5439
-    }
5440
-
5441
-
5442
-    /**
5443
-     * @param $cols_n_values
5444
-     * @param $qualified_column
5445
-     * @param $regular_column
5446
-     * @return null
5447
-     * @throws EE_Error
5448
-     * @throws ReflectionException
5449
-     */
5450
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5451
-    {
5452
-        $value = null;
5453
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5454
-        // does the field on the model relate to this column retrieved from the db?
5455
-        // or is it a db-only field? (not relating to the model)
5456
-        if (isset($cols_n_values[ $qualified_column ])) {
5457
-            $value = $cols_n_values[ $qualified_column ];
5458
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5459
-            $value = $cols_n_values[ $regular_column ];
5460
-        } elseif (! empty($this->foreign_key_aliases)) {
5461
-            // no PK?  ok check if there is a foreign key alias set for this table
5462
-            // then check if that alias exists in the incoming data
5463
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5464
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5465
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5466
-                    $value = $cols_n_values[ $FK_alias ];
5467
-                    [$pk_class] = explode('.', $PK_column);
5468
-                    $pk_model_name = "EEM_{$pk_class}";
5469
-                    /** @var EEM_Base $pk_model */
5470
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5471
-                    if ($pk_model instanceof EEM_Base) {
5472
-                        // make sure object is pulled from db and added to entity map
5473
-                        $pk_model->get_one_by_ID($value);
5474
-                    }
5475
-                    break;
5476
-                }
5477
-            }
5478
-        }
5479
-        return $value;
5480
-    }
5481
-
5482
-
5483
-
5484
-    /**
5485
-     * refresh_entity_map_from_db
5486
-     * Makes sure the model object in the entity map at $id assumes the values
5487
-     * of the database (opposite of EE_base_Class::save())
5488
-     *
5489
-     * @param int|string $id
5490
-     * @return EE_Base_Class
5491
-     * @throws EE_Error
5492
-     */
5493
-    public function refresh_entity_map_from_db($id)
5494
-    {
5495
-        $obj_in_map = $this->get_from_entity_map($id);
5496
-        if ($obj_in_map) {
5497
-            $wpdb_results = $this->_get_all_wpdb_results(
5498
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5499
-            );
5500
-            if ($wpdb_results && is_array($wpdb_results)) {
5501
-                $one_row = reset($wpdb_results);
5502
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5503
-                    $obj_in_map->set_from_db($field_name, $db_value);
5504
-                }
5505
-                // clear the cache of related model objects
5506
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5507
-                    $obj_in_map->clear_cache($relation_name, null, true);
5508
-                }
5509
-            }
5510
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5511
-            return $obj_in_map;
5512
-        }
5513
-        return $this->get_one_by_ID($id);
5514
-    }
5515
-
5516
-
5517
-
5518
-    /**
5519
-     * refresh_entity_map_with
5520
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5521
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5522
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5523
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5524
-     *
5525
-     * @param int|string    $id
5526
-     * @param EE_Base_Class $replacing_model_obj
5527
-     * @return \EE_Base_Class
5528
-     * @throws EE_Error
5529
-     */
5530
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5531
-    {
5532
-        $obj_in_map = $this->get_from_entity_map($id);
5533
-        if ($obj_in_map) {
5534
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5535
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5536
-                    $obj_in_map->set($field_name, $value);
5537
-                }
5538
-                // make the model object in the entity map's cache match the $replacing_model_obj
5539
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5540
-                    $obj_in_map->clear_cache($relation_name, null, true);
5541
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5542
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5543
-                    }
5544
-                }
5545
-            }
5546
-            return $obj_in_map;
5547
-        }
5548
-        $this->add_to_entity_map($replacing_model_obj);
5549
-        return $replacing_model_obj;
5550
-    }
5551
-
5552
-
5553
-
5554
-    /**
5555
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5556
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5557
-     * require_once($this->_getClassName().".class.php");
5558
-     *
5559
-     * @return string
5560
-     */
5561
-    private function _get_class_name()
5562
-    {
5563
-        return "EE_" . $this->get_this_model_name();
5564
-    }
5565
-
5566
-
5567
-
5568
-    /**
5569
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5570
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5571
-     * it would be 'Events'.
5572
-     *
5573
-     * @param int $quantity
5574
-     * @return string
5575
-     */
5576
-    public function item_name($quantity = 1)
5577
-    {
5578
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5579
-    }
5580
-
5581
-
5582
-
5583
-    /**
5584
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5585
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5586
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5587
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5588
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5589
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5590
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5591
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5592
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5593
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5594
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5595
-     *        return $previousReturnValue.$returnString;
5596
-     * }
5597
-     * require('EEM_Answer.model.php');
5598
-     * $answer=EEM_Answer::instance();
5599
-     * echo $answer->my_callback('monkeys',100);
5600
-     * //will output "you called my_callback! and passed args:monkeys,100"
5601
-     *
5602
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5603
-     * @param array  $args       array of original arguments passed to the function
5604
-     * @throws EE_Error
5605
-     * @return mixed whatever the plugin which calls add_filter decides
5606
-     */
5607
-    public function __call($methodName, $args)
5608
-    {
5609
-        $className = get_class($this);
5610
-        $tagName = "FHEE__{$className}__{$methodName}";
5611
-        if (! has_filter($tagName)) {
5612
-            throw new EE_Error(
5613
-                sprintf(
5614
-                    __(
5615
-                        '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 );',
5616
-                        'event_espresso'
5617
-                    ),
5618
-                    $methodName,
5619
-                    $className,
5620
-                    $tagName,
5621
-                    '<br />'
5622
-                )
5623
-            );
5624
-        }
5625
-        return apply_filters($tagName, null, $this, $args);
5626
-    }
5627
-
5628
-
5629
-
5630
-    /**
5631
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5632
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5633
-     *
5634
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5635
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5636
-     *                                                       the object's class name
5637
-     *                                                       or object's ID
5638
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5639
-     *                                                       exists in the database. If it does not, we add it
5640
-     * @throws EE_Error
5641
-     * @return EE_Base_Class
5642
-     */
5643
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5644
-    {
5645
-        $className = $this->_get_class_name();
5646
-        if ($base_class_obj_or_id instanceof $className) {
5647
-            $model_object = $base_class_obj_or_id;
5648
-        } else {
5649
-            $primary_key_field = $this->get_primary_key_field();
5650
-            if (
5651
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5652
-                && (
5653
-                    is_int($base_class_obj_or_id)
5654
-                    || is_string($base_class_obj_or_id)
5655
-                )
5656
-            ) {
5657
-                // assume it's an ID.
5658
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5659
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5660
-            } elseif (
5661
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5662
-                && is_string($base_class_obj_or_id)
5663
-            ) {
5664
-                // assume its a string representation of the object
5665
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5666
-            } else {
5667
-                throw new EE_Error(
5668
-                    sprintf(
5669
-                        __(
5670
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5671
-                            'event_espresso'
5672
-                        ),
5673
-                        $base_class_obj_or_id,
5674
-                        $this->_get_class_name(),
5675
-                        print_r($base_class_obj_or_id, true)
5676
-                    )
5677
-                );
5678
-            }
5679
-        }
5680
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5681
-            $model_object->save();
5682
-        }
5683
-        return $model_object;
5684
-    }
5685
-
5686
-
5687
-
5688
-    /**
5689
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5690
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5691
-     * returns it ID.
5692
-     *
5693
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5694
-     * @return int|string depending on the type of this model object's ID
5695
-     * @throws EE_Error
5696
-     */
5697
-    public function ensure_is_ID($base_class_obj_or_id)
5698
-    {
5699
-        $className = $this->_get_class_name();
5700
-        if ($base_class_obj_or_id instanceof $className) {
5701
-            /** @var $base_class_obj_or_id EE_Base_Class */
5702
-            $id = $base_class_obj_or_id->ID();
5703
-        } elseif (is_int($base_class_obj_or_id)) {
5704
-            // assume it's an ID
5705
-            $id = $base_class_obj_or_id;
5706
-        } elseif (is_string($base_class_obj_or_id)) {
5707
-            // assume its a string representation of the object
5708
-            $id = $base_class_obj_or_id;
5709
-        } else {
5710
-            throw new EE_Error(sprintf(
5711
-                __(
5712
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5713
-                    'event_espresso'
5714
-                ),
5715
-                $base_class_obj_or_id,
5716
-                $this->_get_class_name(),
5717
-                print_r($base_class_obj_or_id, true)
5718
-            ));
5719
-        }
5720
-        return $id;
5721
-    }
5722
-
5723
-
5724
-
5725
-    /**
5726
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5727
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5728
-     * been sanitized and converted into the appropriate domain.
5729
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5730
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5731
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5732
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5733
-     * $EVT = EEM_Event::instance(); $old_setting =
5734
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5735
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5736
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5737
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5738
-     *
5739
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5740
-     * @return void
5741
-     */
5742
-    public function assume_values_already_prepared_by_model_object(
5743
-        $values_already_prepared = self::not_prepared_by_model_object
5744
-    ) {
5745
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5746
-    }
5747
-
5748
-
5749
-
5750
-    /**
5751
-     * Read comments for assume_values_already_prepared_by_model_object()
5752
-     *
5753
-     * @return int
5754
-     */
5755
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5756
-    {
5757
-        return $this->_values_already_prepared_by_model_object;
5758
-    }
5759
-
5760
-
5761
-
5762
-    /**
5763
-     * Gets all the indexes on this model
5764
-     *
5765
-     * @return EE_Index[]
5766
-     */
5767
-    public function indexes()
5768
-    {
5769
-        return $this->_indexes;
5770
-    }
5771
-
5772
-
5773
-
5774
-    /**
5775
-     * Gets all the Unique Indexes on this model
5776
-     *
5777
-     * @return EE_Unique_Index[]
5778
-     */
5779
-    public function unique_indexes()
5780
-    {
5781
-        $unique_indexes = array();
5782
-        foreach ($this->_indexes as $name => $index) {
5783
-            if ($index instanceof EE_Unique_Index) {
5784
-                $unique_indexes [ $name ] = $index;
5785
-            }
5786
-        }
5787
-        return $unique_indexes;
5788
-    }
5789
-
5790
-
5791
-
5792
-    /**
5793
-     * Gets all the fields which, when combined, make the primary key.
5794
-     * This is usually just an array with 1 element (the primary key), but in cases
5795
-     * where there is no primary key, it's a combination of fields as defined
5796
-     * on a primary index
5797
-     *
5798
-     * @return EE_Model_Field_Base[] indexed by the field's name
5799
-     * @throws EE_Error
5800
-     */
5801
-    public function get_combined_primary_key_fields()
5802
-    {
5803
-        foreach ($this->indexes() as $index) {
5804
-            if ($index instanceof EE_Primary_Key_Index) {
5805
-                return $index->fields();
5806
-            }
5807
-        }
5808
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5809
-    }
5810
-
5811
-
5812
-
5813
-    /**
5814
-     * Used to build a primary key string (when the model has no primary key),
5815
-     * which can be used a unique string to identify this model object.
5816
-     *
5817
-     * @param array $fields_n_values keys are field names, values are their values.
5818
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5819
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5820
-     *                               before passing it to this function (that will convert it from columns-n-values
5821
-     *                               to field-names-n-values).
5822
-     * @return string
5823
-     * @throws EE_Error
5824
-     */
5825
-    public function get_index_primary_key_string($fields_n_values)
5826
-    {
5827
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5828
-            $fields_n_values,
5829
-            $this->get_combined_primary_key_fields()
5830
-        );
5831
-        return http_build_query($cols_n_values_for_primary_key_index);
5832
-    }
5833
-
5834
-
5835
-
5836
-    /**
5837
-     * Gets the field values from the primary key string
5838
-     *
5839
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5840
-     * @param string $index_primary_key_string
5841
-     * @return null|array
5842
-     * @throws EE_Error
5843
-     */
5844
-    public function parse_index_primary_key_string($index_primary_key_string)
5845
-    {
5846
-        $key_fields = $this->get_combined_primary_key_fields();
5847
-        // check all of them are in the $id
5848
-        $key_vals_in_combined_pk = array();
5849
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5850
-        foreach ($key_fields as $key_field_name => $field_obj) {
5851
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5852
-                return null;
5853
-            }
5854
-        }
5855
-        return $key_vals_in_combined_pk;
5856
-    }
5857
-
5858
-
5859
-
5860
-    /**
5861
-     * verifies that an array of key-value pairs for model fields has a key
5862
-     * for each field comprising the primary key index
5863
-     *
5864
-     * @param array $key_vals
5865
-     * @return boolean
5866
-     * @throws EE_Error
5867
-     */
5868
-    public function has_all_combined_primary_key_fields($key_vals)
5869
-    {
5870
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5871
-        foreach ($keys_it_should_have as $key) {
5872
-            if (! isset($key_vals[ $key ])) {
5873
-                return false;
5874
-            }
5875
-        }
5876
-        return true;
5877
-    }
5878
-
5879
-
5880
-
5881
-    /**
5882
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5883
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5884
-     *
5885
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5886
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5887
-     * @throws EE_Error
5888
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5889
-     *                                                              indexed)
5890
-     */
5891
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5892
-    {
5893
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5894
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5895
-        } elseif (is_array($model_object_or_attributes_array)) {
5896
-            $attributes_array = $model_object_or_attributes_array;
5897
-        } else {
5898
-            throw new EE_Error(sprintf(__(
5899
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5900
-                "event_espresso"
5901
-            ), $model_object_or_attributes_array));
5902
-        }
5903
-        // even copies obviously won't have the same ID, so remove the primary key
5904
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5905
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5906
-            unset($attributes_array[ $this->primary_key_name() ]);
5907
-        }
5908
-        if (isset($query_params[0])) {
5909
-            $query_params[0] = array_merge($attributes_array, $query_params);
5910
-        } else {
5911
-            $query_params[0] = $attributes_array;
5912
-        }
5913
-        return $this->get_all($query_params);
5914
-    }
5915
-
5916
-
5917
-
5918
-    /**
5919
-     * Gets the first copy we find. See get_all_copies for more details
5920
-     *
5921
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5922
-     * @param array $query_params
5923
-     * @return EE_Base_Class
5924
-     * @throws EE_Error
5925
-     */
5926
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5927
-    {
5928
-        if (! is_array($query_params)) {
5929
-            EE_Error::doing_it_wrong(
5930
-                'EEM_Base::get_one_copy',
5931
-                sprintf(
5932
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5933
-                    gettype($query_params)
5934
-                ),
5935
-                '4.6.0'
5936
-            );
5937
-            $query_params = array();
5938
-        }
5939
-        $query_params['limit'] = 1;
5940
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5941
-        if (is_array($copies)) {
5942
-            return array_shift($copies);
5943
-        }
5944
-        return null;
5945
-    }
5946
-
5947
-
5948
-
5949
-    /**
5950
-     * Updates the item with the specified id. Ignores default query parameters because
5951
-     * we have specified the ID, and its assumed we KNOW what we're doing
5952
-     *
5953
-     * @param array      $fields_n_values keys are field names, values are their new values
5954
-     * @param int|string $id              the value of the primary key to update
5955
-     * @return int number of rows updated
5956
-     * @throws EE_Error
5957
-     */
5958
-    public function update_by_ID($fields_n_values, $id)
5959
-    {
5960
-        $query_params = array(
5961
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5962
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5963
-        );
5964
-        return $this->update($fields_n_values, $query_params);
5965
-    }
5966
-
5967
-
5968
-
5969
-    /**
5970
-     * Changes an operator which was supplied to the models into one usable in SQL
5971
-     *
5972
-     * @param string $operator_supplied
5973
-     * @return string an operator which can be used in SQL
5974
-     * @throws EE_Error
5975
-     */
5976
-    private function _prepare_operator_for_sql($operator_supplied)
5977
-    {
5978
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5979
-            : null;
5980
-        if ($sql_operator) {
5981
-            return $sql_operator;
5982
-        }
5983
-        throw new EE_Error(
5984
-            sprintf(
5985
-                __(
5986
-                    "The operator '%s' is not in the list of valid operators: %s",
5987
-                    "event_espresso"
5988
-                ),
5989
-                $operator_supplied,
5990
-                implode(",", array_keys($this->_valid_operators))
5991
-            )
5992
-        );
5993
-    }
5994
-
5995
-
5996
-
5997
-    /**
5998
-     * Gets the valid operators
5999
-     * @return array keys are accepted strings, values are the SQL they are converted to
6000
-     */
6001
-    public function valid_operators()
6002
-    {
6003
-        return $this->_valid_operators;
6004
-    }
6005
-
6006
-
6007
-
6008
-    /**
6009
-     * Gets the between-style operators (take 2 arguments).
6010
-     * @return array keys are accepted strings, values are the SQL they are converted to
6011
-     */
6012
-    public function valid_between_style_operators()
6013
-    {
6014
-        return array_intersect(
6015
-            $this->valid_operators(),
6016
-            $this->_between_style_operators
6017
-        );
6018
-    }
6019
-
6020
-    /**
6021
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6022
-     * @return array keys are accepted strings, values are the SQL they are converted to
6023
-     */
6024
-    public function valid_like_style_operators()
6025
-    {
6026
-        return array_intersect(
6027
-            $this->valid_operators(),
6028
-            $this->_like_style_operators
6029
-        );
6030
-    }
6031
-
6032
-    /**
6033
-     * Gets the "in"-style operators
6034
-     * @return array keys are accepted strings, values are the SQL they are converted to
6035
-     */
6036
-    public function valid_in_style_operators()
6037
-    {
6038
-        return array_intersect(
6039
-            $this->valid_operators(),
6040
-            $this->_in_style_operators
6041
-        );
6042
-    }
6043
-
6044
-    /**
6045
-     * Gets the "null"-style operators (accept no arguments)
6046
-     * @return array keys are accepted strings, values are the SQL they are converted to
6047
-     */
6048
-    public function valid_null_style_operators()
6049
-    {
6050
-        return array_intersect(
6051
-            $this->valid_operators(),
6052
-            $this->_null_style_operators
6053
-        );
6054
-    }
6055
-
6056
-    /**
6057
-     * Gets an array where keys are the primary keys and values are their 'names'
6058
-     * (as determined by the model object's name() function, which is often overridden)
6059
-     *
6060
-     * @param array $query_params like get_all's
6061
-     * @return string[]
6062
-     * @throws EE_Error
6063
-     */
6064
-    public function get_all_names($query_params = array())
6065
-    {
6066
-        $objs = $this->get_all($query_params);
6067
-        $names = array();
6068
-        foreach ($objs as $obj) {
6069
-            $names[ $obj->ID() ] = $obj->name();
6070
-        }
6071
-        return $names;
6072
-    }
6073
-
6074
-
6075
-
6076
-    /**
6077
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6078
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6079
-     * this is duplicated effort and reduces efficiency) you would be better to use
6080
-     * array_keys() on $model_objects.
6081
-     *
6082
-     * @param \EE_Base_Class[] $model_objects
6083
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6084
-     *                                               in the returned array
6085
-     * @return array
6086
-     * @throws EE_Error
6087
-     */
6088
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6089
-    {
6090
-        if (! $this->has_primary_key_field()) {
6091
-            if (WP_DEBUG) {
6092
-                EE_Error::add_error(
6093
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6094
-                    __FILE__,
6095
-                    __FUNCTION__,
6096
-                    __LINE__
6097
-                );
6098
-            }
6099
-        }
6100
-        $IDs = array();
6101
-        foreach ($model_objects as $model_object) {
6102
-            $id = $model_object->ID();
6103
-            if (! $id) {
6104
-                if ($filter_out_empty_ids) {
6105
-                    continue;
6106
-                }
6107
-                if (WP_DEBUG) {
6108
-                    EE_Error::add_error(
6109
-                        __(
6110
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6111
-                            'event_espresso'
6112
-                        ),
6113
-                        __FILE__,
6114
-                        __FUNCTION__,
6115
-                        __LINE__
6116
-                    );
6117
-                }
6118
-            }
6119
-            $IDs[] = $id;
6120
-        }
6121
-        return $IDs;
6122
-    }
6123
-
6124
-
6125
-
6126
-    /**
6127
-     * Returns the string used in capabilities relating to this model. If there
6128
-     * are no capabilities that relate to this model returns false
6129
-     *
6130
-     * @return string|false
6131
-     */
6132
-    public function cap_slug()
6133
-    {
6134
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6135
-    }
6136
-
6137
-
6138
-
6139
-    /**
6140
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6141
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6142
-     * only returns the cap restrictions array in that context (ie, the array
6143
-     * at that key)
6144
-     *
6145
-     * @param string $context
6146
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6147
-     * @throws EE_Error
6148
-     */
6149
-    public function cap_restrictions($context = EEM_Base::caps_read)
6150
-    {
6151
-        EEM_Base::verify_is_valid_cap_context($context);
6152
-        // check if we ought to run the restriction generator first
6153
-        if (
6154
-            isset($this->_cap_restriction_generators[ $context ])
6155
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6156
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6157
-        ) {
6158
-            $this->_cap_restrictions[ $context ] = array_merge(
6159
-                $this->_cap_restrictions[ $context ],
6160
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6161
-            );
6162
-        }
6163
-        // and make sure we've finalized the construction of each restriction
6164
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6165
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6166
-                $where_conditions_obj->_finalize_construct($this);
6167
-            }
6168
-        }
6169
-        return $this->_cap_restrictions[ $context ];
6170
-    }
6171
-
6172
-
6173
-
6174
-    /**
6175
-     * Indicating whether or not this model thinks its a wp core model
6176
-     *
6177
-     * @return boolean
6178
-     */
6179
-    public function is_wp_core_model()
6180
-    {
6181
-        return $this->_wp_core_model;
6182
-    }
6183
-
6184
-
6185
-
6186
-    /**
6187
-     * Gets all the caps that are missing which impose a restriction on
6188
-     * queries made in this context
6189
-     *
6190
-     * @param string $context one of EEM_Base::caps_ constants
6191
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6192
-     * @throws EE_Error
6193
-     */
6194
-    public function caps_missing($context = EEM_Base::caps_read)
6195
-    {
6196
-        $missing_caps = array();
6197
-        $cap_restrictions = $this->cap_restrictions($context);
6198
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6199
-            if (
6200
-                ! EE_Capabilities::instance()
6201
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6202
-            ) {
6203
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6204
-            }
6205
-        }
6206
-        return $missing_caps;
6207
-    }
6208
-
6209
-
6210
-
6211
-    /**
6212
-     * Gets the mapping from capability contexts to action strings used in capability names
6213
-     *
6214
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6215
-     * one of 'read', 'edit', or 'delete'
6216
-     */
6217
-    public function cap_contexts_to_cap_action_map()
6218
-    {
6219
-        return apply_filters(
6220
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6221
-            $this->_cap_contexts_to_cap_action_map,
6222
-            $this
6223
-        );
6224
-    }
6225
-
6226
-
6227
-
6228
-    /**
6229
-     * Gets the action string for the specified capability context
6230
-     *
6231
-     * @param string $context
6232
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6233
-     * @throws EE_Error
6234
-     */
6235
-    public function cap_action_for_context($context)
6236
-    {
6237
-        $mapping = $this->cap_contexts_to_cap_action_map();
6238
-        if (isset($mapping[ $context ])) {
6239
-            return $mapping[ $context ];
6240
-        }
6241
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6242
-            return $action;
6243
-        }
6244
-        throw new EE_Error(
6245
-            sprintf(
6246
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6247
-                $context,
6248
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6249
-            )
6250
-        );
6251
-    }
6252
-
6253
-
6254
-
6255
-    /**
6256
-     * Returns all the capability contexts which are valid when querying models
6257
-     *
6258
-     * @return array
6259
-     */
6260
-    public static function valid_cap_contexts()
6261
-    {
6262
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6263
-            self::caps_read,
6264
-            self::caps_read_admin,
6265
-            self::caps_edit,
6266
-            self::caps_delete,
6267
-        ));
6268
-    }
6269
-
6270
-
6271
-
6272
-    /**
6273
-     * Returns all valid options for 'default_where_conditions'
6274
-     *
6275
-     * @return array
6276
-     */
6277
-    public static function valid_default_where_conditions()
6278
-    {
6279
-        return array(
6280
-            EEM_Base::default_where_conditions_all,
6281
-            EEM_Base::default_where_conditions_this_only,
6282
-            EEM_Base::default_where_conditions_others_only,
6283
-            EEM_Base::default_where_conditions_minimum_all,
6284
-            EEM_Base::default_where_conditions_minimum_others,
6285
-            EEM_Base::default_where_conditions_none
6286
-        );
6287
-    }
6288
-
6289
-    // public static function default_where_conditions_full
6290
-    /**
6291
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6292
-     *
6293
-     * @param string $context
6294
-     * @return bool
6295
-     * @throws EE_Error
6296
-     */
6297
-    public static function verify_is_valid_cap_context($context)
6298
-    {
6299
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6300
-        if (in_array($context, $valid_cap_contexts)) {
6301
-            return true;
6302
-        }
6303
-        throw new EE_Error(
6304
-            sprintf(
6305
-                __(
6306
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6307
-                    'event_espresso'
6308
-                ),
6309
-                $context,
6310
-                'EEM_Base',
6311
-                implode(',', $valid_cap_contexts)
6312
-            )
6313
-        );
6314
-    }
6315
-
6316
-
6317
-
6318
-    /**
6319
-     * Clears all the models field caches. This is only useful when a sub-class
6320
-     * might have added a field or something and these caches might be invalidated
6321
-     */
6322
-    protected function _invalidate_field_caches()
6323
-    {
6324
-        $this->_cache_foreign_key_to_fields = array();
6325
-        $this->_cached_fields = null;
6326
-        $this->_cached_fields_non_db_only = null;
6327
-    }
6328
-
6329
-
6330
-
6331
-    /**
6332
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6333
-     * (eg "and", "or", "not").
6334
-     *
6335
-     * @return array
6336
-     */
6337
-    public function logic_query_param_keys()
6338
-    {
6339
-        return $this->_logic_query_param_keys;
6340
-    }
6341
-
6342
-
6343
-
6344
-    /**
6345
-     * Determines whether or not the where query param array key is for a logic query param.
6346
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6347
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6348
-     *
6349
-     * @param $query_param_key
6350
-     * @return bool
6351
-     */
6352
-    public function is_logic_query_param_key($query_param_key)
6353
-    {
6354
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6355
-            if (
6356
-                $query_param_key === $logic_query_param_key
6357
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6358
-            ) {
6359
-                return true;
6360
-            }
6361
-        }
6362
-        return false;
6363
-    }
6364
-
6365
-    /**
6366
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6367
-     * @since 4.9.74.p
6368
-     * @return boolean
6369
-     */
6370
-    public function hasPassword()
6371
-    {
6372
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6373
-        if ($this->has_password_field === null) {
6374
-            $password_field = $this->getPasswordField();
6375
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6376
-        }
6377
-        return $this->has_password_field;
6378
-    }
6379
-
6380
-    /**
6381
-     * Returns the password field on this model, if there is one
6382
-     * @since 4.9.74.p
6383
-     * @return EE_Password_Field|null
6384
-     */
6385
-    public function getPasswordField()
6386
-    {
6387
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6388
-        // there's no need to search for it. If we don't know yet, then find out
6389
-        if ($this->has_password_field === null && $this->password_field === null) {
6390
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6391
-        }
6392
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6393
-        return $this->password_field;
6394
-    }
6395
-
6396
-
6397
-    /**
6398
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6399
-     * @since 4.9.74.p
6400
-     * @return EE_Model_Field_Base[]
6401
-     * @throws EE_Error
6402
-     */
6403
-    public function getPasswordProtectedFields()
6404
-    {
6405
-        $password_field = $this->getPasswordField();
6406
-        $fields = array();
6407
-        if ($password_field instanceof EE_Password_Field) {
6408
-            $field_names = $password_field->protectedFields();
6409
-            foreach ($field_names as $field_name) {
6410
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6411
-            }
6412
-        }
6413
-        return $fields;
6414
-    }
6415
-
6416
-
6417
-    /**
6418
-     * Checks if the current user can perform the requested action on this model
6419
-     * @since 4.9.74.p
6420
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6421
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6422
-     * @return bool
6423
-     * @throws EE_Error
6424
-     * @throws InvalidArgumentException
6425
-     * @throws InvalidDataTypeException
6426
-     * @throws InvalidInterfaceException
6427
-     * @throws ReflectionException
6428
-     * @throws UnexpectedEntityException
6429
-     */
6430
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6431
-    {
6432
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6433
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6434
-        }
6435
-        if (!is_array($model_obj_or_fields_n_values)) {
6436
-            throw new UnexpectedEntityException(
6437
-                $model_obj_or_fields_n_values,
6438
-                'EE_Base_Class',
6439
-                sprintf(
6440
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6441
-                    __FUNCTION__
6442
-                )
6443
-            );
6444
-        }
6445
-        return $this->exists(
6446
-            $this->alter_query_params_to_restrict_by_ID(
6447
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6448
-                array(
6449
-                    'default_where_conditions' => 'none',
6450
-                    'caps'                     => $cap_to_check,
6451
-                )
6452
-            )
6453
-        );
6454
-    }
6455
-
6456
-    /**
6457
-     * Returns the query param where conditions key to the password affecting this model.
6458
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6459
-     * @since 4.9.74.p
6460
-     * @return null|string
6461
-     * @throws EE_Error
6462
-     * @throws InvalidArgumentException
6463
-     * @throws InvalidDataTypeException
6464
-     * @throws InvalidInterfaceException
6465
-     * @throws ModelConfigurationException
6466
-     * @throws ReflectionException
6467
-     */
6468
-    public function modelChainAndPassword()
6469
-    {
6470
-        if ($this->model_chain_to_password === null) {
6471
-            throw new ModelConfigurationException(
6472
-                $this,
6473
-                esc_html_x(
6474
-                // @codingStandardsIgnoreStart
6475
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6476
-                    // @codingStandardsIgnoreEnd
6477
-                    '1: model name',
6478
-                    'event_espresso'
6479
-                )
6480
-            );
6481
-        }
6482
-        if ($this->model_chain_to_password === '') {
6483
-            $model_with_password = $this;
6484
-        } else {
6485
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6486
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6487
-            } else {
6488
-                $last_model_in_chain = $this->model_chain_to_password;
6489
-            }
6490
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6491
-        }
6492
-
6493
-        $password_field = $model_with_password->getPasswordField();
6494
-        if ($password_field instanceof EE_Password_Field) {
6495
-            $password_field_name = $password_field->get_name();
6496
-        } else {
6497
-            throw new ModelConfigurationException(
6498
-                $this,
6499
-                sprintf(
6500
-                    esc_html_x(
6501
-                        '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"',
6502
-                        '1: model name, 2: special string',
6503
-                        'event_espresso'
6504
-                    ),
6505
-                    $model_with_password->get_this_model_name(),
6506
-                    $this->model_chain_to_password
6507
-                )
6508
-            );
6509
-        }
6510
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6511
-    }
6512
-
6513
-    /**
6514
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6515
-     * or if this model itself has a password affecting access to some of its other fields.
6516
-     * @since 4.9.74.p
6517
-     * @return boolean
6518
-     */
6519
-    public function restrictedByRelatedModelPassword()
6520
-    {
6521
-        return $this->model_chain_to_password !== null;
6522
-    }
3817
+		}
3818
+		return $null_friendly_where_conditions;
3819
+	}
3820
+
3821
+
3822
+
3823
+	/**
3824
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3825
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3826
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3827
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3828
+	 *
3829
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
+	 */
3832
+	private function _get_default_where_conditions($model_relation_path = '')
3833
+	{
3834
+		if ($this->_ignore_where_strategy) {
3835
+			return array();
3836
+		}
3837
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
+	}
3839
+
3840
+
3841
+
3842
+	/**
3843
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3844
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3845
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3846
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3847
+	 * Similar to _get_default_where_conditions
3848
+	 *
3849
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3850
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
+	 */
3852
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3853
+	{
3854
+		if ($this->_ignore_where_strategy) {
3855
+			return array();
3856
+		}
3857
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3858
+	}
3859
+
3860
+
3861
+
3862
+	/**
3863
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3864
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3865
+	 *
3866
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3867
+	 * @return string
3868
+	 * @throws EE_Error
3869
+	 */
3870
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3871
+	{
3872
+		$selects = $this->_get_columns_to_select_for_this_model();
3873
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3874
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
+			foreach ($other_model_selects as $key => $value) {
3877
+				$selects[] = $value;
3878
+			}
3879
+		}
3880
+		return implode(", ", $selects);
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
+	 * So that's going to be the columns for all the fields on the model
3888
+	 *
3889
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
+	 */
3892
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
+	{
3894
+		$fields = $this->field_settings();
3895
+		$selects = array();
3896
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
+			$model_relation_chain,
3898
+			$this->get_this_model_name()
3899
+		);
3900
+		foreach ($fields as $field_obj) {
3901
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3902
+						 . $field_obj->get_table_alias()
3903
+						 . "."
3904
+						 . $field_obj->get_table_column()
3905
+						 . " AS '"
3906
+						 . $table_alias_with_model_relation_chain_prefix
3907
+						 . $field_obj->get_table_alias()
3908
+						 . "."
3909
+						 . $field_obj->get_table_column()
3910
+						 . "'";
3911
+		}
3912
+		// make sure we are also getting the PKs of each table
3913
+		$tables = $this->get_tables();
3914
+		if (count($tables) > 1) {
3915
+			foreach ($tables as $table_obj) {
3916
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
+									   . $table_obj->get_fully_qualified_pk_column();
3918
+				if (! in_array($qualified_pk_column, $selects)) {
3919
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
+				}
3921
+			}
3922
+		}
3923
+		return $selects;
3924
+	}
3925
+
3926
+
3927
+
3928
+	/**
3929
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
+	 * SQL for joining, and the data types
3933
+	 *
3934
+	 * @param null|string                 $original_query_param
3935
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3940
+	 *                                                          or 'Registration's
3941
+	 * @param string                      $original_query_param what it originally was (eg
3942
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
+	 *                                                          matches $query_param
3944
+	 * @throws EE_Error
3945
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
+	 */
3947
+	private function _extract_related_model_info_from_query_param(
3948
+		$query_param,
3949
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
+		$query_param_type,
3951
+		$original_query_param = null
3952
+	) {
3953
+		if ($original_query_param === null) {
3954
+			$original_query_param = $query_param;
3955
+		}
3956
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
+		$allow_fields = in_array(
3960
+			$query_param_type,
3961
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
+			true
3963
+		);
3964
+		// check to see if we have a field on this model
3965
+		$this_model_fields = $this->field_settings(true);
3966
+		if (array_key_exists($query_param, $this_model_fields)) {
3967
+			if ($allow_fields) {
3968
+				return;
3969
+			}
3970
+			throw new EE_Error(
3971
+				sprintf(
3972
+					__(
3973
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
+						"event_espresso"
3975
+					),
3976
+					$query_param,
3977
+					get_class($this),
3978
+					$query_param_type,
3979
+					$original_query_param
3980
+				)
3981
+			);
3982
+		}
3983
+		// check if this is a special logic query param
3984
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
+			if ($allow_logic_query_params) {
3986
+				return;
3987
+			}
3988
+			throw new EE_Error(
3989
+				sprintf(
3990
+					__(
3991
+						'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',
3992
+						'event_espresso'
3993
+					),
3994
+					implode('", "', $this->_logic_query_param_keys),
3995
+					$query_param,
3996
+					get_class($this),
3997
+					'<br />',
3998
+					"\t"
3999
+					. ' $passed_in_query_info = <pre>'
4000
+					. print_r($passed_in_query_info, true)
4001
+					. '</pre>'
4002
+					. "\n\t"
4003
+					. ' $query_param_type = '
4004
+					. $query_param_type
4005
+					. "\n\t"
4006
+					. ' $original_query_param = '
4007
+					. $original_query_param
4008
+				)
4009
+			);
4010
+		}
4011
+		// check if it's a custom selection
4012
+		if (
4013
+			$this->_custom_selections instanceof CustomSelects
4014
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
+		) {
4016
+			return;
4017
+		}
4018
+		// check if has a model name at the beginning
4019
+		// and
4020
+		// check if it's a field on a related model
4021
+		if (
4022
+			$this->extractJoinModelFromQueryParams(
4023
+				$passed_in_query_info,
4024
+				$query_param,
4025
+				$original_query_param,
4026
+				$query_param_type
4027
+			)
4028
+		) {
4029
+			return;
4030
+		}
4031
+
4032
+		// ok so $query_param didn't start with a model name
4033
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4034
+		// it's wack, that's what it is
4035
+		throw new EE_Error(
4036
+			sprintf(
4037
+				esc_html__(
4038
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
+					"event_espresso"
4040
+				),
4041
+				$query_param,
4042
+				get_class($this),
4043
+				$query_param_type,
4044
+				$original_query_param
4045
+			)
4046
+		);
4047
+	}
4048
+
4049
+
4050
+	/**
4051
+	 * Extracts any possible join model information from the provided possible_join_string.
4052
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
+	 * parts that should be added to the query.
4054
+	 *
4055
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
+	 * @param null|string                 $original_query_param
4058
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
+	 * @return bool  returns true if a join was added and false if not.
4061
+	 * @throws EE_Error
4062
+	 */
4063
+	private function extractJoinModelFromQueryParams(
4064
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4065
+		$possible_join_string,
4066
+		$original_query_param,
4067
+		$query_parameter_type
4068
+	) {
4069
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
+				if ($possible_join_string === '') {
4074
+					// nothing left to $query_param
4075
+					// we should actually end in a field name, not a model like this!
4076
+					throw new EE_Error(
4077
+						sprintf(
4078
+							esc_html__(
4079
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
+								"event_espresso"
4081
+							),
4082
+							$possible_join_string,
4083
+							$query_parameter_type,
4084
+							get_class($this),
4085
+							$valid_related_model_name
4086
+						)
4087
+					);
4088
+				}
4089
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
+				$related_model_obj->_extract_related_model_info_from_query_param(
4091
+					$possible_join_string,
4092
+					$query_info_carrier,
4093
+					$query_parameter_type,
4094
+					$original_query_param
4095
+				);
4096
+				return true;
4097
+			}
4098
+			if ($possible_join_string === $valid_related_model_name) {
4099
+				$this->_add_join_to_model(
4100
+					$valid_related_model_name,
4101
+					$query_info_carrier,
4102
+					$original_query_param
4103
+				);
4104
+				return true;
4105
+			}
4106
+		}
4107
+		return false;
4108
+	}
4109
+
4110
+
4111
+	/**
4112
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
+	{
4118
+		if (
4119
+			$this->_custom_selections instanceof CustomSelects
4120
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
+			)
4123
+		) {
4124
+			$original_selects = $this->_custom_selections->originalSelects();
4125
+			foreach ($original_selects as $alias => $select_configuration) {
4126
+				$this->extractJoinModelFromQueryParams(
4127
+					$query_info_carrier,
4128
+					$select_configuration[0],
4129
+					$select_configuration[0],
4130
+					'custom_selects'
4131
+				);
4132
+			}
4133
+		}
4134
+	}
4135
+
4136
+
4137
+
4138
+	/**
4139
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
+	 * and store it on $passed_in_query_info
4141
+	 *
4142
+	 * @param string                      $model_name
4143
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4145
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4146
+	 *                                                          and are adding a join to 'Payment' with the original
4147
+	 *                                                          query param key
4148
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4150
+	 *                                                          Payment wants to add default query params so that it
4151
+	 *                                                          will know what models to prepend onto its default query
4152
+	 *                                                          params or in case it wants to rename tables (in case
4153
+	 *                                                          there are multiple joins to the same table)
4154
+	 * @return void
4155
+	 * @throws EE_Error
4156
+	 */
4157
+	private function _add_join_to_model(
4158
+		$model_name,
4159
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
+		$original_query_param
4161
+	) {
4162
+		$relation_obj = $this->related_settings_for($model_name);
4163
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
+		// check if the relation is HABTM, because then we're essentially doing two joins
4165
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4167
+			$join_model_obj = $relation_obj->get_join_model();
4168
+			// replace the model specified with the join model for this relation chain, whi
4169
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
+				$model_name,
4171
+				$join_model_obj->get_this_model_name(),
4172
+				$model_relation_chain
4173
+			);
4174
+			$passed_in_query_info->merge(
4175
+				new EE_Model_Query_Info_Carrier(
4176
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
+				)
4179
+			);
4180
+		}
4181
+		// now just join to the other table pointed to by the relation object, and add its data types
4182
+		$passed_in_query_info->merge(
4183
+			new EE_Model_Query_Info_Carrier(
4184
+				array($model_relation_chain => $model_name),
4185
+				$relation_obj->get_join_statement($model_relation_chain)
4186
+			)
4187
+		);
4188
+	}
4189
+
4190
+
4191
+
4192
+	/**
4193
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
+	 *
4195
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
+	 * @return string of SQL
4197
+	 * @throws EE_Error
4198
+	 */
4199
+	private function _construct_where_clause($where_params)
4200
+	{
4201
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
+		if ($SQL) {
4203
+			return " WHERE " . $SQL;
4204
+		}
4205
+		return '';
4206
+	}
4207
+
4208
+
4209
+
4210
+	/**
4211
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
+	 * and should be passed HAVING parameters, not WHERE parameters
4213
+	 *
4214
+	 * @param array $having_params
4215
+	 * @return string
4216
+	 * @throws EE_Error
4217
+	 */
4218
+	private function _construct_having_clause($having_params)
4219
+	{
4220
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
+		if ($SQL) {
4222
+			return " HAVING " . $SQL;
4223
+		}
4224
+		return '';
4225
+	}
4226
+
4227
+
4228
+	/**
4229
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
+	 * Event_Meta.meta_value = 'foo'))"
4231
+	 *
4232
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
+	 * @throws EE_Error
4235
+	 * @return string of SQL
4236
+	 */
4237
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
+	{
4239
+		$where_clauses = array();
4240
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
+				switch ($query_param) {
4244
+					case 'not':
4245
+					case 'NOT':
4246
+						$where_clauses[] = "! ("
4247
+										   . $this->_construct_condition_clause_recursive(
4248
+											   $op_and_value_or_sub_condition,
4249
+											   $glue
4250
+										   )
4251
+										   . ")";
4252
+						break;
4253
+					case 'and':
4254
+					case 'AND':
4255
+						$where_clauses[] = " ("
4256
+										   . $this->_construct_condition_clause_recursive(
4257
+											   $op_and_value_or_sub_condition,
4258
+											   ' AND '
4259
+										   )
4260
+										   . ")";
4261
+						break;
4262
+					case 'or':
4263
+					case 'OR':
4264
+						$where_clauses[] = " ("
4265
+										   . $this->_construct_condition_clause_recursive(
4266
+											   $op_and_value_or_sub_condition,
4267
+											   ' OR '
4268
+										   )
4269
+										   . ")";
4270
+						break;
4271
+				}
4272
+			} else {
4273
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4274
+				// if it's not a normal field, maybe it's a custom selection?
4275
+				if (! $field_obj) {
4276
+					if ($this->_custom_selections instanceof CustomSelects) {
4277
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
+					} else {
4279
+						throw new EE_Error(sprintf(__(
4280
+							"%s is neither a valid model field name, nor a custom selection",
4281
+							"event_espresso"
4282
+						), $query_param));
4283
+					}
4284
+				}
4285
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
+			}
4288
+		}
4289
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4290
+	}
4291
+
4292
+
4293
+
4294
+	/**
4295
+	 * Takes the input parameter and extract the table name (alias) and column name
4296
+	 *
4297
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
+	 * @throws EE_Error
4299
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
+	 */
4301
+	private function _deduce_column_name_from_query_param($query_param)
4302
+	{
4303
+		$field = $this->_deduce_field_from_query_param($query_param);
4304
+		if ($field) {
4305
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
+				$field->get_model_name(),
4307
+				$query_param
4308
+			);
4309
+			return $table_alias_prefix . $field->get_qualified_column();
4310
+		}
4311
+		if (
4312
+			$this->_custom_selections instanceof CustomSelects
4313
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
+		) {
4315
+			// maybe it's custom selection item?
4316
+			// if so, just use it as the "column name"
4317
+			return $query_param;
4318
+		}
4319
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
+			? implode(',', $this->_custom_selections->columnAliases())
4321
+			: '';
4322
+		throw new EE_Error(
4323
+			sprintf(
4324
+				__(
4325
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4326
+					"event_espresso"
4327
+				),
4328
+				$query_param,
4329
+				$custom_select_aliases
4330
+			)
4331
+		);
4332
+	}
4333
+
4334
+
4335
+
4336
+	/**
4337
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
+	 *
4342
+	 * @param string $condition_query_param_key
4343
+	 * @return string
4344
+	 */
4345
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
+	{
4347
+		$pos_of_star = strpos($condition_query_param_key, '*');
4348
+		if ($pos_of_star === false) {
4349
+			return $condition_query_param_key;
4350
+		}
4351
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
+		return $condition_query_param_sans_star;
4353
+	}
4354
+
4355
+
4356
+
4357
+	/**
4358
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
+	 *
4360
+	 * @param                            mixed      array | string    $op_and_value
4361
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
+	 * @throws EE_Error
4363
+	 * @return string
4364
+	 */
4365
+	private function _construct_op_and_value($op_and_value, $field_obj)
4366
+	{
4367
+		if (is_array($op_and_value)) {
4368
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
+			if (! $operator) {
4370
+				$php_array_like_string = array();
4371
+				foreach ($op_and_value as $key => $value) {
4372
+					$php_array_like_string[] = "$key=>$value";
4373
+				}
4374
+				throw new EE_Error(
4375
+					sprintf(
4376
+						__(
4377
+							"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))",
4378
+							"event_espresso"
4379
+						),
4380
+						implode(",", $php_array_like_string)
4381
+					)
4382
+				);
4383
+			}
4384
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
+		} else {
4386
+			$operator = '=';
4387
+			$value = $op_and_value;
4388
+		}
4389
+		// check to see if the value is actually another field
4390
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
+		}
4393
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
+			// in this case, the value should be an array, or at least a comma-separated list
4395
+			// it will need to handle a little differently
4396
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4398
+			return $operator . SP . $cleaned_value;
4399
+		}
4400
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
+			// the value should be an array with count of two.
4402
+			if (count($value) !== 2) {
4403
+				throw new EE_Error(
4404
+					sprintf(
4405
+						__(
4406
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
+							'event_espresso'
4408
+						),
4409
+						"BETWEEN"
4410
+					)
4411
+				);
4412
+			}
4413
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
+			return $operator . SP . $cleaned_value;
4415
+		}
4416
+		if (in_array($operator, $this->valid_null_style_operators())) {
4417
+			if ($value !== null) {
4418
+				throw new EE_Error(
4419
+					sprintf(
4420
+						__(
4421
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
+							"event_espresso"
4423
+						),
4424
+						$value,
4425
+						$operator
4426
+					)
4427
+				);
4428
+			}
4429
+			return $operator;
4430
+		}
4431
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
+			// remove other junk. So just treat it as a string.
4434
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
+		}
4436
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
+		}
4439
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
+			throw new EE_Error(
4441
+				sprintf(
4442
+					__(
4443
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
+						'event_espresso'
4445
+					),
4446
+					$operator,
4447
+					$operator
4448
+				)
4449
+			);
4450
+		}
4451
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
+			throw new EE_Error(
4453
+				sprintf(
4454
+					__(
4455
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
+						'event_espresso'
4457
+					),
4458
+					$operator,
4459
+					$operator
4460
+				)
4461
+			);
4462
+		}
4463
+		throw new EE_Error(
4464
+			sprintf(
4465
+				__(
4466
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
+					"event_espresso"
4468
+				),
4469
+				http_build_query($op_and_value)
4470
+			)
4471
+		);
4472
+	}
4473
+
4474
+
4475
+
4476
+	/**
4477
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
+	 *
4479
+	 * @param array                      $values
4480
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
+	 *                                              '%s'
4482
+	 * @return string
4483
+	 * @throws EE_Error
4484
+	 */
4485
+	public function _construct_between_value($values, $field_obj)
4486
+	{
4487
+		$cleaned_values = array();
4488
+		foreach ($values as $value) {
4489
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
+		}
4491
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
+	}
4493
+
4494
+
4495
+
4496
+	/**
4497
+	 * Takes an array or a comma-separated list of $values and cleans them
4498
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4499
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4500
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4501
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4502
+	 *
4503
+	 * @param mixed                      $values    array or comma-separated string
4504
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4505
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4506
+	 * @throws EE_Error
4507
+	 */
4508
+	public function _construct_in_value($values, $field_obj)
4509
+	{
4510
+		// check if the value is a CSV list
4511
+		if (is_string($values)) {
4512
+			// in which case, turn it into an array
4513
+			$values = explode(",", $values);
4514
+		}
4515
+		$cleaned_values = array();
4516
+		foreach ($values as $value) {
4517
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4518
+		}
4519
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4520
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4521
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4522
+		if (empty($cleaned_values)) {
4523
+			$all_fields = $this->field_settings();
4524
+			$a_field = array_shift($all_fields);
4525
+			$main_table = $this->_get_main_table();
4526
+			$cleaned_values[] = "SELECT "
4527
+								. $a_field->get_table_column()
4528
+								. " FROM "
4529
+								. $main_table->get_table_name()
4530
+								. " WHERE FALSE";
4531
+		}
4532
+		return "(" . implode(",", $cleaned_values) . ")";
4533
+	}
4534
+
4535
+
4536
+
4537
+	/**
4538
+	 * @param mixed                      $value
4539
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4540
+	 * @throws EE_Error
4541
+	 * @return false|null|string
4542
+	 */
4543
+	private function _wpdb_prepare_using_field($value, $field_obj)
4544
+	{
4545
+		/** @type WPDB $wpdb */
4546
+		global $wpdb;
4547
+		if ($field_obj instanceof EE_Model_Field_Base) {
4548
+			return $wpdb->prepare(
4549
+				$field_obj->get_wpdb_data_type(),
4550
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4551
+			);
4552
+		} //$field_obj should really just be a data type
4553
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4554
+			throw new EE_Error(
4555
+				sprintf(
4556
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4557
+					$field_obj,
4558
+					implode(",", $this->_valid_wpdb_data_types)
4559
+				)
4560
+			);
4561
+		}
4562
+		return $wpdb->prepare($field_obj, $value);
4563
+	}
4564
+
4565
+
4566
+
4567
+	/**
4568
+	 * Takes the input parameter and finds the model field that it indicates.
4569
+	 *
4570
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4571
+	 * @throws EE_Error
4572
+	 * @return EE_Model_Field_Base
4573
+	 */
4574
+	protected function _deduce_field_from_query_param($query_param_name)
4575
+	{
4576
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4577
+		// which will help us find the database table and column
4578
+		$query_param_parts = explode(".", $query_param_name);
4579
+		if (empty($query_param_parts)) {
4580
+			throw new EE_Error(sprintf(__(
4581
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4582
+				'event_espresso'
4583
+			), $query_param_name));
4584
+		}
4585
+		$number_of_parts = count($query_param_parts);
4586
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4587
+		if ($number_of_parts === 1) {
4588
+			$field_name = $last_query_param_part;
4589
+			$model_obj = $this;
4590
+		} else {// $number_of_parts >= 2
4591
+			// the last part is the column name, and there are only 2parts. therefore...
4592
+			$field_name = $last_query_param_part;
4593
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4594
+		}
4595
+		try {
4596
+			return $model_obj->field_settings_for($field_name);
4597
+		} catch (EE_Error $e) {
4598
+			return null;
4599
+		}
4600
+	}
4601
+
4602
+
4603
+
4604
+	/**
4605
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4606
+	 * alias and column which corresponds to it
4607
+	 *
4608
+	 * @param string $field_name
4609
+	 * @throws EE_Error
4610
+	 * @return string
4611
+	 */
4612
+	public function _get_qualified_column_for_field($field_name)
4613
+	{
4614
+		$all_fields = $this->field_settings();
4615
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4616
+		if ($field) {
4617
+			return $field->get_qualified_column();
4618
+		}
4619
+		throw new EE_Error(
4620
+			sprintf(
4621
+				__(
4622
+					"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.",
4623
+					'event_espresso'
4624
+				),
4625
+				$field_name,
4626
+				get_class($this)
4627
+			)
4628
+		);
4629
+	}
4630
+
4631
+
4632
+
4633
+	/**
4634
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4635
+	 * Example usage:
4636
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4637
+	 *      array(),
4638
+	 *      ARRAY_A,
4639
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4640
+	 *  );
4641
+	 * is equivalent to
4642
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4643
+	 * and
4644
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4645
+	 *      array(
4646
+	 *          array(
4647
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4648
+	 *          ),
4649
+	 *          ARRAY_A,
4650
+	 *          implode(
4651
+	 *              ', ',
4652
+	 *              array_merge(
4653
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4654
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4655
+	 *              )
4656
+	 *          )
4657
+	 *      )
4658
+	 *  );
4659
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4660
+	 *
4661
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4662
+	 *                                            and the one whose fields you are selecting for example: when querying
4663
+	 *                                            tickets model and selecting fields from the tickets model you would
4664
+	 *                                            leave this parameter empty, because no models are needed to join
4665
+	 *                                            between the queried model and the selected one. Likewise when
4666
+	 *                                            querying the datetime model and selecting fields from the tickets
4667
+	 *                                            model, it would also be left empty, because there is a direct
4668
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4669
+	 *                                            them together. However, when querying from the event model and
4670
+	 *                                            selecting fields from the ticket model, you should provide the string
4671
+	 *                                            'Datetime', indicating that the event model must first join to the
4672
+	 *                                            datetime model in order to find its relation to ticket model.
4673
+	 *                                            Also, when querying from the venue model and selecting fields from
4674
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4675
+	 *                                            indicating you need to join the venue model to the event model,
4676
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4677
+	 *                                            This string is used to deduce the prefix that gets added onto the
4678
+	 *                                            models' tables qualified columns
4679
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4680
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4681
+	 *                                            qualified column names
4682
+	 * @return array|string
4683
+	 */
4684
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4685
+	{
4686
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4687
+		$qualified_columns = array();
4688
+		foreach ($this->field_settings() as $field_name => $field) {
4689
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4690
+		}
4691
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4692
+	}
4693
+
4694
+
4695
+
4696
+	/**
4697
+	 * constructs the select use on special limit joins
4698
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4699
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4700
+	 * (as that is typically where the limits would be set).
4701
+	 *
4702
+	 * @param  string       $table_alias The table the select is being built for
4703
+	 * @param  mixed|string $limit       The limit for this select
4704
+	 * @return string                The final select join element for the query.
4705
+	 */
4706
+	public function _construct_limit_join_select($table_alias, $limit)
4707
+	{
4708
+		$SQL = '';
4709
+		foreach ($this->_tables as $table_obj) {
4710
+			if ($table_obj instanceof EE_Primary_Table) {
4711
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4712
+					? $table_obj->get_select_join_limit($limit)
4713
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4714
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4715
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4716
+					? $table_obj->get_select_join_limit_join($limit)
4717
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4718
+			}
4719
+		}
4720
+		return $SQL;
4721
+	}
4722
+
4723
+
4724
+
4725
+	/**
4726
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4727
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4728
+	 *
4729
+	 * @return string SQL
4730
+	 * @throws EE_Error
4731
+	 */
4732
+	public function _construct_internal_join()
4733
+	{
4734
+		$SQL = $this->_get_main_table()->get_table_sql();
4735
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4736
+		return $SQL;
4737
+	}
4738
+
4739
+
4740
+
4741
+	/**
4742
+	 * Constructs the SQL for joining all the tables on this model.
4743
+	 * Normally $alias should be the primary table's alias, but in cases where
4744
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4745
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4746
+	 * alias, this will construct SQL like:
4747
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4748
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4749
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4750
+	 *
4751
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4752
+	 * @return string
4753
+	 */
4754
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4755
+	{
4756
+		$SQL = '';
4757
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4758
+		foreach ($this->_tables as $table_obj) {
4759
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4760
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4761
+					// so we're joining to this table, meaning the table is already in
4762
+					// the FROM statement, BUT the primary table isn't. So we want
4763
+					// to add the inverse join sql
4764
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4765
+				} else {
4766
+					// just add a regular JOIN to this table from the primary table
4767
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4768
+				}
4769
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4770
+		}
4771
+		return $SQL;
4772
+	}
4773
+
4774
+
4775
+
4776
+	/**
4777
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4778
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4779
+	 * their data type (eg, '%s', '%d', etc)
4780
+	 *
4781
+	 * @return array
4782
+	 */
4783
+	public function _get_data_types()
4784
+	{
4785
+		$data_types = array();
4786
+		foreach ($this->field_settings() as $field_obj) {
4787
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4788
+			/** @var $field_obj EE_Model_Field_Base */
4789
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4790
+		}
4791
+		return $data_types;
4792
+	}
4793
+
4794
+
4795
+
4796
+	/**
4797
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4798
+	 *
4799
+	 * @param string $model_name
4800
+	 * @throws EE_Error
4801
+	 * @return EEM_Base
4802
+	 */
4803
+	public function get_related_model_obj($model_name)
4804
+	{
4805
+		$model_classname = "EEM_" . $model_name;
4806
+		if (! class_exists($model_classname)) {
4807
+			throw new EE_Error(sprintf(__(
4808
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4809
+				'event_espresso'
4810
+			), $model_name, $model_classname));
4811
+		}
4812
+		return call_user_func($model_classname . "::instance");
4813
+	}
4814
+
4815
+
4816
+
4817
+	/**
4818
+	 * Returns the array of EE_ModelRelations for this model.
4819
+	 *
4820
+	 * @return EE_Model_Relation_Base[]
4821
+	 */
4822
+	public function relation_settings()
4823
+	{
4824
+		return $this->_model_relations;
4825
+	}
4826
+
4827
+
4828
+
4829
+	/**
4830
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4831
+	 * because without THOSE models, this model probably doesn't have much purpose.
4832
+	 * (Eg, without an event, datetimes have little purpose.)
4833
+	 *
4834
+	 * @return EE_Belongs_To_Relation[]
4835
+	 */
4836
+	public function belongs_to_relations()
4837
+	{
4838
+		$belongs_to_relations = array();
4839
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4840
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4841
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4842
+			}
4843
+		}
4844
+		return $belongs_to_relations;
4845
+	}
4846
+
4847
+
4848
+
4849
+	/**
4850
+	 * Returns the specified EE_Model_Relation, or throws an exception
4851
+	 *
4852
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4853
+	 * @throws EE_Error
4854
+	 * @return EE_Model_Relation_Base
4855
+	 */
4856
+	public function related_settings_for($relation_name)
4857
+	{
4858
+		$relatedModels = $this->relation_settings();
4859
+		if (! array_key_exists($relation_name, $relatedModels)) {
4860
+			throw new EE_Error(
4861
+				sprintf(
4862
+					__(
4863
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4864
+						'event_espresso'
4865
+					),
4866
+					$relation_name,
4867
+					$this->_get_class_name(),
4868
+					implode(', ', array_keys($relatedModels))
4869
+				)
4870
+			);
4871
+		}
4872
+		return $relatedModels[ $relation_name ];
4873
+	}
4874
+
4875
+
4876
+
4877
+	/**
4878
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4879
+	 * fields
4880
+	 *
4881
+	 * @param string $fieldName
4882
+	 * @param boolean $include_db_only_fields
4883
+	 * @throws EE_Error
4884
+	 * @return EE_Model_Field_Base
4885
+	 */
4886
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4887
+	{
4888
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4889
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4890
+			throw new EE_Error(sprintf(
4891
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4892
+				$fieldName,
4893
+				get_class($this)
4894
+			));
4895
+		}
4896
+		return $fieldSettings[ $fieldName ];
4897
+	}
4898
+
4899
+
4900
+
4901
+	/**
4902
+	 * Checks if this field exists on this model
4903
+	 *
4904
+	 * @param string $fieldName a key in the model's _field_settings array
4905
+	 * @return boolean
4906
+	 */
4907
+	public function has_field($fieldName)
4908
+	{
4909
+		$fieldSettings = $this->field_settings(true);
4910
+		if (isset($fieldSettings[ $fieldName ])) {
4911
+			return true;
4912
+		}
4913
+		return false;
4914
+	}
4915
+
4916
+
4917
+
4918
+	/**
4919
+	 * Returns whether or not this model has a relation to the specified model
4920
+	 *
4921
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4922
+	 * @return boolean
4923
+	 */
4924
+	public function has_relation($relation_name)
4925
+	{
4926
+		$relations = $this->relation_settings();
4927
+		if (isset($relations[ $relation_name ])) {
4928
+			return true;
4929
+		}
4930
+		return false;
4931
+	}
4932
+
4933
+
4934
+
4935
+	/**
4936
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4937
+	 * Eg, on EE_Answer that would be ANS_ID field object
4938
+	 *
4939
+	 * @param $field_obj
4940
+	 * @return boolean
4941
+	 */
4942
+	public function is_primary_key_field($field_obj)
4943
+	{
4944
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4945
+	}
4946
+
4947
+
4948
+
4949
+	/**
4950
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4951
+	 * Eg, on EE_Answer that would be ANS_ID field object
4952
+	 *
4953
+	 * @return EE_Model_Field_Base
4954
+	 * @throws EE_Error
4955
+	 */
4956
+	public function get_primary_key_field()
4957
+	{
4958
+		if ($this->_primary_key_field === null) {
4959
+			foreach ($this->field_settings(true) as $field_obj) {
4960
+				if ($this->is_primary_key_field($field_obj)) {
4961
+					$this->_primary_key_field = $field_obj;
4962
+					break;
4963
+				}
4964
+			}
4965
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4966
+				throw new EE_Error(sprintf(
4967
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4968
+					get_class($this)
4969
+				));
4970
+			}
4971
+		}
4972
+		return $this->_primary_key_field;
4973
+	}
4974
+
4975
+
4976
+
4977
+	/**
4978
+	 * Returns whether or not not there is a primary key on this model.
4979
+	 * Internally does some caching.
4980
+	 *
4981
+	 * @return boolean
4982
+	 */
4983
+	public function has_primary_key_field()
4984
+	{
4985
+		if ($this->_has_primary_key_field === null) {
4986
+			try {
4987
+				$this->get_primary_key_field();
4988
+				$this->_has_primary_key_field = true;
4989
+			} catch (EE_Error $e) {
4990
+				$this->_has_primary_key_field = false;
4991
+			}
4992
+		}
4993
+		return $this->_has_primary_key_field;
4994
+	}
4995
+
4996
+
4997
+
4998
+	/**
4999
+	 * Finds the first field of type $field_class_name.
5000
+	 *
5001
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5002
+	 *                                 EE_Foreign_Key_Field, etc
5003
+	 * @return EE_Model_Field_Base or null if none is found
5004
+	 */
5005
+	public function get_a_field_of_type($field_class_name)
5006
+	{
5007
+		foreach ($this->field_settings() as $field) {
5008
+			if ($field instanceof $field_class_name) {
5009
+				return $field;
5010
+			}
5011
+		}
5012
+		return null;
5013
+	}
5014
+
5015
+
5016
+
5017
+	/**
5018
+	 * Gets a foreign key field pointing to model.
5019
+	 *
5020
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5021
+	 * @return EE_Foreign_Key_Field_Base
5022
+	 * @throws EE_Error
5023
+	 */
5024
+	public function get_foreign_key_to($model_name)
5025
+	{
5026
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5027
+			foreach ($this->field_settings() as $field) {
5028
+				if (
5029
+					$field instanceof EE_Foreign_Key_Field_Base
5030
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5031
+				) {
5032
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5033
+					break;
5034
+				}
5035
+			}
5036
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5037
+				throw new EE_Error(sprintf(__(
5038
+					"There is no foreign key field pointing to model %s on model %s",
5039
+					'event_espresso'
5040
+				), $model_name, get_class($this)));
5041
+			}
5042
+		}
5043
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5044
+	}
5045
+
5046
+
5047
+
5048
+	/**
5049
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5050
+	 *
5051
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5052
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5053
+	 *                            Either one works
5054
+	 * @return string
5055
+	 */
5056
+	public function get_table_for_alias($table_alias)
5057
+	{
5058
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5059
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5060
+	}
5061
+
5062
+
5063
+
5064
+	/**
5065
+	 * Returns a flat array of all field son this model, instead of organizing them
5066
+	 * by table_alias as they are in the constructor.
5067
+	 *
5068
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5069
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5070
+	 */
5071
+	public function field_settings($include_db_only_fields = false)
5072
+	{
5073
+		if ($include_db_only_fields) {
5074
+			if ($this->_cached_fields === null) {
5075
+				$this->_cached_fields = array();
5076
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5077
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5078
+						$this->_cached_fields[ $field_name ] = $field_obj;
5079
+					}
5080
+				}
5081
+			}
5082
+			return $this->_cached_fields;
5083
+		}
5084
+		if ($this->_cached_fields_non_db_only === null) {
5085
+			$this->_cached_fields_non_db_only = array();
5086
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5087
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5088
+					/** @var $field_obj EE_Model_Field_Base */
5089
+					if (! $field_obj->is_db_only_field()) {
5090
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5091
+					}
5092
+				}
5093
+			}
5094
+		}
5095
+		return $this->_cached_fields_non_db_only;
5096
+	}
5097
+
5098
+
5099
+
5100
+	/**
5101
+	 *        cycle though array of attendees and create objects out of each item
5102
+	 *
5103
+	 * @access        private
5104
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5105
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5106
+	 *                           numerically indexed)
5107
+	 * @throws EE_Error
5108
+	 */
5109
+	protected function _create_objects($rows = array())
5110
+	{
5111
+		$array_of_objects = array();
5112
+		if (empty($rows)) {
5113
+			return array();
5114
+		}
5115
+		$count_if_model_has_no_primary_key = 0;
5116
+		$has_primary_key = $this->has_primary_key_field();
5117
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5118
+		foreach ((array) $rows as $row) {
5119
+			if (empty($row)) {
5120
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5121
+				return array();
5122
+			}
5123
+			// check if we've already set this object in the results array,
5124
+			// in which case there's no need to process it further (again)
5125
+			if ($has_primary_key) {
5126
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5127
+					$row,
5128
+					$primary_key_field->get_qualified_column(),
5129
+					$primary_key_field->get_table_column()
5130
+				);
5131
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5132
+					continue;
5133
+				}
5134
+			}
5135
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5136
+			if (! $classInstance) {
5137
+				throw new EE_Error(
5138
+					sprintf(
5139
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5140
+						$this->get_this_model_name(),
5141
+						http_build_query($row)
5142
+					)
5143
+				);
5144
+			}
5145
+			// set the timezone on the instantiated objects
5146
+			$classInstance->set_timezone($this->_timezone);
5147
+			// make sure if there is any timezone setting present that we set the timezone for the object
5148
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5149
+			$array_of_objects[ $key ] = $classInstance;
5150
+			// also, for all the relations of type BelongsTo, see if we can cache
5151
+			// those related models
5152
+			// (we could do this for other relations too, but if there are conditions
5153
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5154
+			// so it requires a little more thought than just caching them immediately...)
5155
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5156
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5157
+					// check if this model's INFO is present. If so, cache it on the model
5158
+					$other_model = $relation_obj->get_other_model();
5159
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5160
+					// if we managed to make a model object from the results, cache it on the main model object
5161
+					if ($other_model_obj_maybe) {
5162
+						// set timezone on these other model objects if they are present
5163
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5164
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5165
+					}
5166
+				}
5167
+			}
5168
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5169
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5170
+			// the field in the CustomSelects object
5171
+			if ($this->_custom_selections instanceof CustomSelects) {
5172
+				$classInstance->setCustomSelectsValues(
5173
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5174
+				);
5175
+			}
5176
+		}
5177
+		return $array_of_objects;
5178
+	}
5179
+
5180
+
5181
+	/**
5182
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5183
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5184
+	 *
5185
+	 * @param array $db_results_row
5186
+	 * @return array
5187
+	 */
5188
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5189
+	{
5190
+		$results = array();
5191
+		if ($this->_custom_selections instanceof CustomSelects) {
5192
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5193
+				if (isset($db_results_row[ $alias ])) {
5194
+					$results[ $alias ] = $this->convertValueToDataType(
5195
+						$db_results_row[ $alias ],
5196
+						$this->_custom_selections->getDataTypeForAlias($alias)
5197
+					);
5198
+				}
5199
+			}
5200
+		}
5201
+		return $results;
5202
+	}
5203
+
5204
+
5205
+	/**
5206
+	 * This will set the value for the given alias
5207
+	 * @param string $value
5208
+	 * @param string $datatype (one of %d, %s, %f)
5209
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5210
+	 */
5211
+	protected function convertValueToDataType($value, $datatype)
5212
+	{
5213
+		switch ($datatype) {
5214
+			case '%f':
5215
+				return (float) $value;
5216
+			case '%d':
5217
+				return (int) $value;
5218
+			default:
5219
+				return (string) $value;
5220
+		}
5221
+	}
5222
+
5223
+
5224
+	/**
5225
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5226
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5227
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5228
+	 * object (as set in the model_field!).
5229
+	 *
5230
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5231
+	 */
5232
+	public function create_default_object()
5233
+	{
5234
+		$this_model_fields_and_values = array();
5235
+		// setup the row using default values;
5236
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5237
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5238
+		}
5239
+		$className = $this->_get_class_name();
5240
+		$classInstance = EE_Registry::instance()
5241
+									->load_class($className, array($this_model_fields_and_values), false, false);
5242
+		return $classInstance;
5243
+	}
5244
+
5245
+
5246
+
5247
+	/**
5248
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5249
+	 *                             or an stdClass where each property is the name of a column,
5250
+	 * @return EE_Base_Class
5251
+	 * @throws EE_Error
5252
+	 */
5253
+	public function instantiate_class_from_array_or_object($cols_n_values)
5254
+	{
5255
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5256
+			$cols_n_values = get_object_vars($cols_n_values);
5257
+		}
5258
+		$primary_key = null;
5259
+		// make sure the array only has keys that are fields/columns on this model
5260
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5261
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5262
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5263
+		}
5264
+		$className = $this->_get_class_name();
5265
+		// check we actually found results that we can use to build our model object
5266
+		// if not, return null
5267
+		if ($this->has_primary_key_field()) {
5268
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5269
+				return null;
5270
+			}
5271
+		} elseif ($this->unique_indexes()) {
5272
+			$first_column = reset($this_model_fields_n_values);
5273
+			if (empty($first_column)) {
5274
+				return null;
5275
+			}
5276
+		}
5277
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5278
+		if ($primary_key) {
5279
+			$classInstance = $this->get_from_entity_map($primary_key);
5280
+			if (! $classInstance) {
5281
+				$classInstance = EE_Registry::instance()
5282
+											->load_class(
5283
+												$className,
5284
+												array($this_model_fields_n_values, $this->_timezone),
5285
+												true,
5286
+												false
5287
+											);
5288
+				// add this new object to the entity map
5289
+				$classInstance = $this->add_to_entity_map($classInstance);
5290
+			}
5291
+		} else {
5292
+			$classInstance = EE_Registry::instance()
5293
+										->load_class(
5294
+											$className,
5295
+											array($this_model_fields_n_values, $this->_timezone),
5296
+											true,
5297
+											false
5298
+										);
5299
+		}
5300
+		return $classInstance;
5301
+	}
5302
+
5303
+
5304
+
5305
+	/**
5306
+	 * Gets the model object from the  entity map if it exists
5307
+	 *
5308
+	 * @param int|string $id the ID of the model object
5309
+	 * @return EE_Base_Class
5310
+	 */
5311
+	public function get_from_entity_map($id)
5312
+	{
5313
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5314
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5315
+	}
5316
+
5317
+
5318
+
5319
+	/**
5320
+	 * add_to_entity_map
5321
+	 * Adds the object to the model's entity mappings
5322
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5323
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5324
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5325
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5326
+	 *        then this method should be called immediately after the update query
5327
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5328
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5329
+	 *
5330
+	 * @param    EE_Base_Class $object
5331
+	 * @throws EE_Error
5332
+	 * @return \EE_Base_Class
5333
+	 */
5334
+	public function add_to_entity_map(EE_Base_Class $object)
5335
+	{
5336
+		$className = $this->_get_class_name();
5337
+		if (! $object instanceof $className) {
5338
+			throw new EE_Error(sprintf(
5339
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5340
+				is_object($object) ? get_class($object) : $object,
5341
+				$className
5342
+			));
5343
+		}
5344
+		/** @var $object EE_Base_Class */
5345
+		if (! $object->ID()) {
5346
+			throw new EE_Error(sprintf(__(
5347
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5348
+				"event_espresso"
5349
+			), get_class($this)));
5350
+		}
5351
+		// double check it's not already there
5352
+		$classInstance = $this->get_from_entity_map($object->ID());
5353
+		if ($classInstance) {
5354
+			return $classInstance;
5355
+		}
5356
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5357
+		return $object;
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5364
+	 * if no identifier is provided, then the entire entity map is emptied
5365
+	 *
5366
+	 * @param int|string $id the ID of the model object
5367
+	 * @return boolean
5368
+	 */
5369
+	public function clear_entity_map($id = null)
5370
+	{
5371
+		if (empty($id)) {
5372
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5373
+			return true;
5374
+		}
5375
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5376
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5377
+			return true;
5378
+		}
5379
+		return false;
5380
+	}
5381
+
5382
+
5383
+
5384
+	/**
5385
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5386
+	 * Given an array where keys are column (or column alias) names and values,
5387
+	 * returns an array of their corresponding field names and database values
5388
+	 *
5389
+	 * @param array $cols_n_values
5390
+	 * @return array
5391
+	 */
5392
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5393
+	{
5394
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5395
+	}
5396
+
5397
+
5398
+
5399
+	/**
5400
+	 * _deduce_fields_n_values_from_cols_n_values
5401
+	 * Given an array where keys are column (or column alias) names and values,
5402
+	 * returns an array of their corresponding field names and database values
5403
+	 *
5404
+	 * @param string $cols_n_values
5405
+	 * @return array
5406
+	 */
5407
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5408
+	{
5409
+		$this_model_fields_n_values = array();
5410
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5411
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5412
+				$cols_n_values,
5413
+				$table_obj->get_fully_qualified_pk_column(),
5414
+				$table_obj->get_pk_column()
5415
+			);
5416
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5417
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5418
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5419
+					if (! $field_obj->is_db_only_field()) {
5420
+						// prepare field as if its coming from db
5421
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5422
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5423
+					}
5424
+				}
5425
+			} else {
5426
+				// the table's rows existed. Use their values
5427
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5428
+					if (! $field_obj->is_db_only_field()) {
5429
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5430
+							$cols_n_values,
5431
+							$field_obj->get_qualified_column(),
5432
+							$field_obj->get_table_column()
5433
+						);
5434
+					}
5435
+				}
5436
+			}
5437
+		}
5438
+		return $this_model_fields_n_values;
5439
+	}
5440
+
5441
+
5442
+	/**
5443
+	 * @param $cols_n_values
5444
+	 * @param $qualified_column
5445
+	 * @param $regular_column
5446
+	 * @return null
5447
+	 * @throws EE_Error
5448
+	 * @throws ReflectionException
5449
+	 */
5450
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5451
+	{
5452
+		$value = null;
5453
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5454
+		// does the field on the model relate to this column retrieved from the db?
5455
+		// or is it a db-only field? (not relating to the model)
5456
+		if (isset($cols_n_values[ $qualified_column ])) {
5457
+			$value = $cols_n_values[ $qualified_column ];
5458
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5459
+			$value = $cols_n_values[ $regular_column ];
5460
+		} elseif (! empty($this->foreign_key_aliases)) {
5461
+			// no PK?  ok check if there is a foreign key alias set for this table
5462
+			// then check if that alias exists in the incoming data
5463
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5464
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5465
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5466
+					$value = $cols_n_values[ $FK_alias ];
5467
+					[$pk_class] = explode('.', $PK_column);
5468
+					$pk_model_name = "EEM_{$pk_class}";
5469
+					/** @var EEM_Base $pk_model */
5470
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5471
+					if ($pk_model instanceof EEM_Base) {
5472
+						// make sure object is pulled from db and added to entity map
5473
+						$pk_model->get_one_by_ID($value);
5474
+					}
5475
+					break;
5476
+				}
5477
+			}
5478
+		}
5479
+		return $value;
5480
+	}
5481
+
5482
+
5483
+
5484
+	/**
5485
+	 * refresh_entity_map_from_db
5486
+	 * Makes sure the model object in the entity map at $id assumes the values
5487
+	 * of the database (opposite of EE_base_Class::save())
5488
+	 *
5489
+	 * @param int|string $id
5490
+	 * @return EE_Base_Class
5491
+	 * @throws EE_Error
5492
+	 */
5493
+	public function refresh_entity_map_from_db($id)
5494
+	{
5495
+		$obj_in_map = $this->get_from_entity_map($id);
5496
+		if ($obj_in_map) {
5497
+			$wpdb_results = $this->_get_all_wpdb_results(
5498
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5499
+			);
5500
+			if ($wpdb_results && is_array($wpdb_results)) {
5501
+				$one_row = reset($wpdb_results);
5502
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5503
+					$obj_in_map->set_from_db($field_name, $db_value);
5504
+				}
5505
+				// clear the cache of related model objects
5506
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5507
+					$obj_in_map->clear_cache($relation_name, null, true);
5508
+				}
5509
+			}
5510
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5511
+			return $obj_in_map;
5512
+		}
5513
+		return $this->get_one_by_ID($id);
5514
+	}
5515
+
5516
+
5517
+
5518
+	/**
5519
+	 * refresh_entity_map_with
5520
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5521
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5522
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5523
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5524
+	 *
5525
+	 * @param int|string    $id
5526
+	 * @param EE_Base_Class $replacing_model_obj
5527
+	 * @return \EE_Base_Class
5528
+	 * @throws EE_Error
5529
+	 */
5530
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5531
+	{
5532
+		$obj_in_map = $this->get_from_entity_map($id);
5533
+		if ($obj_in_map) {
5534
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5535
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5536
+					$obj_in_map->set($field_name, $value);
5537
+				}
5538
+				// make the model object in the entity map's cache match the $replacing_model_obj
5539
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5540
+					$obj_in_map->clear_cache($relation_name, null, true);
5541
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5542
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5543
+					}
5544
+				}
5545
+			}
5546
+			return $obj_in_map;
5547
+		}
5548
+		$this->add_to_entity_map($replacing_model_obj);
5549
+		return $replacing_model_obj;
5550
+	}
5551
+
5552
+
5553
+
5554
+	/**
5555
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5556
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5557
+	 * require_once($this->_getClassName().".class.php");
5558
+	 *
5559
+	 * @return string
5560
+	 */
5561
+	private function _get_class_name()
5562
+	{
5563
+		return "EE_" . $this->get_this_model_name();
5564
+	}
5565
+
5566
+
5567
+
5568
+	/**
5569
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5570
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5571
+	 * it would be 'Events'.
5572
+	 *
5573
+	 * @param int $quantity
5574
+	 * @return string
5575
+	 */
5576
+	public function item_name($quantity = 1)
5577
+	{
5578
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5579
+	}
5580
+
5581
+
5582
+
5583
+	/**
5584
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5585
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5586
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5587
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5588
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5589
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5590
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5591
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5592
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5593
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5594
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5595
+	 *        return $previousReturnValue.$returnString;
5596
+	 * }
5597
+	 * require('EEM_Answer.model.php');
5598
+	 * $answer=EEM_Answer::instance();
5599
+	 * echo $answer->my_callback('monkeys',100);
5600
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5601
+	 *
5602
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5603
+	 * @param array  $args       array of original arguments passed to the function
5604
+	 * @throws EE_Error
5605
+	 * @return mixed whatever the plugin which calls add_filter decides
5606
+	 */
5607
+	public function __call($methodName, $args)
5608
+	{
5609
+		$className = get_class($this);
5610
+		$tagName = "FHEE__{$className}__{$methodName}";
5611
+		if (! has_filter($tagName)) {
5612
+			throw new EE_Error(
5613
+				sprintf(
5614
+					__(
5615
+						'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 );',
5616
+						'event_espresso'
5617
+					),
5618
+					$methodName,
5619
+					$className,
5620
+					$tagName,
5621
+					'<br />'
5622
+				)
5623
+			);
5624
+		}
5625
+		return apply_filters($tagName, null, $this, $args);
5626
+	}
5627
+
5628
+
5629
+
5630
+	/**
5631
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5632
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5633
+	 *
5634
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5635
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5636
+	 *                                                       the object's class name
5637
+	 *                                                       or object's ID
5638
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5639
+	 *                                                       exists in the database. If it does not, we add it
5640
+	 * @throws EE_Error
5641
+	 * @return EE_Base_Class
5642
+	 */
5643
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5644
+	{
5645
+		$className = $this->_get_class_name();
5646
+		if ($base_class_obj_or_id instanceof $className) {
5647
+			$model_object = $base_class_obj_or_id;
5648
+		} else {
5649
+			$primary_key_field = $this->get_primary_key_field();
5650
+			if (
5651
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5652
+				&& (
5653
+					is_int($base_class_obj_or_id)
5654
+					|| is_string($base_class_obj_or_id)
5655
+				)
5656
+			) {
5657
+				// assume it's an ID.
5658
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5659
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5660
+			} elseif (
5661
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5662
+				&& is_string($base_class_obj_or_id)
5663
+			) {
5664
+				// assume its a string representation of the object
5665
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5666
+			} else {
5667
+				throw new EE_Error(
5668
+					sprintf(
5669
+						__(
5670
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5671
+							'event_espresso'
5672
+						),
5673
+						$base_class_obj_or_id,
5674
+						$this->_get_class_name(),
5675
+						print_r($base_class_obj_or_id, true)
5676
+					)
5677
+				);
5678
+			}
5679
+		}
5680
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5681
+			$model_object->save();
5682
+		}
5683
+		return $model_object;
5684
+	}
5685
+
5686
+
5687
+
5688
+	/**
5689
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5690
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5691
+	 * returns it ID.
5692
+	 *
5693
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5694
+	 * @return int|string depending on the type of this model object's ID
5695
+	 * @throws EE_Error
5696
+	 */
5697
+	public function ensure_is_ID($base_class_obj_or_id)
5698
+	{
5699
+		$className = $this->_get_class_name();
5700
+		if ($base_class_obj_or_id instanceof $className) {
5701
+			/** @var $base_class_obj_or_id EE_Base_Class */
5702
+			$id = $base_class_obj_or_id->ID();
5703
+		} elseif (is_int($base_class_obj_or_id)) {
5704
+			// assume it's an ID
5705
+			$id = $base_class_obj_or_id;
5706
+		} elseif (is_string($base_class_obj_or_id)) {
5707
+			// assume its a string representation of the object
5708
+			$id = $base_class_obj_or_id;
5709
+		} else {
5710
+			throw new EE_Error(sprintf(
5711
+				__(
5712
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5713
+					'event_espresso'
5714
+				),
5715
+				$base_class_obj_or_id,
5716
+				$this->_get_class_name(),
5717
+				print_r($base_class_obj_or_id, true)
5718
+			));
5719
+		}
5720
+		return $id;
5721
+	}
5722
+
5723
+
5724
+
5725
+	/**
5726
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5727
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5728
+	 * been sanitized and converted into the appropriate domain.
5729
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5730
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5731
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5732
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5733
+	 * $EVT = EEM_Event::instance(); $old_setting =
5734
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5735
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5736
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5737
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5738
+	 *
5739
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5740
+	 * @return void
5741
+	 */
5742
+	public function assume_values_already_prepared_by_model_object(
5743
+		$values_already_prepared = self::not_prepared_by_model_object
5744
+	) {
5745
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5746
+	}
5747
+
5748
+
5749
+
5750
+	/**
5751
+	 * Read comments for assume_values_already_prepared_by_model_object()
5752
+	 *
5753
+	 * @return int
5754
+	 */
5755
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5756
+	{
5757
+		return $this->_values_already_prepared_by_model_object;
5758
+	}
5759
+
5760
+
5761
+
5762
+	/**
5763
+	 * Gets all the indexes on this model
5764
+	 *
5765
+	 * @return EE_Index[]
5766
+	 */
5767
+	public function indexes()
5768
+	{
5769
+		return $this->_indexes;
5770
+	}
5771
+
5772
+
5773
+
5774
+	/**
5775
+	 * Gets all the Unique Indexes on this model
5776
+	 *
5777
+	 * @return EE_Unique_Index[]
5778
+	 */
5779
+	public function unique_indexes()
5780
+	{
5781
+		$unique_indexes = array();
5782
+		foreach ($this->_indexes as $name => $index) {
5783
+			if ($index instanceof EE_Unique_Index) {
5784
+				$unique_indexes [ $name ] = $index;
5785
+			}
5786
+		}
5787
+		return $unique_indexes;
5788
+	}
5789
+
5790
+
5791
+
5792
+	/**
5793
+	 * Gets all the fields which, when combined, make the primary key.
5794
+	 * This is usually just an array with 1 element (the primary key), but in cases
5795
+	 * where there is no primary key, it's a combination of fields as defined
5796
+	 * on a primary index
5797
+	 *
5798
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5799
+	 * @throws EE_Error
5800
+	 */
5801
+	public function get_combined_primary_key_fields()
5802
+	{
5803
+		foreach ($this->indexes() as $index) {
5804
+			if ($index instanceof EE_Primary_Key_Index) {
5805
+				return $index->fields();
5806
+			}
5807
+		}
5808
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5809
+	}
5810
+
5811
+
5812
+
5813
+	/**
5814
+	 * Used to build a primary key string (when the model has no primary key),
5815
+	 * which can be used a unique string to identify this model object.
5816
+	 *
5817
+	 * @param array $fields_n_values keys are field names, values are their values.
5818
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5819
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5820
+	 *                               before passing it to this function (that will convert it from columns-n-values
5821
+	 *                               to field-names-n-values).
5822
+	 * @return string
5823
+	 * @throws EE_Error
5824
+	 */
5825
+	public function get_index_primary_key_string($fields_n_values)
5826
+	{
5827
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5828
+			$fields_n_values,
5829
+			$this->get_combined_primary_key_fields()
5830
+		);
5831
+		return http_build_query($cols_n_values_for_primary_key_index);
5832
+	}
5833
+
5834
+
5835
+
5836
+	/**
5837
+	 * Gets the field values from the primary key string
5838
+	 *
5839
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5840
+	 * @param string $index_primary_key_string
5841
+	 * @return null|array
5842
+	 * @throws EE_Error
5843
+	 */
5844
+	public function parse_index_primary_key_string($index_primary_key_string)
5845
+	{
5846
+		$key_fields = $this->get_combined_primary_key_fields();
5847
+		// check all of them are in the $id
5848
+		$key_vals_in_combined_pk = array();
5849
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5850
+		foreach ($key_fields as $key_field_name => $field_obj) {
5851
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5852
+				return null;
5853
+			}
5854
+		}
5855
+		return $key_vals_in_combined_pk;
5856
+	}
5857
+
5858
+
5859
+
5860
+	/**
5861
+	 * verifies that an array of key-value pairs for model fields has a key
5862
+	 * for each field comprising the primary key index
5863
+	 *
5864
+	 * @param array $key_vals
5865
+	 * @return boolean
5866
+	 * @throws EE_Error
5867
+	 */
5868
+	public function has_all_combined_primary_key_fields($key_vals)
5869
+	{
5870
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5871
+		foreach ($keys_it_should_have as $key) {
5872
+			if (! isset($key_vals[ $key ])) {
5873
+				return false;
5874
+			}
5875
+		}
5876
+		return true;
5877
+	}
5878
+
5879
+
5880
+
5881
+	/**
5882
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5883
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5884
+	 *
5885
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5886
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5887
+	 * @throws EE_Error
5888
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5889
+	 *                                                              indexed)
5890
+	 */
5891
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5892
+	{
5893
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5894
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5895
+		} elseif (is_array($model_object_or_attributes_array)) {
5896
+			$attributes_array = $model_object_or_attributes_array;
5897
+		} else {
5898
+			throw new EE_Error(sprintf(__(
5899
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5900
+				"event_espresso"
5901
+			), $model_object_or_attributes_array));
5902
+		}
5903
+		// even copies obviously won't have the same ID, so remove the primary key
5904
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5905
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5906
+			unset($attributes_array[ $this->primary_key_name() ]);
5907
+		}
5908
+		if (isset($query_params[0])) {
5909
+			$query_params[0] = array_merge($attributes_array, $query_params);
5910
+		} else {
5911
+			$query_params[0] = $attributes_array;
5912
+		}
5913
+		return $this->get_all($query_params);
5914
+	}
5915
+
5916
+
5917
+
5918
+	/**
5919
+	 * Gets the first copy we find. See get_all_copies for more details
5920
+	 *
5921
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5922
+	 * @param array $query_params
5923
+	 * @return EE_Base_Class
5924
+	 * @throws EE_Error
5925
+	 */
5926
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5927
+	{
5928
+		if (! is_array($query_params)) {
5929
+			EE_Error::doing_it_wrong(
5930
+				'EEM_Base::get_one_copy',
5931
+				sprintf(
5932
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5933
+					gettype($query_params)
5934
+				),
5935
+				'4.6.0'
5936
+			);
5937
+			$query_params = array();
5938
+		}
5939
+		$query_params['limit'] = 1;
5940
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5941
+		if (is_array($copies)) {
5942
+			return array_shift($copies);
5943
+		}
5944
+		return null;
5945
+	}
5946
+
5947
+
5948
+
5949
+	/**
5950
+	 * Updates the item with the specified id. Ignores default query parameters because
5951
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5952
+	 *
5953
+	 * @param array      $fields_n_values keys are field names, values are their new values
5954
+	 * @param int|string $id              the value of the primary key to update
5955
+	 * @return int number of rows updated
5956
+	 * @throws EE_Error
5957
+	 */
5958
+	public function update_by_ID($fields_n_values, $id)
5959
+	{
5960
+		$query_params = array(
5961
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5962
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5963
+		);
5964
+		return $this->update($fields_n_values, $query_params);
5965
+	}
5966
+
5967
+
5968
+
5969
+	/**
5970
+	 * Changes an operator which was supplied to the models into one usable in SQL
5971
+	 *
5972
+	 * @param string $operator_supplied
5973
+	 * @return string an operator which can be used in SQL
5974
+	 * @throws EE_Error
5975
+	 */
5976
+	private function _prepare_operator_for_sql($operator_supplied)
5977
+	{
5978
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5979
+			: null;
5980
+		if ($sql_operator) {
5981
+			return $sql_operator;
5982
+		}
5983
+		throw new EE_Error(
5984
+			sprintf(
5985
+				__(
5986
+					"The operator '%s' is not in the list of valid operators: %s",
5987
+					"event_espresso"
5988
+				),
5989
+				$operator_supplied,
5990
+				implode(",", array_keys($this->_valid_operators))
5991
+			)
5992
+		);
5993
+	}
5994
+
5995
+
5996
+
5997
+	/**
5998
+	 * Gets the valid operators
5999
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6000
+	 */
6001
+	public function valid_operators()
6002
+	{
6003
+		return $this->_valid_operators;
6004
+	}
6005
+
6006
+
6007
+
6008
+	/**
6009
+	 * Gets the between-style operators (take 2 arguments).
6010
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6011
+	 */
6012
+	public function valid_between_style_operators()
6013
+	{
6014
+		return array_intersect(
6015
+			$this->valid_operators(),
6016
+			$this->_between_style_operators
6017
+		);
6018
+	}
6019
+
6020
+	/**
6021
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6022
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6023
+	 */
6024
+	public function valid_like_style_operators()
6025
+	{
6026
+		return array_intersect(
6027
+			$this->valid_operators(),
6028
+			$this->_like_style_operators
6029
+		);
6030
+	}
6031
+
6032
+	/**
6033
+	 * Gets the "in"-style operators
6034
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6035
+	 */
6036
+	public function valid_in_style_operators()
6037
+	{
6038
+		return array_intersect(
6039
+			$this->valid_operators(),
6040
+			$this->_in_style_operators
6041
+		);
6042
+	}
6043
+
6044
+	/**
6045
+	 * Gets the "null"-style operators (accept no arguments)
6046
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6047
+	 */
6048
+	public function valid_null_style_operators()
6049
+	{
6050
+		return array_intersect(
6051
+			$this->valid_operators(),
6052
+			$this->_null_style_operators
6053
+		);
6054
+	}
6055
+
6056
+	/**
6057
+	 * Gets an array where keys are the primary keys and values are their 'names'
6058
+	 * (as determined by the model object's name() function, which is often overridden)
6059
+	 *
6060
+	 * @param array $query_params like get_all's
6061
+	 * @return string[]
6062
+	 * @throws EE_Error
6063
+	 */
6064
+	public function get_all_names($query_params = array())
6065
+	{
6066
+		$objs = $this->get_all($query_params);
6067
+		$names = array();
6068
+		foreach ($objs as $obj) {
6069
+			$names[ $obj->ID() ] = $obj->name();
6070
+		}
6071
+		return $names;
6072
+	}
6073
+
6074
+
6075
+
6076
+	/**
6077
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6078
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6079
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6080
+	 * array_keys() on $model_objects.
6081
+	 *
6082
+	 * @param \EE_Base_Class[] $model_objects
6083
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6084
+	 *                                               in the returned array
6085
+	 * @return array
6086
+	 * @throws EE_Error
6087
+	 */
6088
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6089
+	{
6090
+		if (! $this->has_primary_key_field()) {
6091
+			if (WP_DEBUG) {
6092
+				EE_Error::add_error(
6093
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6094
+					__FILE__,
6095
+					__FUNCTION__,
6096
+					__LINE__
6097
+				);
6098
+			}
6099
+		}
6100
+		$IDs = array();
6101
+		foreach ($model_objects as $model_object) {
6102
+			$id = $model_object->ID();
6103
+			if (! $id) {
6104
+				if ($filter_out_empty_ids) {
6105
+					continue;
6106
+				}
6107
+				if (WP_DEBUG) {
6108
+					EE_Error::add_error(
6109
+						__(
6110
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6111
+							'event_espresso'
6112
+						),
6113
+						__FILE__,
6114
+						__FUNCTION__,
6115
+						__LINE__
6116
+					);
6117
+				}
6118
+			}
6119
+			$IDs[] = $id;
6120
+		}
6121
+		return $IDs;
6122
+	}
6123
+
6124
+
6125
+
6126
+	/**
6127
+	 * Returns the string used in capabilities relating to this model. If there
6128
+	 * are no capabilities that relate to this model returns false
6129
+	 *
6130
+	 * @return string|false
6131
+	 */
6132
+	public function cap_slug()
6133
+	{
6134
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6135
+	}
6136
+
6137
+
6138
+
6139
+	/**
6140
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6141
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6142
+	 * only returns the cap restrictions array in that context (ie, the array
6143
+	 * at that key)
6144
+	 *
6145
+	 * @param string $context
6146
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6147
+	 * @throws EE_Error
6148
+	 */
6149
+	public function cap_restrictions($context = EEM_Base::caps_read)
6150
+	{
6151
+		EEM_Base::verify_is_valid_cap_context($context);
6152
+		// check if we ought to run the restriction generator first
6153
+		if (
6154
+			isset($this->_cap_restriction_generators[ $context ])
6155
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6156
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6157
+		) {
6158
+			$this->_cap_restrictions[ $context ] = array_merge(
6159
+				$this->_cap_restrictions[ $context ],
6160
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6161
+			);
6162
+		}
6163
+		// and make sure we've finalized the construction of each restriction
6164
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6165
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6166
+				$where_conditions_obj->_finalize_construct($this);
6167
+			}
6168
+		}
6169
+		return $this->_cap_restrictions[ $context ];
6170
+	}
6171
+
6172
+
6173
+
6174
+	/**
6175
+	 * Indicating whether or not this model thinks its a wp core model
6176
+	 *
6177
+	 * @return boolean
6178
+	 */
6179
+	public function is_wp_core_model()
6180
+	{
6181
+		return $this->_wp_core_model;
6182
+	}
6183
+
6184
+
6185
+
6186
+	/**
6187
+	 * Gets all the caps that are missing which impose a restriction on
6188
+	 * queries made in this context
6189
+	 *
6190
+	 * @param string $context one of EEM_Base::caps_ constants
6191
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6192
+	 * @throws EE_Error
6193
+	 */
6194
+	public function caps_missing($context = EEM_Base::caps_read)
6195
+	{
6196
+		$missing_caps = array();
6197
+		$cap_restrictions = $this->cap_restrictions($context);
6198
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6199
+			if (
6200
+				! EE_Capabilities::instance()
6201
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6202
+			) {
6203
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6204
+			}
6205
+		}
6206
+		return $missing_caps;
6207
+	}
6208
+
6209
+
6210
+
6211
+	/**
6212
+	 * Gets the mapping from capability contexts to action strings used in capability names
6213
+	 *
6214
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6215
+	 * one of 'read', 'edit', or 'delete'
6216
+	 */
6217
+	public function cap_contexts_to_cap_action_map()
6218
+	{
6219
+		return apply_filters(
6220
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6221
+			$this->_cap_contexts_to_cap_action_map,
6222
+			$this
6223
+		);
6224
+	}
6225
+
6226
+
6227
+
6228
+	/**
6229
+	 * Gets the action string for the specified capability context
6230
+	 *
6231
+	 * @param string $context
6232
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6233
+	 * @throws EE_Error
6234
+	 */
6235
+	public function cap_action_for_context($context)
6236
+	{
6237
+		$mapping = $this->cap_contexts_to_cap_action_map();
6238
+		if (isset($mapping[ $context ])) {
6239
+			return $mapping[ $context ];
6240
+		}
6241
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6242
+			return $action;
6243
+		}
6244
+		throw new EE_Error(
6245
+			sprintf(
6246
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6247
+				$context,
6248
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6249
+			)
6250
+		);
6251
+	}
6252
+
6253
+
6254
+
6255
+	/**
6256
+	 * Returns all the capability contexts which are valid when querying models
6257
+	 *
6258
+	 * @return array
6259
+	 */
6260
+	public static function valid_cap_contexts()
6261
+	{
6262
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6263
+			self::caps_read,
6264
+			self::caps_read_admin,
6265
+			self::caps_edit,
6266
+			self::caps_delete,
6267
+		));
6268
+	}
6269
+
6270
+
6271
+
6272
+	/**
6273
+	 * Returns all valid options for 'default_where_conditions'
6274
+	 *
6275
+	 * @return array
6276
+	 */
6277
+	public static function valid_default_where_conditions()
6278
+	{
6279
+		return array(
6280
+			EEM_Base::default_where_conditions_all,
6281
+			EEM_Base::default_where_conditions_this_only,
6282
+			EEM_Base::default_where_conditions_others_only,
6283
+			EEM_Base::default_where_conditions_minimum_all,
6284
+			EEM_Base::default_where_conditions_minimum_others,
6285
+			EEM_Base::default_where_conditions_none
6286
+		);
6287
+	}
6288
+
6289
+	// public static function default_where_conditions_full
6290
+	/**
6291
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6292
+	 *
6293
+	 * @param string $context
6294
+	 * @return bool
6295
+	 * @throws EE_Error
6296
+	 */
6297
+	public static function verify_is_valid_cap_context($context)
6298
+	{
6299
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6300
+		if (in_array($context, $valid_cap_contexts)) {
6301
+			return true;
6302
+		}
6303
+		throw new EE_Error(
6304
+			sprintf(
6305
+				__(
6306
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6307
+					'event_espresso'
6308
+				),
6309
+				$context,
6310
+				'EEM_Base',
6311
+				implode(',', $valid_cap_contexts)
6312
+			)
6313
+		);
6314
+	}
6315
+
6316
+
6317
+
6318
+	/**
6319
+	 * Clears all the models field caches. This is only useful when a sub-class
6320
+	 * might have added a field or something and these caches might be invalidated
6321
+	 */
6322
+	protected function _invalidate_field_caches()
6323
+	{
6324
+		$this->_cache_foreign_key_to_fields = array();
6325
+		$this->_cached_fields = null;
6326
+		$this->_cached_fields_non_db_only = null;
6327
+	}
6328
+
6329
+
6330
+
6331
+	/**
6332
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6333
+	 * (eg "and", "or", "not").
6334
+	 *
6335
+	 * @return array
6336
+	 */
6337
+	public function logic_query_param_keys()
6338
+	{
6339
+		return $this->_logic_query_param_keys;
6340
+	}
6341
+
6342
+
6343
+
6344
+	/**
6345
+	 * Determines whether or not the where query param array key is for a logic query param.
6346
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6347
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6348
+	 *
6349
+	 * @param $query_param_key
6350
+	 * @return bool
6351
+	 */
6352
+	public function is_logic_query_param_key($query_param_key)
6353
+	{
6354
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6355
+			if (
6356
+				$query_param_key === $logic_query_param_key
6357
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6358
+			) {
6359
+				return true;
6360
+			}
6361
+		}
6362
+		return false;
6363
+	}
6364
+
6365
+	/**
6366
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6367
+	 * @since 4.9.74.p
6368
+	 * @return boolean
6369
+	 */
6370
+	public function hasPassword()
6371
+	{
6372
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6373
+		if ($this->has_password_field === null) {
6374
+			$password_field = $this->getPasswordField();
6375
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6376
+		}
6377
+		return $this->has_password_field;
6378
+	}
6379
+
6380
+	/**
6381
+	 * Returns the password field on this model, if there is one
6382
+	 * @since 4.9.74.p
6383
+	 * @return EE_Password_Field|null
6384
+	 */
6385
+	public function getPasswordField()
6386
+	{
6387
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6388
+		// there's no need to search for it. If we don't know yet, then find out
6389
+		if ($this->has_password_field === null && $this->password_field === null) {
6390
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6391
+		}
6392
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6393
+		return $this->password_field;
6394
+	}
6395
+
6396
+
6397
+	/**
6398
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6399
+	 * @since 4.9.74.p
6400
+	 * @return EE_Model_Field_Base[]
6401
+	 * @throws EE_Error
6402
+	 */
6403
+	public function getPasswordProtectedFields()
6404
+	{
6405
+		$password_field = $this->getPasswordField();
6406
+		$fields = array();
6407
+		if ($password_field instanceof EE_Password_Field) {
6408
+			$field_names = $password_field->protectedFields();
6409
+			foreach ($field_names as $field_name) {
6410
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6411
+			}
6412
+		}
6413
+		return $fields;
6414
+	}
6415
+
6416
+
6417
+	/**
6418
+	 * Checks if the current user can perform the requested action on this model
6419
+	 * @since 4.9.74.p
6420
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6421
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6422
+	 * @return bool
6423
+	 * @throws EE_Error
6424
+	 * @throws InvalidArgumentException
6425
+	 * @throws InvalidDataTypeException
6426
+	 * @throws InvalidInterfaceException
6427
+	 * @throws ReflectionException
6428
+	 * @throws UnexpectedEntityException
6429
+	 */
6430
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6431
+	{
6432
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6433
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6434
+		}
6435
+		if (!is_array($model_obj_or_fields_n_values)) {
6436
+			throw new UnexpectedEntityException(
6437
+				$model_obj_or_fields_n_values,
6438
+				'EE_Base_Class',
6439
+				sprintf(
6440
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6441
+					__FUNCTION__
6442
+				)
6443
+			);
6444
+		}
6445
+		return $this->exists(
6446
+			$this->alter_query_params_to_restrict_by_ID(
6447
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6448
+				array(
6449
+					'default_where_conditions' => 'none',
6450
+					'caps'                     => $cap_to_check,
6451
+				)
6452
+			)
6453
+		);
6454
+	}
6455
+
6456
+	/**
6457
+	 * Returns the query param where conditions key to the password affecting this model.
6458
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6459
+	 * @since 4.9.74.p
6460
+	 * @return null|string
6461
+	 * @throws EE_Error
6462
+	 * @throws InvalidArgumentException
6463
+	 * @throws InvalidDataTypeException
6464
+	 * @throws InvalidInterfaceException
6465
+	 * @throws ModelConfigurationException
6466
+	 * @throws ReflectionException
6467
+	 */
6468
+	public function modelChainAndPassword()
6469
+	{
6470
+		if ($this->model_chain_to_password === null) {
6471
+			throw new ModelConfigurationException(
6472
+				$this,
6473
+				esc_html_x(
6474
+				// @codingStandardsIgnoreStart
6475
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6476
+					// @codingStandardsIgnoreEnd
6477
+					'1: model name',
6478
+					'event_espresso'
6479
+				)
6480
+			);
6481
+		}
6482
+		if ($this->model_chain_to_password === '') {
6483
+			$model_with_password = $this;
6484
+		} else {
6485
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6486
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6487
+			} else {
6488
+				$last_model_in_chain = $this->model_chain_to_password;
6489
+			}
6490
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6491
+		}
6492
+
6493
+		$password_field = $model_with_password->getPasswordField();
6494
+		if ($password_field instanceof EE_Password_Field) {
6495
+			$password_field_name = $password_field->get_name();
6496
+		} else {
6497
+			throw new ModelConfigurationException(
6498
+				$this,
6499
+				sprintf(
6500
+					esc_html_x(
6501
+						'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"',
6502
+						'1: model name, 2: special string',
6503
+						'event_espresso'
6504
+					),
6505
+					$model_with_password->get_this_model_name(),
6506
+					$this->model_chain_to_password
6507
+				)
6508
+			);
6509
+		}
6510
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6511
+	}
6512
+
6513
+	/**
6514
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6515
+	 * or if this model itself has a password affecting access to some of its other fields.
6516
+	 * @since 4.9.74.p
6517
+	 * @return boolean
6518
+	 */
6519
+	public function restrictedByRelatedModelPassword()
6520
+	{
6521
+		return $this->model_chain_to_password !== null;
6522
+	}
6523 6523
 }
Please login to merge, or discard this patch.
Spacing   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -556,7 +556,7 @@  discard block
 block discarded – undo
556 556
     protected function __construct($timezone = null)
557 557
     {
558 558
         // check that the model has not been loaded too soon
559
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
560 560
             throw new EE_Error(
561 561
                 sprintf(
562 562
                     __(
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
          *
580 580
          * @var EE_Table_Base[] $_tables
581 581
          */
582
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
583 583
         foreach ($this->_tables as $table_alias => $table_obj) {
584 584
             /** @var $table_obj EE_Table_Base */
585 585
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -594,10 +594,10 @@  discard block
 block discarded – undo
594 594
          *
595 595
          * @param EE_Model_Field_Base[] $_fields
596 596
          */
597
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
598 598
         $this->_invalidate_field_caches();
599 599
         foreach ($this->_fields as $table_alias => $fields_for_table) {
600
-            if (! array_key_exists($table_alias, $this->_tables)) {
600
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
601 601
                 throw new EE_Error(sprintf(__(
602 602
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
603 603
                     'event_espresso'
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
          * @param EE_Model_Relation_Base[] $_model_relations
629 629
          */
630 630
         $this->_model_relations = (array) apply_filters(
631
-            'FHEE__' . get_class($this) . '__construct__model_relations',
631
+            'FHEE__'.get_class($this).'__construct__model_relations',
632 632
             $this->_model_relations
633 633
         );
634 634
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -640,12 +640,12 @@  discard block
 block discarded – undo
640 640
         }
641 641
         $this->set_timezone($timezone);
642 642
         // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
643
+        if ( ! $this->_default_where_conditions_strategy) {
644 644
             // nothing was set during child constructor, so set default
645 645
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646 646
         }
647 647
         $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
648
+        if ( ! $this->_minimum_where_conditions_strategy) {
649 649
             // nothing was set during child constructor, so set default
650 650
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651 651
         }
@@ -656,10 +656,10 @@  discard block
 block discarded – undo
656 656
             $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657 657
         }
658 658
         // initialize the standard cap restriction generators if none were specified by the child constructor
659
-        if (! empty($this->_cap_restriction_generators)) {
659
+        if ( ! empty($this->_cap_restriction_generators)) {
660 660
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
661
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
662
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
663 663
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664 664
                         new EE_Restriction_Generator_Protected(),
665 665
                         $cap_context,
@@ -669,12 +669,12 @@  discard block
 block discarded – undo
669 669
             }
670 670
         }
671 671
         // if there are cap restriction generators, use them to make the default cap restrictions
672
-        if (! empty($this->_cap_restriction_generators)) {
672
+        if ( ! empty($this->_cap_restriction_generators)) {
673 673
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
674
+                if ( ! $generator_object) {
675 675
                     continue;
676 676
                 }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
678 678
                     throw new EE_Error(
679 679
                         sprintf(
680 680
                             __(
@@ -687,12 +687,12 @@  discard block
 block discarded – undo
687 687
                     );
688 688
                 }
689 689
                 $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
690
+                if ( ! $generator_object->construction_finalized()) {
691 691
                     $generator_object->_construct_finalize($this, $action);
692 692
                 }
693 693
             }
694 694
         }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
+        do_action('AHEE__'.get_class($this).'__construct__end');
696 696
     }
697 697
 
698 698
 
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
     public static function instance($timezone = null)
740 740
     {
741 741
         // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
742
+        if ( ! static::$_instance instanceof static) {
743 743
             // instantiate Espresso_model
744 744
             static::$_instance = new static(
745 745
                 $timezone,
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
             foreach ($r->getDefaultProperties() as $property => $value) {
779 779
                 // don't set instance to null like it was originally,
780 780
                 // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
781
+                if ( ! isset($static_properties[$property])) {
782 782
                     static::$_instance->{$property} = $value;
783 783
                 }
784 784
             }
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
      */
803 803
     protected static function getLoader(): LoaderInterface
804 804
     {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
806 806
             EEM_Base::$loader = LoaderFactory::getLoader();
807 807
         }
808 808
         return EEM_Base::$loader;
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
      */
823 823
     public function status_array($translated = false)
824 824
     {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
826 826
             return array();
827 827
         }
828 828
         $model_name = $this->get_this_model_name();
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831 831
         $status_array = array();
832 832
         foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
+            $status_array[$status->ID()] = $status->get('STS_code');
834 834
         }
835 835
         return $translated
836 836
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
     {
892 892
         $wp_user_field_name = $this->wp_user_field_name();
893 893
         if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
895 895
         }
896 896
         return $query_params;
897 897
     }
@@ -909,17 +909,17 @@  discard block
 block discarded – undo
909 909
     public function wp_user_field_name()
910 910
     {
911 911
         try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
912
+            if ( ! empty($this->_model_chain_to_wp_user)) {
913 913
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914 914
                 $last_model_name = end($models_to_follow_to_wp_users);
915 915
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
917 917
             } else {
918 918
                 $model_with_fk_to_wp_users = $this;
919 919
                 $model_chain_to_wp_user = '';
920 920
             }
921 921
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
923 923
         } catch (EE_Error $e) {
924 924
             return false;
925 925
         }
@@ -996,11 +996,11 @@  discard block
 block discarded – undo
996 996
         if ($this->_custom_selections instanceof CustomSelects) {
997 997
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998 998
             $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
999
+                ? ', '.$custom_expressions
1000 1000
                 : $custom_expressions;
1001 1001
         }
1002 1002
 
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1004 1004
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005 1005
     }
1006 1006
 
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
      */
1018 1018
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019 1019
     {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021 1021
             return null;
1022 1022
         }
1023 1023
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
         if (is_array($columns_to_select)) {
1067 1067
             $select_sql_array = array();
1068 1068
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070 1070
                     throw new EE_Error(
1071 1071
                         sprintf(
1072 1072
                             __(
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
                         )
1079 1079
                     );
1080 1080
                 }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1157,12 +1157,12 @@  discard block
 block discarded – undo
1157 1157
      */
1158 1158
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159 1159
     {
1160
-        if (! isset($query_params[0])) {
1160
+        if ( ! isset($query_params[0])) {
1161 1161
             $query_params[0] = array();
1162 1162
         }
1163 1163
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1164 1164
         if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
+            $query_params[0][$this->primary_key_name()] = $id;
1166 1166
         } else {
1167 1167
             // no primary key, so the $id must be from the get_index_primary_key_string()
1168 1168
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function get_one($query_params = array())
1184 1184
     {
1185
-        if (! is_array($query_params)) {
1185
+        if ( ! is_array($query_params)) {
1186 1186
             EE_Error::doing_it_wrong(
1187 1187
                 'EEM_Base::get_one',
1188 1188
                 sprintf(
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
                 return array();
1381 1381
             }
1382 1382
         }
1383
-        if (! is_array($query_params)) {
1383
+        if ( ! is_array($query_params)) {
1384 1384
             EE_Error::doing_it_wrong(
1385 1385
                 'EEM_Base::_get_consecutive',
1386 1386
                 sprintf(
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
             $query_params = array();
1393 1393
         }
1394 1394
         // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1396 1396
         $query_params['limit'] = $limit;
1397 1397
         // set direction
1398 1398
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1473,7 +1473,7 @@  discard block
 block discarded – undo
1473 1473
     {
1474 1474
         $field_settings = $this->field_settings_for($field_name);
1475 1475
         // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1477 1477
             throw new EE_Error(sprintf(__(
1478 1478
                 '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.',
1479 1479
                 'event_espresso'
@@ -1622,7 +1622,7 @@  discard block
 block discarded – undo
1622 1622
      */
1623 1623
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624 1624
     {
1625
-        if (! is_array($query_params)) {
1625
+        if ( ! is_array($query_params)) {
1626 1626
             EE_Error::doing_it_wrong(
1627 1627
                 'EEM_Base::update',
1628 1628
                 sprintf(
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
             $wpdb_result = (array) $wpdb_result;
1671 1671
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672 1672
             if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1674 1674
             } else {
1675 1675
                 // 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)
1676 1676
                 $main_table_pk_value = null;
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
                     // in this table, right? so insert a row in the current table, using any fields available
1687 1687
                     if (
1688 1688
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1689
+                           && $wpdb_result[$this_table_pk_column])
1690 1690
                     ) {
1691 1691
                         $success = $this->_insert_into_specific_table(
1692 1692
                             $table_obj,
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
                             $main_table_pk_value
1695 1695
                         );
1696 1696
                         // if we died here, report the error
1697
-                        if (! $success) {
1697
+                        if ( ! $success) {
1698 1698
                             return false;
1699 1699
                         }
1700 1700
                     }
@@ -1722,10 +1722,10 @@  discard block
 block discarded – undo
1722 1722
                 $model_objs_affected_ids = array();
1723 1723
                 foreach ($models_affected_key_columns as $row) {
1724 1724
                     $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1726 1726
                 }
1727 1727
             }
1728
-            if (! $model_objs_affected_ids) {
1728
+            if ( ! $model_objs_affected_ids) {
1729 1729
                 // wait wait wait- if nothing was affected let's stop here
1730 1730
                 return 0;
1731 1731
             }
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
                . $model_query_info->get_full_join_sql()
1753 1753
                . " SET "
1754 1754
                . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756 1756
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757 1757
         /**
1758 1758
          * Action called after a model update call has been made.
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
          * @param int      $rows_affected
1764 1764
          */
1765 1765
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1766
+        return $rows_affected; // how many supposedly got updated
1767 1767
     }
1768 1768
 
1769 1769
 
@@ -1791,7 +1791,7 @@  discard block
 block discarded – undo
1791 1791
         }
1792 1792
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793 1793
         $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1795 1795
         return $this->_do_wpdb_query('get_col', array($SQL));
1796 1796
     }
1797 1797
 
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
     {
1810 1810
         $query_params['limit'] = 1;
1811 1811
         $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1812
+        if ( ! empty($col)) {
1813 1813
             return reset($col);
1814 1814
         }
1815 1815
         return null;
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841 1841
             $value_sql = $prepared_value === null ? 'NULL'
1842 1842
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1844 1844
         }
1845 1845
         return implode(",", $cols_n_values);
1846 1846
     }
@@ -1984,12 +1984,12 @@  discard block
 block discarded – undo
1984 1984
         if (
1985 1985
             $this->has_primary_key_field()
1986 1986
             && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1988 1988
         ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1990 1990
             foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1991
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1992
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1993 1993
                 }
1994 1994
             }
1995 1995
 
@@ -2026,7 +2026,7 @@  discard block
 block discarded – undo
2026 2026
          * @param int      $rows_deleted
2027 2027
          */
2028 2028
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2029
+        return $rows_deleted; // how many supposedly got deleted
2030 2030
     }
2031 2031
 
2032 2032
 
@@ -2120,15 +2120,15 @@  discard block
 block discarded – undo
2120 2120
                 if (
2121 2121
                     $allow_blocking
2122 2122
                     && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2124 2124
                     )
2125 2125
                 ) {
2126 2126
                     continue;
2127 2127
                 }
2128 2128
                 // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2129
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2130
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2131
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2132 2132
                 }
2133 2133
             }
2134 2134
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2137,8 +2137,8 @@  discard block
 block discarded – undo
2137 2137
                 $ids_to_delete_indexed_by_column_for_row = array();
2138 2138
                 foreach ($fields as $cpk_field) {
2139 2139
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2140
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2141
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2142 2142
                     }
2143 2143
                 }
2144 2144
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179 2179
                 // make sure we have unique $ids
2180 2180
                 $ids = array_unique($ids);
2181
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2181
+                $query[] = $column.' IN('.implode(',', $ids).')';
2182 2182
             }
2183 2183
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184 2184
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2186,7 +2186,7 @@  discard block
 block discarded – undo
2186 2186
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187 2187
                 $values_for_each_combined_primary_key_for_a_row = array();
2188 2188
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2189
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2190 2190
                 }
2191 2191
                 $ways_to_identify_a_row[] = '('
2192 2192
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2258,8 +2258,8 @@  discard block
 block discarded – undo
2258 2258
                 $column_to_count = '*';
2259 2259
             }
2260 2260
         }
2261
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2262
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2263 2263
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264 2264
     }
2265 2265
 
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             $field_obj = $this->get_primary_key_field();
2283 2283
         }
2284 2284
         $column_to_count = $field_obj->get_qualified_column();
2285
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2285
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2286 2286
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287 2287
         $data_type = $field_obj->get_wpdb_data_type();
2288 2288
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2309,7 +2309,7 @@  discard block
 block discarded – undo
2309 2309
         // if we're in maintenance mode level 2, DON'T run any queries
2310 2310
         // because level 2 indicates the database needs updating and
2311 2311
         // is probably out of sync with the code
2312
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2312
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2313 2313
             throw new EE_Error(sprintf(__(
2314 2314
                 "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.",
2315 2315
                 "event_espresso"
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
         }
2318 2318
         /** @type WPDB $wpdb */
2319 2319
         global $wpdb;
2320
-        if (! method_exists($wpdb, $wpdb_method)) {
2320
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2321 2321
             throw new EE_Error(sprintf(__(
2322 2322
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2323 2323
                 'event_espresso'
@@ -2331,7 +2331,7 @@  discard block
 block discarded – undo
2331 2331
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2332 2332
         if (WP_DEBUG) {
2333 2333
             $wpdb->show_errors($old_show_errors_value);
2334
-            if (! empty($wpdb->last_error)) {
2334
+            if ( ! empty($wpdb->last_error)) {
2335 2335
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336 2336
             }
2337 2337
             if ($result === false) {
@@ -2397,7 +2397,7 @@  discard block
 block discarded – undo
2397 2397
                     return $result;
2398 2398
                     break;
2399 2399
             }
2400
-            if (! empty($error_message)) {
2400
+            if ( ! empty($error_message)) {
2401 2401
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402 2402
                 trigger_error($error_message);
2403 2403
             }
@@ -2477,11 +2477,11 @@  discard block
 block discarded – undo
2477 2477
      */
2478 2478
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479 2479
     {
2480
-        return " FROM " . $model_query_info->get_full_join_sql() .
2481
-               $model_query_info->get_where_sql() .
2482
-               $model_query_info->get_group_by_sql() .
2483
-               $model_query_info->get_having_sql() .
2484
-               $model_query_info->get_order_by_sql() .
2480
+        return " FROM ".$model_query_info->get_full_join_sql().
2481
+               $model_query_info->get_where_sql().
2482
+               $model_query_info->get_group_by_sql().
2483
+               $model_query_info->get_having_sql().
2484
+               $model_query_info->get_order_by_sql().
2485 2485
                $model_query_info->get_limit_sql();
2486 2486
     }
2487 2487
 
@@ -2677,12 +2677,12 @@  discard block
 block discarded – undo
2677 2677
         $related_model = $this->get_related_model_obj($model_name);
2678 2678
         // we're just going to use the query params on the related model's normal get_all query,
2679 2679
         // except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2680
+        if ( ! isset($query_params['default_where_conditions'])) {
2681 2681
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682 2682
         }
2683 2683
         $this_model_name = $this->get_this_model_name();
2684 2684
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2685
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2686 2686
         return $related_model->count($query_params, $field_to_count, $distinct);
2687 2687
     }
2688 2688
 
@@ -2702,7 +2702,7 @@  discard block
 block discarded – undo
2702 2702
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703 2703
     {
2704 2704
         $related_model = $this->get_related_model_obj($model_name);
2705
-        if (! is_array($query_params)) {
2705
+        if ( ! is_array($query_params)) {
2706 2706
             EE_Error::doing_it_wrong(
2707 2707
                 'EEM_Base::sum_related',
2708 2708
                 sprintf(
@@ -2715,12 +2715,12 @@  discard block
 block discarded – undo
2715 2715
         }
2716 2716
         // we're just going to use the query params on the related model's normal get_all query,
2717 2717
         // except add a condition to say to match the current mod
2718
-        if (! isset($query_params['default_where_conditions'])) {
2718
+        if ( ! isset($query_params['default_where_conditions'])) {
2719 2719
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720 2720
         }
2721 2721
         $this_model_name = $this->get_this_model_name();
2722 2722
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2723
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2724 2724
         return $related_model->sum($query_params, $field_to_sum);
2725 2725
     }
2726 2726
 
@@ -2773,7 +2773,7 @@  discard block
 block discarded – undo
2773 2773
                 $field_with_model_name = $field;
2774 2774
             }
2775 2775
         }
2776
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2776
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2777 2777
             throw new EE_Error(sprintf(
2778 2778
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779 2779
                 $this->get_this_model_name()
@@ -2910,13 +2910,13 @@  discard block
 block discarded – undo
2910 2910
                 || $this->get_primary_key_field()
2911 2911
                    instanceof
2912 2912
                    EE_Primary_Key_String_Field)
2913
-            && isset($fields_n_values[ $this->primary_key_name() ])
2913
+            && isset($fields_n_values[$this->primary_key_name()])
2914 2914
         ) {
2915
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2915
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2916 2916
         }
2917 2917
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918 2918
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2919
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2920 2920
         }
2921 2921
         // if there is nothing to base this search on, then we shouldn't find anything
2922 2922
         if (empty($query_params)) {
@@ -2994,15 +2994,15 @@  discard block
 block discarded – undo
2994 2994
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995 2995
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2996 2996
             if ($prepared_value !== null) {
2997
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2997
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2998 2998
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999 2999
             }
3000 3000
         }
3001 3001
         if ($table instanceof EE_Secondary_Table && $new_id) {
3002 3002
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3003 3003
             // so add the fk to the main table as a column
3004
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3005
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3006 3006
         }
3007 3007
         // insert the new entry
3008 3008
         $result = $this->_do_wpdb_query(
@@ -3019,7 +3019,7 @@  discard block
 block discarded – undo
3019 3019
             }
3020 3020
             // it's not an auto-increment primary key, so
3021 3021
             // it must have been supplied
3022
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3022
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3023 3023
         }
3024 3024
         // we can't return a  primary key because there is none. instead return
3025 3025
         // a unique string indicating this model
@@ -3044,14 +3044,14 @@  discard block
 block discarded – undo
3044 3044
         if (
3045 3045
             ! $field_obj->is_nullable()
3046 3046
             && (
3047
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3048
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
+                ! isset($fields_n_values[$field_obj->get_name()])
3048
+                || $fields_n_values[$field_obj->get_name()] === null
3049 3049
             )
3050 3050
         ) {
3051
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3051
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3052 3052
         }
3053
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3054
+            ? $fields_n_values[$field_obj->get_name()]
3055 3055
             : null;
3056 3056
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057 3057
     }
@@ -3152,7 +3152,7 @@  discard block
 block discarded – undo
3152 3152
      */
3153 3153
     public function get_table_obj_by_alias($table_alias = '')
3154 3154
     {
3155
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3155
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156 3156
     }
3157 3157
 
3158 3158
 
@@ -3167,7 +3167,7 @@  discard block
 block discarded – undo
3167 3167
         $other_tables = array();
3168 3168
         foreach ($this->_tables as $table_alias => $table) {
3169 3169
             if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[ $table_alias ] = $table;
3170
+                $other_tables[$table_alias] = $table;
3171 3171
             }
3172 3172
         }
3173 3173
         return $other_tables;
@@ -3183,7 +3183,7 @@  discard block
 block discarded – undo
3183 3183
      */
3184 3184
     public function _get_fields_for_table($table_alias)
3185 3185
     {
3186
-        return $this->_fields[ $table_alias ];
3186
+        return $this->_fields[$table_alias];
3187 3187
     }
3188 3188
 
3189 3189
 
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
                     $query_info_carrier,
3213 3213
                     'group_by'
3214 3214
                 );
3215
-            } elseif (! empty($query_params['group_by'])) {
3215
+            } elseif ( ! empty($query_params['group_by'])) {
3216 3216
                 $this->_extract_related_model_info_from_query_param(
3217 3217
                     $query_params['group_by'],
3218 3218
                     $query_info_carrier,
@@ -3234,7 +3234,7 @@  discard block
 block discarded – undo
3234 3234
                     $query_info_carrier,
3235 3235
                     'order_by'
3236 3236
                 );
3237
-            } elseif (! empty($query_params['order_by'])) {
3237
+            } elseif ( ! empty($query_params['order_by'])) {
3238 3238
                 $this->_extract_related_model_info_from_query_param(
3239 3239
                     $query_params['order_by'],
3240 3240
                     $query_info_carrier,
@@ -3269,7 +3269,7 @@  discard block
 block discarded – undo
3269 3269
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270 3270
         $query_param_type
3271 3271
     ) {
3272
-        if (! empty($sub_query_params)) {
3272
+        if ( ! empty($sub_query_params)) {
3273 3273
             $sub_query_params = (array) $sub_query_params;
3274 3274
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275 3275
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
                 // of array('Registration.TXN_ID'=>23)
3285 3285
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286 3286
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
-                    if (! is_array($possibly_array_of_params)) {
3287
+                    if ( ! is_array($possibly_array_of_params)) {
3288 3288
                         throw new EE_Error(sprintf(
3289 3289
                             __(
3290 3290
                                 "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'))",
@@ -3308,7 +3308,7 @@  discard block
 block discarded – undo
3308 3308
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309 3309
                     // indicating that $possible_array_of_params[1] is actually a field name,
3310 3310
                     // from which we should extract query parameters!
3311
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3311
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312 3312
                         throw new EE_Error(sprintf(__(
3313 3313
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314 3314
                             "event_espresso"
@@ -3342,8 +3342,8 @@  discard block
 block discarded – undo
3342 3342
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343 3343
         $query_param_type
3344 3344
     ) {
3345
-        if (! empty($sub_query_params)) {
3346
-            if (! is_array($sub_query_params)) {
3345
+        if ( ! empty($sub_query_params)) {
3346
+            if ( ! is_array($sub_query_params)) {
3347 3347
                 throw new EE_Error(sprintf(
3348 3348
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349 3349
                     $sub_query_params
@@ -3377,7 +3377,7 @@  discard block
 block discarded – undo
3377 3377
      */
3378 3378
     public function _create_model_query_info_carrier($query_params)
3379 3379
     {
3380
-        if (! is_array($query_params)) {
3380
+        if ( ! is_array($query_params)) {
3381 3381
             EE_Error::doing_it_wrong(
3382 3382
                 'EEM_Base::_create_model_query_info_carrier',
3383 3383
                 sprintf(
@@ -3410,7 +3410,7 @@  discard block
 block discarded – undo
3410 3410
             // only include if related to a cpt where no password has been set
3411 3411
             $query_params[0]['OR*nopassword'] = array(
3412 3412
                 $where_param_key_for_password => '',
3413
-                $where_param_key_for_password . '*' => array('IS_NULL')
3413
+                $where_param_key_for_password.'*' => array('IS_NULL')
3414 3414
             );
3415 3415
         }
3416 3416
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3464,7 +3464,7 @@  discard block
 block discarded – undo
3464 3464
         // set limit
3465 3465
         if (array_key_exists('limit', $query_params)) {
3466 3466
             if (is_array($query_params['limit'])) {
3467
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3467
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468 3468
                     $e = sprintf(
3469 3469
                         __(
3470 3470
                             "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)",
@@ -3472,12 +3472,12 @@  discard block
 block discarded – undo
3472 3472
                         ),
3473 3473
                         http_build_query($query_params['limit'])
3474 3474
                     );
3475
-                    throw new EE_Error($e . "|" . $e);
3475
+                    throw new EE_Error($e."|".$e);
3476 3476
                 }
3477 3477
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
-            } elseif (! empty($query_params['limit'])) {
3480
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3478
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3479
+            } elseif ( ! empty($query_params['limit'])) {
3480
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3481 3481
             }
3482 3482
         }
3483 3483
         // set order by
@@ -3509,10 +3509,10 @@  discard block
 block discarded – undo
3509 3509
                 $order_array = array();
3510 3510
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511 3511
                     $order = $this->_extract_order($order);
3512
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3512
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3513 3513
                 }
3514
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
-            } elseif (! empty($query_params['order_by'])) {
3514
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3515
+            } elseif ( ! empty($query_params['order_by'])) {
3516 3516
                 $this->_extract_related_model_info_from_query_param(
3517 3517
                     $query_params['order_by'],
3518 3518
                     $query_object,
@@ -3523,7 +3523,7 @@  discard block
 block discarded – undo
3523 3523
                     ? $this->_extract_order($query_params['order'])
3524 3524
                     : 'DESC';
3525 3525
                 $query_object->set_order_by_sql(
3526
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3526
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3527 3527
                 );
3528 3528
             }
3529 3529
         }
@@ -3535,7 +3535,7 @@  discard block
 block discarded – undo
3535 3535
         ) {
3536 3536
             $pk_field = $this->get_primary_key_field();
3537 3537
             $order = $this->_extract_order($query_params['order']);
3538
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3538
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3539 3539
         }
3540 3540
         // set group by
3541 3541
         if (array_key_exists('group_by', $query_params)) {
@@ -3545,10 +3545,10 @@  discard block
 block discarded – undo
3545 3545
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546 3546
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547 3547
                 }
3548
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
-            } elseif (! empty($query_params['group_by'])) {
3548
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3549
+            } elseif ( ! empty($query_params['group_by'])) {
3550 3550
                 $query_object->set_group_by_sql(
3551
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3551
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3552 3552
                 );
3553 3553
             }
3554 3554
         }
@@ -3558,7 +3558,7 @@  discard block
 block discarded – undo
3558 3558
         }
3559 3559
         // now, just verify they didn't pass anything wack
3560 3560
         foreach ($query_params as $query_key => $query_value) {
3561
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3561
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3562 3562
                 throw new EE_Error(
3563 3563
                     sprintf(
3564 3564
                         __(
@@ -3666,7 +3666,7 @@  discard block
 block discarded – undo
3666 3666
         $where_query_params = array()
3667 3667
     ) {
3668 3668
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3669
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670 3670
             throw new EE_Error(sprintf(
3671 3671
                 __(
3672 3672
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3798,19 +3798,19 @@  discard block
 block discarded – undo
3798 3798
     ) {
3799 3799
         $null_friendly_where_conditions = array();
3800 3800
         $none_overridden = true;
3801
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3801
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3802 3802
         foreach ($default_where_conditions as $key => $val) {
3803
-            if (isset($provided_where_conditions[ $key ])) {
3803
+            if (isset($provided_where_conditions[$key])) {
3804 3804
                 $none_overridden = false;
3805 3805
             } else {
3806
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3806
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3807 3807
             }
3808 3808
         }
3809 3809
         if ($none_overridden && $default_where_conditions) {
3810 3810
             if ($model->has_primary_key_field()) {
3811
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3811
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3812 3812
                                                                                 . "."
3813
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3813
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3814 3814
             }/*else{
3815 3815
                 //@todo NO PK, use other defaults
3816 3816
             }*/
@@ -3915,7 +3915,7 @@  discard block
 block discarded – undo
3915 3915
             foreach ($tables as $table_obj) {
3916 3916
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917 3917
                                        . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3918
+                if ( ! in_array($qualified_pk_column, $selects)) {
3919 3919
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920 3920
                 }
3921 3921
             }
@@ -4067,9 +4067,9 @@  discard block
 block discarded – undo
4067 4067
         $query_parameter_type
4068 4068
     ) {
4069 4069
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4071 4071
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4073 4073
                 if ($possible_join_string === '') {
4074 4074
                     // nothing left to $query_param
4075 4075
                     // we should actually end in a field name, not a model like this!
@@ -4200,7 +4200,7 @@  discard block
 block discarded – undo
4200 4200
     {
4201 4201
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202 4202
         if ($SQL) {
4203
-            return " WHERE " . $SQL;
4203
+            return " WHERE ".$SQL;
4204 4204
         }
4205 4205
         return '';
4206 4206
     }
@@ -4219,7 +4219,7 @@  discard block
 block discarded – undo
4219 4219
     {
4220 4220
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221 4221
         if ($SQL) {
4222
-            return " HAVING " . $SQL;
4222
+            return " HAVING ".$SQL;
4223 4223
         }
4224 4224
         return '';
4225 4225
     }
@@ -4238,7 +4238,7 @@  discard block
 block discarded – undo
4238 4238
     {
4239 4239
         $where_clauses = array();
4240 4240
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4242 4242
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4243 4243
                 switch ($query_param) {
4244 4244
                     case 'not':
@@ -4272,7 +4272,7 @@  discard block
 block discarded – undo
4272 4272
             } else {
4273 4273
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4274 4274
                 // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4275
+                if ( ! $field_obj) {
4276 4276
                     if ($this->_custom_selections instanceof CustomSelects) {
4277 4277
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278 4278
                     } else {
@@ -4283,7 +4283,7 @@  discard block
 block discarded – undo
4283 4283
                     }
4284 4284
                 }
4285 4285
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4287 4287
             }
4288 4288
         }
4289 4289
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4306,7 +4306,7 @@  discard block
 block discarded – undo
4306 4306
                 $field->get_model_name(),
4307 4307
                 $query_param
4308 4308
             );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4309
+            return $table_alias_prefix.$field->get_qualified_column();
4310 4310
         }
4311 4311
         if (
4312 4312
             $this->_custom_selections instanceof CustomSelects
@@ -4366,7 +4366,7 @@  discard block
 block discarded – undo
4366 4366
     {
4367 4367
         if (is_array($op_and_value)) {
4368 4368
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4369
+            if ( ! $operator) {
4370 4370
                 $php_array_like_string = array();
4371 4371
                 foreach ($op_and_value as $key => $value) {
4372 4372
                     $php_array_like_string[] = "$key=>$value";
@@ -4388,14 +4388,14 @@  discard block
 block discarded – undo
4388 4388
         }
4389 4389
         // check to see if the value is actually another field
4390 4390
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4392 4392
         }
4393 4393
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394 4394
             // in this case, the value should be an array, or at least a comma-separated list
4395 4395
             // it will need to handle a little differently
4396 4396
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397 4397
             // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4398
+            return $operator.SP.$cleaned_value;
4399 4399
         }
4400 4400
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401 4401
             // the value should be an array with count of two.
@@ -4411,7 +4411,7 @@  discard block
 block discarded – undo
4411 4411
                 );
4412 4412
             }
4413 4413
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4414
+            return $operator.SP.$cleaned_value;
4415 4415
         }
4416 4416
         if (in_array($operator, $this->valid_null_style_operators())) {
4417 4417
             if ($value !== null) {
@@ -4431,10 +4431,10 @@  discard block
 block discarded – undo
4431 4431
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432 4432
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433 4433
             // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4435 4435
         }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4436
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4438 4438
         }
4439 4439
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440 4440
             throw new EE_Error(
@@ -4448,7 +4448,7 @@  discard block
 block discarded – undo
4448 4448
                 )
4449 4449
             );
4450 4450
         }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452 4452
             throw new EE_Error(
4453 4453
                 sprintf(
4454 4454
                     __(
@@ -4488,7 +4488,7 @@  discard block
 block discarded – undo
4488 4488
         foreach ($values as $value) {
4489 4489
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490 4490
         }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4492 4492
     }
4493 4493
 
4494 4494
 
@@ -4529,7 +4529,7 @@  discard block
 block discarded – undo
4529 4529
                                 . $main_table->get_table_name()
4530 4530
                                 . " WHERE FALSE";
4531 4531
         }
4532
-        return "(" . implode(",", $cleaned_values) . ")";
4532
+        return "(".implode(",", $cleaned_values).")";
4533 4533
     }
4534 4534
 
4535 4535
 
@@ -4550,7 +4550,7 @@  discard block
 block discarded – undo
4550 4550
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4551 4551
             );
4552 4552
         } //$field_obj should really just be a data type
4553
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4554 4554
             throw new EE_Error(
4555 4555
                 sprintf(
4556 4556
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4583,14 +4583,14 @@  discard block
 block discarded – undo
4583 4583
             ), $query_param_name));
4584 4584
         }
4585 4585
         $number_of_parts = count($query_param_parts);
4586
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4587 4587
         if ($number_of_parts === 1) {
4588 4588
             $field_name = $last_query_param_part;
4589 4589
             $model_obj = $this;
4590 4590
         } else {// $number_of_parts >= 2
4591 4591
             // the last part is the column name, and there are only 2parts. therefore...
4592 4592
             $field_name = $last_query_param_part;
4593
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4594 4594
         }
4595 4595
         try {
4596 4596
             return $model_obj->field_settings_for($field_name);
@@ -4612,7 +4612,7 @@  discard block
 block discarded – undo
4612 4612
     public function _get_qualified_column_for_field($field_name)
4613 4613
     {
4614 4614
         $all_fields = $this->field_settings();
4615
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4616 4616
         if ($field) {
4617 4617
             return $field->get_qualified_column();
4618 4618
         }
@@ -4683,10 +4683,10 @@  discard block
 block discarded – undo
4683 4683
      */
4684 4684
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4685 4685
     {
4686
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4687 4687
         $qualified_columns = array();
4688 4688
         foreach ($this->field_settings() as $field_name => $field) {
4689
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4690 4690
         }
4691 4691
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4692 4692
     }
@@ -4710,11 +4710,11 @@  discard block
 block discarded – undo
4710 4710
             if ($table_obj instanceof EE_Primary_Table) {
4711 4711
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4712 4712
                     ? $table_obj->get_select_join_limit($limit)
4713
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4714 4714
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4715 4715
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4716 4716
                     ? $table_obj->get_select_join_limit_join($limit)
4717
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4717
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4718 4718
             }
4719 4719
         }
4720 4720
         return $SQL;
@@ -4786,7 +4786,7 @@  discard block
 block discarded – undo
4786 4786
         foreach ($this->field_settings() as $field_obj) {
4787 4787
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4788 4788
             /** @var $field_obj EE_Model_Field_Base */
4789
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4790 4790
         }
4791 4791
         return $data_types;
4792 4792
     }
@@ -4802,14 +4802,14 @@  discard block
 block discarded – undo
4802 4802
      */
4803 4803
     public function get_related_model_obj($model_name)
4804 4804
     {
4805
-        $model_classname = "EEM_" . $model_name;
4806
-        if (! class_exists($model_classname)) {
4805
+        $model_classname = "EEM_".$model_name;
4806
+        if ( ! class_exists($model_classname)) {
4807 4807
             throw new EE_Error(sprintf(__(
4808 4808
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4809 4809
                 'event_espresso'
4810 4810
             ), $model_name, $model_classname));
4811 4811
         }
4812
-        return call_user_func($model_classname . "::instance");
4812
+        return call_user_func($model_classname."::instance");
4813 4813
     }
4814 4814
 
4815 4815
 
@@ -4838,7 +4838,7 @@  discard block
 block discarded – undo
4838 4838
         $belongs_to_relations = array();
4839 4839
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4840 4840
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4841
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4841
+                $belongs_to_relations[$model_name] = $relation_obj;
4842 4842
             }
4843 4843
         }
4844 4844
         return $belongs_to_relations;
@@ -4856,7 +4856,7 @@  discard block
 block discarded – undo
4856 4856
     public function related_settings_for($relation_name)
4857 4857
     {
4858 4858
         $relatedModels = $this->relation_settings();
4859
-        if (! array_key_exists($relation_name, $relatedModels)) {
4859
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4860 4860
             throw new EE_Error(
4861 4861
                 sprintf(
4862 4862
                     __(
@@ -4869,7 +4869,7 @@  discard block
 block discarded – undo
4869 4869
                 )
4870 4870
             );
4871 4871
         }
4872
-        return $relatedModels[ $relation_name ];
4872
+        return $relatedModels[$relation_name];
4873 4873
     }
4874 4874
 
4875 4875
 
@@ -4886,14 +4886,14 @@  discard block
 block discarded – undo
4886 4886
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4887 4887
     {
4888 4888
         $fieldSettings = $this->field_settings($include_db_only_fields);
4889
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4889
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4890 4890
             throw new EE_Error(sprintf(
4891 4891
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4892 4892
                 $fieldName,
4893 4893
                 get_class($this)
4894 4894
             ));
4895 4895
         }
4896
-        return $fieldSettings[ $fieldName ];
4896
+        return $fieldSettings[$fieldName];
4897 4897
     }
4898 4898
 
4899 4899
 
@@ -4907,7 +4907,7 @@  discard block
 block discarded – undo
4907 4907
     public function has_field($fieldName)
4908 4908
     {
4909 4909
         $fieldSettings = $this->field_settings(true);
4910
-        if (isset($fieldSettings[ $fieldName ])) {
4910
+        if (isset($fieldSettings[$fieldName])) {
4911 4911
             return true;
4912 4912
         }
4913 4913
         return false;
@@ -4924,7 +4924,7 @@  discard block
 block discarded – undo
4924 4924
     public function has_relation($relation_name)
4925 4925
     {
4926 4926
         $relations = $this->relation_settings();
4927
-        if (isset($relations[ $relation_name ])) {
4927
+        if (isset($relations[$relation_name])) {
4928 4928
             return true;
4929 4929
         }
4930 4930
         return false;
@@ -4962,7 +4962,7 @@  discard block
 block discarded – undo
4962 4962
                     break;
4963 4963
                 }
4964 4964
             }
4965
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4966 4966
                 throw new EE_Error(sprintf(
4967 4967
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
4968 4968
                     get_class($this)
@@ -5023,24 +5023,24 @@  discard block
 block discarded – undo
5023 5023
      */
5024 5024
     public function get_foreign_key_to($model_name)
5025 5025
     {
5026
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5027 5027
             foreach ($this->field_settings() as $field) {
5028 5028
                 if (
5029 5029
                     $field instanceof EE_Foreign_Key_Field_Base
5030 5030
                     && in_array($model_name, $field->get_model_names_pointed_to())
5031 5031
                 ) {
5032
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5033 5033
                     break;
5034 5034
                 }
5035 5035
             }
5036
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5037 5037
                 throw new EE_Error(sprintf(__(
5038 5038
                     "There is no foreign key field pointing to model %s on model %s",
5039 5039
                     'event_espresso'
5040 5040
                 ), $model_name, get_class($this)));
5041 5041
             }
5042 5042
         }
5043
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
+        return $this->_cache_foreign_key_to_fields[$model_name];
5044 5044
     }
5045 5045
 
5046 5046
 
@@ -5056,7 +5056,7 @@  discard block
 block discarded – undo
5056 5056
     public function get_table_for_alias($table_alias)
5057 5057
     {
5058 5058
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5059
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5060 5060
     }
5061 5061
 
5062 5062
 
@@ -5075,7 +5075,7 @@  discard block
 block discarded – undo
5075 5075
                 $this->_cached_fields = array();
5076 5076
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5077 5077
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5078
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5078
+                        $this->_cached_fields[$field_name] = $field_obj;
5079 5079
                     }
5080 5080
                 }
5081 5081
             }
@@ -5086,8 +5086,8 @@  discard block
 block discarded – undo
5086 5086
             foreach ($this->_fields as $fields_corresponding_to_table) {
5087 5087
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5088 5088
                     /** @var $field_obj EE_Model_Field_Base */
5089
-                    if (! $field_obj->is_db_only_field()) {
5090
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5089
+                    if ( ! $field_obj->is_db_only_field()) {
5090
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5091 5091
                     }
5092 5092
                 }
5093 5093
             }
@@ -5128,12 +5128,12 @@  discard block
 block discarded – undo
5128 5128
                     $primary_key_field->get_qualified_column(),
5129 5129
                     $primary_key_field->get_table_column()
5130 5130
                 );
5131
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5132 5132
                     continue;
5133 5133
                 }
5134 5134
             }
5135 5135
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5136
-            if (! $classInstance) {
5136
+            if ( ! $classInstance) {
5137 5137
                 throw new EE_Error(
5138 5138
                     sprintf(
5139 5139
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5146,7 +5146,7 @@  discard block
 block discarded – undo
5146 5146
             $classInstance->set_timezone($this->_timezone);
5147 5147
             // make sure if there is any timezone setting present that we set the timezone for the object
5148 5148
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5149
-            $array_of_objects[ $key ] = $classInstance;
5149
+            $array_of_objects[$key] = $classInstance;
5150 5150
             // also, for all the relations of type BelongsTo, see if we can cache
5151 5151
             // those related models
5152 5152
             // (we could do this for other relations too, but if there are conditions
@@ -5190,9 +5190,9 @@  discard block
 block discarded – undo
5190 5190
         $results = array();
5191 5191
         if ($this->_custom_selections instanceof CustomSelects) {
5192 5192
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5193
-                if (isset($db_results_row[ $alias ])) {
5194
-                    $results[ $alias ] = $this->convertValueToDataType(
5195
-                        $db_results_row[ $alias ],
5193
+                if (isset($db_results_row[$alias])) {
5194
+                    $results[$alias] = $this->convertValueToDataType(
5195
+                        $db_results_row[$alias],
5196 5196
                         $this->_custom_selections->getDataTypeForAlias($alias)
5197 5197
                     );
5198 5198
                 }
@@ -5234,7 +5234,7 @@  discard block
 block discarded – undo
5234 5234
         $this_model_fields_and_values = array();
5235 5235
         // setup the row using default values;
5236 5236
         foreach ($this->field_settings() as $field_name => $field_obj) {
5237
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5238 5238
         }
5239 5239
         $className = $this->_get_class_name();
5240 5240
         $classInstance = EE_Registry::instance()
@@ -5252,20 +5252,20 @@  discard block
 block discarded – undo
5252 5252
      */
5253 5253
     public function instantiate_class_from_array_or_object($cols_n_values)
5254 5254
     {
5255
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5256 5256
             $cols_n_values = get_object_vars($cols_n_values);
5257 5257
         }
5258 5258
         $primary_key = null;
5259 5259
         // make sure the array only has keys that are fields/columns on this model
5260 5260
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5261
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5262
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5261
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5262
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5263 5263
         }
5264 5264
         $className = $this->_get_class_name();
5265 5265
         // check we actually found results that we can use to build our model object
5266 5266
         // if not, return null
5267 5267
         if ($this->has_primary_key_field()) {
5268
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5269 5269
                 return null;
5270 5270
             }
5271 5271
         } elseif ($this->unique_indexes()) {
@@ -5277,7 +5277,7 @@  discard block
 block discarded – undo
5277 5277
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5278 5278
         if ($primary_key) {
5279 5279
             $classInstance = $this->get_from_entity_map($primary_key);
5280
-            if (! $classInstance) {
5280
+            if ( ! $classInstance) {
5281 5281
                 $classInstance = EE_Registry::instance()
5282 5282
                                             ->load_class(
5283 5283
                                                 $className,
@@ -5310,8 +5310,8 @@  discard block
 block discarded – undo
5310 5310
      */
5311 5311
     public function get_from_entity_map($id)
5312 5312
     {
5313
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5314
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5313
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5314
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5315 5315
     }
5316 5316
 
5317 5317
 
@@ -5334,7 +5334,7 @@  discard block
 block discarded – undo
5334 5334
     public function add_to_entity_map(EE_Base_Class $object)
5335 5335
     {
5336 5336
         $className = $this->_get_class_name();
5337
-        if (! $object instanceof $className) {
5337
+        if ( ! $object instanceof $className) {
5338 5338
             throw new EE_Error(sprintf(
5339 5339
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5340 5340
                 is_object($object) ? get_class($object) : $object,
@@ -5342,7 +5342,7 @@  discard block
 block discarded – undo
5342 5342
             ));
5343 5343
         }
5344 5344
         /** @var $object EE_Base_Class */
5345
-        if (! $object->ID()) {
5345
+        if ( ! $object->ID()) {
5346 5346
             throw new EE_Error(sprintf(__(
5347 5347
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5348 5348
                 "event_espresso"
@@ -5353,7 +5353,7 @@  discard block
 block discarded – undo
5353 5353
         if ($classInstance) {
5354 5354
             return $classInstance;
5355 5355
         }
5356
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5357 5357
         return $object;
5358 5358
     }
5359 5359
 
@@ -5369,11 +5369,11 @@  discard block
 block discarded – undo
5369 5369
     public function clear_entity_map($id = null)
5370 5370
     {
5371 5371
         if (empty($id)) {
5372
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5373 5373
             return true;
5374 5374
         }
5375
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5376
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5375
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5376
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5377 5377
             return true;
5378 5378
         }
5379 5379
         return false;
@@ -5416,17 +5416,17 @@  discard block
 block discarded – undo
5416 5416
             // there is a primary key on this table and its not set. Use defaults for all its columns
5417 5417
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5418 5418
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5419
-                    if (! $field_obj->is_db_only_field()) {
5419
+                    if ( ! $field_obj->is_db_only_field()) {
5420 5420
                         // prepare field as if its coming from db
5421 5421
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5422
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5423 5423
                     }
5424 5424
                 }
5425 5425
             } else {
5426 5426
                 // the table's rows existed. Use their values
5427 5427
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5428
-                    if (! $field_obj->is_db_only_field()) {
5429
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5428
+                    if ( ! $field_obj->is_db_only_field()) {
5429
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5430 5430
                             $cols_n_values,
5431 5431
                             $field_obj->get_qualified_column(),
5432 5432
                             $field_obj->get_table_column()
@@ -5453,17 +5453,17 @@  discard block
 block discarded – undo
5453 5453
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5454 5454
         // does the field on the model relate to this column retrieved from the db?
5455 5455
         // or is it a db-only field? (not relating to the model)
5456
-        if (isset($cols_n_values[ $qualified_column ])) {
5457
-            $value = $cols_n_values[ $qualified_column ];
5458
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5459
-            $value = $cols_n_values[ $regular_column ];
5460
-        } elseif (! empty($this->foreign_key_aliases)) {
5456
+        if (isset($cols_n_values[$qualified_column])) {
5457
+            $value = $cols_n_values[$qualified_column];
5458
+        } elseif (isset($cols_n_values[$regular_column])) {
5459
+            $value = $cols_n_values[$regular_column];
5460
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5461 5461
             // no PK?  ok check if there is a foreign key alias set for this table
5462 5462
             // then check if that alias exists in the incoming data
5463 5463
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5464 5464
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5465
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5466
-                    $value = $cols_n_values[ $FK_alias ];
5465
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5466
+                    $value = $cols_n_values[$FK_alias];
5467 5467
                     [$pk_class] = explode('.', $PK_column);
5468 5468
                     $pk_model_name = "EEM_{$pk_class}";
5469 5469
                     /** @var EEM_Base $pk_model */
@@ -5507,7 +5507,7 @@  discard block
 block discarded – undo
5507 5507
                     $obj_in_map->clear_cache($relation_name, null, true);
5508 5508
                 }
5509 5509
             }
5510
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5511 5511
             return $obj_in_map;
5512 5512
         }
5513 5513
         return $this->get_one_by_ID($id);
@@ -5560,7 +5560,7 @@  discard block
 block discarded – undo
5560 5560
      */
5561 5561
     private function _get_class_name()
5562 5562
     {
5563
-        return "EE_" . $this->get_this_model_name();
5563
+        return "EE_".$this->get_this_model_name();
5564 5564
     }
5565 5565
 
5566 5566
 
@@ -5608,7 +5608,7 @@  discard block
 block discarded – undo
5608 5608
     {
5609 5609
         $className = get_class($this);
5610 5610
         $tagName = "FHEE__{$className}__{$methodName}";
5611
-        if (! has_filter($tagName)) {
5611
+        if ( ! has_filter($tagName)) {
5612 5612
             throw new EE_Error(
5613 5613
                 sprintf(
5614 5614
                     __(
@@ -5781,7 +5781,7 @@  discard block
 block discarded – undo
5781 5781
         $unique_indexes = array();
5782 5782
         foreach ($this->_indexes as $name => $index) {
5783 5783
             if ($index instanceof EE_Unique_Index) {
5784
-                $unique_indexes [ $name ] = $index;
5784
+                $unique_indexes [$name] = $index;
5785 5785
             }
5786 5786
         }
5787 5787
         return $unique_indexes;
@@ -5848,7 +5848,7 @@  discard block
 block discarded – undo
5848 5848
         $key_vals_in_combined_pk = array();
5849 5849
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5850 5850
         foreach ($key_fields as $key_field_name => $field_obj) {
5851
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5851
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5852 5852
                 return null;
5853 5853
             }
5854 5854
         }
@@ -5869,7 +5869,7 @@  discard block
 block discarded – undo
5869 5869
     {
5870 5870
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5871 5871
         foreach ($keys_it_should_have as $key) {
5872
-            if (! isset($key_vals[ $key ])) {
5872
+            if ( ! isset($key_vals[$key])) {
5873 5873
                 return false;
5874 5874
             }
5875 5875
         }
@@ -5902,8 +5902,8 @@  discard block
 block discarded – undo
5902 5902
         }
5903 5903
         // even copies obviously won't have the same ID, so remove the primary key
5904 5904
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5905
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5906
-            unset($attributes_array[ $this->primary_key_name() ]);
5905
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5906
+            unset($attributes_array[$this->primary_key_name()]);
5907 5907
         }
5908 5908
         if (isset($query_params[0])) {
5909 5909
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5925,7 +5925,7 @@  discard block
 block discarded – undo
5925 5925
      */
5926 5926
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5927 5927
     {
5928
-        if (! is_array($query_params)) {
5928
+        if ( ! is_array($query_params)) {
5929 5929
             EE_Error::doing_it_wrong(
5930 5930
                 'EEM_Base::get_one_copy',
5931 5931
                 sprintf(
@@ -5975,7 +5975,7 @@  discard block
 block discarded – undo
5975 5975
      */
5976 5976
     private function _prepare_operator_for_sql($operator_supplied)
5977 5977
     {
5978
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5978
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5979 5979
             : null;
5980 5980
         if ($sql_operator) {
5981 5981
             return $sql_operator;
@@ -6066,7 +6066,7 @@  discard block
 block discarded – undo
6066 6066
         $objs = $this->get_all($query_params);
6067 6067
         $names = array();
6068 6068
         foreach ($objs as $obj) {
6069
-            $names[ $obj->ID() ] = $obj->name();
6069
+            $names[$obj->ID()] = $obj->name();
6070 6070
         }
6071 6071
         return $names;
6072 6072
     }
@@ -6087,7 +6087,7 @@  discard block
 block discarded – undo
6087 6087
      */
6088 6088
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6089 6089
     {
6090
-        if (! $this->has_primary_key_field()) {
6090
+        if ( ! $this->has_primary_key_field()) {
6091 6091
             if (WP_DEBUG) {
6092 6092
                 EE_Error::add_error(
6093 6093
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6100,7 +6100,7 @@  discard block
 block discarded – undo
6100 6100
         $IDs = array();
6101 6101
         foreach ($model_objects as $model_object) {
6102 6102
             $id = $model_object->ID();
6103
-            if (! $id) {
6103
+            if ( ! $id) {
6104 6104
                 if ($filter_out_empty_ids) {
6105 6105
                     continue;
6106 6106
                 }
@@ -6151,22 +6151,22 @@  discard block
 block discarded – undo
6151 6151
         EEM_Base::verify_is_valid_cap_context($context);
6152 6152
         // check if we ought to run the restriction generator first
6153 6153
         if (
6154
-            isset($this->_cap_restriction_generators[ $context ])
6155
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6156
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6154
+            isset($this->_cap_restriction_generators[$context])
6155
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6156
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6157 6157
         ) {
6158
-            $this->_cap_restrictions[ $context ] = array_merge(
6159
-                $this->_cap_restrictions[ $context ],
6160
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6158
+            $this->_cap_restrictions[$context] = array_merge(
6159
+                $this->_cap_restrictions[$context],
6160
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6161 6161
             );
6162 6162
         }
6163 6163
         // and make sure we've finalized the construction of each restriction
6164
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6164
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6165 6165
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6166 6166
                 $where_conditions_obj->_finalize_construct($this);
6167 6167
             }
6168 6168
         }
6169
-        return $this->_cap_restrictions[ $context ];
6169
+        return $this->_cap_restrictions[$context];
6170 6170
     }
6171 6171
 
6172 6172
 
@@ -6198,9 +6198,9 @@  discard block
 block discarded – undo
6198 6198
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6199 6199
             if (
6200 6200
                 ! EE_Capabilities::instance()
6201
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6201
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6202 6202
             ) {
6203
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6203
+                $missing_caps[$cap] = $restriction_if_no_cap;
6204 6204
             }
6205 6205
         }
6206 6206
         return $missing_caps;
@@ -6235,8 +6235,8 @@  discard block
 block discarded – undo
6235 6235
     public function cap_action_for_context($context)
6236 6236
     {
6237 6237
         $mapping = $this->cap_contexts_to_cap_action_map();
6238
-        if (isset($mapping[ $context ])) {
6239
-            return $mapping[ $context ];
6238
+        if (isset($mapping[$context])) {
6239
+            return $mapping[$context];
6240 6240
         }
6241 6241
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6242 6242
             return $action;
@@ -6354,7 +6354,7 @@  discard block
 block discarded – undo
6354 6354
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6355 6355
             if (
6356 6356
                 $query_param_key === $logic_query_param_key
6357
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6357
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6358 6358
             ) {
6359 6359
                 return true;
6360 6360
             }
@@ -6407,7 +6407,7 @@  discard block
 block discarded – undo
6407 6407
         if ($password_field instanceof EE_Password_Field) {
6408 6408
             $field_names = $password_field->protectedFields();
6409 6409
             foreach ($field_names as $field_name) {
6410
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6410
+                $fields[$field_name] = $this->field_settings_for($field_name);
6411 6411
             }
6412 6412
         }
6413 6413
         return $fields;
@@ -6432,7 +6432,7 @@  discard block
 block discarded – undo
6432 6432
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6433 6433
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6434 6434
         }
6435
-        if (!is_array($model_obj_or_fields_n_values)) {
6435
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6436 6436
             throw new UnexpectedEntityException(
6437 6437
                 $model_obj_or_fields_n_values,
6438 6438
                 'EE_Base_Class',
@@ -6507,7 +6507,7 @@  discard block
 block discarded – undo
6507 6507
                 )
6508 6508
             );
6509 6509
         }
6510
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6510
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6511 6511
     }
6512 6512
 
6513 6513
     /**
Please login to merge, or discard this patch.
core/db_classes/EE_Form_Section.class.php 1 patch
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -19,227 +19,227 @@
 block discarded – undo
19 19
 class EE_Form_Section extends EE_Soft_Delete_Base_Class
20 20
 {
21 21
 
22
-    /**
23
-     * @param array $props_n_values
24
-     * @return EE_Form_Section
25
-     * @throws EE_Error
26
-     * @throws ReflectionException
27
-     */
28
-    public static function new_instance(array $props_n_values = []): EE_Form_Section
29
-    {
30
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
31
-        return $has_object
32
-            ?: new self($props_n_values);
33
-    }
34
-
35
-
36
-    /**
37
-     * @param array $props_n_values
38
-     * @return EE_Form_Section
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    public static function new_instance_from_db(array $props_n_values = []): EE_Form_Section
43
-    {
44
-        return new self($props_n_values);
45
-    }
46
-
47
-
48
-    /**
49
-     * Form Section UUID (universally unique identifier)
50
-     *
51
-     * @return string
52
-     * @throws EE_Error
53
-     * @throws ReflectionException
54
-     */
55
-    public function UUID(): string
56
-    {
57
-        return $this->get('FSC_UUID');
58
-    }
59
-
60
-
61
-    /**
62
-     * Form user types that this form section should be presented to.
63
-     * Values correspond to the EEM_Form_Section::APPLIES_TO_* constants.
64
-     *
65
-     * @return string
66
-     * @throws EE_Error
67
-     * @throws ReflectionException
68
-     */
69
-    public function appliesTo(): string
70
-    {
71
-        return $this->get('FSC_appliesTo');
72
-    }
73
-
74
-
75
-    /**
76
-     * UUID or ID of related entity this form section belongs to.
77
-     *
78
-     * @return string
79
-     * @throws EE_Error
80
-     * @throws ReflectionException
81
-     */
82
-    public function belongsTo(): string
83
-    {
84
-        return $this->get('FSC_belongsTo');
85
-    }
86
-
87
-
88
-    /**
89
-     * HTML classes to be applied to this form section's container.
90
-     *
91
-     * @return string
92
-     * @throws EE_Error
93
-     * @throws ReflectionException
94
-     */
95
-    public function htmlClass(): string
96
-    {
97
-        return $this->get('FSC_htmlClass');
98
-    }
99
-
100
-
101
-    /**
102
-     * Order in which form section appears in a form.
103
-     *
104
-     * @return int
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public function order(): int
109
-    {
110
-        return $this->get('FSC_order');
111
-    }
112
-
113
-
114
-    /**
115
-     * Related model type.
116
-     *
117
-     * @return string
118
-     * @throws EE_Error
119
-     * @throws ReflectionException
120
-     */
121
-    public function relation(): string
122
-    {
123
-        return $this->get('FSC_relation');
124
-    }
125
-
126
-
127
-    /**
128
-     * Whether form section is active, archived, trashed, or used as a default on new forms.
129
-     * Values correspond to the EEM_Form_Section::STATUS_* constants.
130
-     *
131
-     * @return string
132
-     * @throws EE_Error
133
-     * @throws ReflectionException
134
-     */
135
-    public function status(): string
136
-    {
137
-        return $this->get('FSC_status');
138
-    }
139
-
140
-
141
-    /**
142
-     * returns the id the wordpress user who created this question
143
-     *
144
-     * @return int
145
-     * @throws EE_Error
146
-     * @throws ReflectionException
147
-     */
148
-    public function wpUser(): int
149
-    {
150
-        return $this->get('FSC_wpUser');
151
-    }
152
-
153
-
154
-    /**
155
-     * Form user types that this form section should be presented to.
156
-     * Values correspond to the EEM_Form_Section::APPLIES_TO_* constants.
157
-     *
158
-     * @param string $user_type
159
-     * @throws EE_Error
160
-     * @throws ReflectionException
161
-     */
162
-    public function setAppliesTo(string $user_type)
163
-    {
164
-        $this->set('FSC_appliesTo', $user_type);
165
-    }
166
-
167
-
168
-    /**
169
-     * UUID or ID of related entity this form section belongs to.
170
-     *
171
-     * @param string $relation_UUID
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     */
175
-    public function setBelongsTo(string $relation_UUID)
176
-    {
177
-        $this->set('FSC_belongsTo', $relation_UUID);
178
-    }
179
-
180
-
181
-    /**
182
-     * HTML classes to be applied to this form section's container.
183
-     *
184
-     * @param string $html_class
185
-     * @throws EE_Error
186
-     * @throws ReflectionException
187
-     */
188
-    public function setHtmlClass(string $html_class)
189
-    {
190
-        $this->set('FSC_htmlClass', $html_class);
191
-    }
192
-
193
-
194
-    /**
195
-     * Order in which form section appears in a form.
196
-     *
197
-     * @param int $order
198
-     * @throws EE_Error
199
-     * @throws ReflectionException
200
-     */
201
-    public function setOrder(int $order)
202
-    {
203
-        $this->set('FSC_order', $order);
204
-    }
205
-
206
-
207
-    /**
208
-     * Related model type.
209
-     *
210
-     * @param string $relation
211
-     * @throws EE_Error
212
-     * @throws ReflectionException
213
-     */
214
-    public function setRelation(string $relation)
215
-    {
216
-        $this->set('FSC_relation', $relation);
217
-    }
218
-
219
-
220
-    /**
221
-     * Whether form section is active, archived, trashed, or used as a default on new forms.
222
-     * Values correspond to the EEM_Form_Section::STATUS_* constants.
223
-     *
224
-     * @param string $status
225
-     * @throws EE_Error
226
-     * @throws ReflectionException
227
-     */
228
-    public function setStatus(string $status)
229
-    {
230
-        $this->set('FSC_status', $status);
231
-    }
232
-
233
-
234
-    /**
235
-     * returns the id the wordpress user who created this question
236
-     *
237
-     * @param int $wp_user
238
-     * @throws EE_Error
239
-     * @throws ReflectionException
240
-     */
241
-    public function setWpUser(int $wp_user)
242
-    {
243
-        $this->set('FSC_wpUser', $wp_user);
244
-    }
22
+	/**
23
+	 * @param array $props_n_values
24
+	 * @return EE_Form_Section
25
+	 * @throws EE_Error
26
+	 * @throws ReflectionException
27
+	 */
28
+	public static function new_instance(array $props_n_values = []): EE_Form_Section
29
+	{
30
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
31
+		return $has_object
32
+			?: new self($props_n_values);
33
+	}
34
+
35
+
36
+	/**
37
+	 * @param array $props_n_values
38
+	 * @return EE_Form_Section
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	public static function new_instance_from_db(array $props_n_values = []): EE_Form_Section
43
+	{
44
+		return new self($props_n_values);
45
+	}
46
+
47
+
48
+	/**
49
+	 * Form Section UUID (universally unique identifier)
50
+	 *
51
+	 * @return string
52
+	 * @throws EE_Error
53
+	 * @throws ReflectionException
54
+	 */
55
+	public function UUID(): string
56
+	{
57
+		return $this->get('FSC_UUID');
58
+	}
59
+
60
+
61
+	/**
62
+	 * Form user types that this form section should be presented to.
63
+	 * Values correspond to the EEM_Form_Section::APPLIES_TO_* constants.
64
+	 *
65
+	 * @return string
66
+	 * @throws EE_Error
67
+	 * @throws ReflectionException
68
+	 */
69
+	public function appliesTo(): string
70
+	{
71
+		return $this->get('FSC_appliesTo');
72
+	}
73
+
74
+
75
+	/**
76
+	 * UUID or ID of related entity this form section belongs to.
77
+	 *
78
+	 * @return string
79
+	 * @throws EE_Error
80
+	 * @throws ReflectionException
81
+	 */
82
+	public function belongsTo(): string
83
+	{
84
+		return $this->get('FSC_belongsTo');
85
+	}
86
+
87
+
88
+	/**
89
+	 * HTML classes to be applied to this form section's container.
90
+	 *
91
+	 * @return string
92
+	 * @throws EE_Error
93
+	 * @throws ReflectionException
94
+	 */
95
+	public function htmlClass(): string
96
+	{
97
+		return $this->get('FSC_htmlClass');
98
+	}
99
+
100
+
101
+	/**
102
+	 * Order in which form section appears in a form.
103
+	 *
104
+	 * @return int
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public function order(): int
109
+	{
110
+		return $this->get('FSC_order');
111
+	}
112
+
113
+
114
+	/**
115
+	 * Related model type.
116
+	 *
117
+	 * @return string
118
+	 * @throws EE_Error
119
+	 * @throws ReflectionException
120
+	 */
121
+	public function relation(): string
122
+	{
123
+		return $this->get('FSC_relation');
124
+	}
125
+
126
+
127
+	/**
128
+	 * Whether form section is active, archived, trashed, or used as a default on new forms.
129
+	 * Values correspond to the EEM_Form_Section::STATUS_* constants.
130
+	 *
131
+	 * @return string
132
+	 * @throws EE_Error
133
+	 * @throws ReflectionException
134
+	 */
135
+	public function status(): string
136
+	{
137
+		return $this->get('FSC_status');
138
+	}
139
+
140
+
141
+	/**
142
+	 * returns the id the wordpress user who created this question
143
+	 *
144
+	 * @return int
145
+	 * @throws EE_Error
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function wpUser(): int
149
+	{
150
+		return $this->get('FSC_wpUser');
151
+	}
152
+
153
+
154
+	/**
155
+	 * Form user types that this form section should be presented to.
156
+	 * Values correspond to the EEM_Form_Section::APPLIES_TO_* constants.
157
+	 *
158
+	 * @param string $user_type
159
+	 * @throws EE_Error
160
+	 * @throws ReflectionException
161
+	 */
162
+	public function setAppliesTo(string $user_type)
163
+	{
164
+		$this->set('FSC_appliesTo', $user_type);
165
+	}
166
+
167
+
168
+	/**
169
+	 * UUID or ID of related entity this form section belongs to.
170
+	 *
171
+	 * @param string $relation_UUID
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 */
175
+	public function setBelongsTo(string $relation_UUID)
176
+	{
177
+		$this->set('FSC_belongsTo', $relation_UUID);
178
+	}
179
+
180
+
181
+	/**
182
+	 * HTML classes to be applied to this form section's container.
183
+	 *
184
+	 * @param string $html_class
185
+	 * @throws EE_Error
186
+	 * @throws ReflectionException
187
+	 */
188
+	public function setHtmlClass(string $html_class)
189
+	{
190
+		$this->set('FSC_htmlClass', $html_class);
191
+	}
192
+
193
+
194
+	/**
195
+	 * Order in which form section appears in a form.
196
+	 *
197
+	 * @param int $order
198
+	 * @throws EE_Error
199
+	 * @throws ReflectionException
200
+	 */
201
+	public function setOrder(int $order)
202
+	{
203
+		$this->set('FSC_order', $order);
204
+	}
205
+
206
+
207
+	/**
208
+	 * Related model type.
209
+	 *
210
+	 * @param string $relation
211
+	 * @throws EE_Error
212
+	 * @throws ReflectionException
213
+	 */
214
+	public function setRelation(string $relation)
215
+	{
216
+		$this->set('FSC_relation', $relation);
217
+	}
218
+
219
+
220
+	/**
221
+	 * Whether form section is active, archived, trashed, or used as a default on new forms.
222
+	 * Values correspond to the EEM_Form_Section::STATUS_* constants.
223
+	 *
224
+	 * @param string $status
225
+	 * @throws EE_Error
226
+	 * @throws ReflectionException
227
+	 */
228
+	public function setStatus(string $status)
229
+	{
230
+		$this->set('FSC_status', $status);
231
+	}
232
+
233
+
234
+	/**
235
+	 * returns the id the wordpress user who created this question
236
+	 *
237
+	 * @param int $wp_user
238
+	 * @throws EE_Error
239
+	 * @throws ReflectionException
240
+	 */
241
+	public function setWpUser(int $wp_user)
242
+	{
243
+		$this->set('FSC_wpUser', $wp_user);
244
+	}
245 245
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_12_0.dms.php 2 patches
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -13,63 +13,63 @@  discard block
 block discarded – undo
13 13
  */
14 14
 class EE_DMS_Core_4_12_0 extends EE_Data_Migration_Script_Base
15 15
 {
16
-    /**
17
-     *
18
-     * @param EE_DMS_Core_4_11_0 $dms_4_11
19
-     * @param TableManager|null  $table_manager
20
-     * @param TableAnalysis|null $table_analysis
21
-     */
22
-    public function __construct(
23
-        EE_DMS_Core_4_11_0 $dms_4_11,
24
-        TableManager $table_manager = null,
25
-        TableAnalysis $table_analysis = null
26
-    ) {
27
-        $this->previous_dms      = $dms_4_11;
28
-        $this->_pretty_name      = esc_html__("Data Update to Event Espresso 4.12.0", "event_espresso");
29
-        $this->_priority         = 10;
30
-        $this->_migration_stages = [
31
-
32
-        ];
33
-        parent::__construct($table_manager, $table_analysis);
34
-    }
35
-
36
-
37
-    /**
38
-     * Whether to migrate or not.
39
-     *
40
-     * @param array $version_array
41
-     * @return bool
42
-     */
43
-    public function can_migrate_from_version($version_array)
44
-    {
45
-        $version_string = $version_array['Core'];
46
-        return $version_string
47
-               && version_compare($version_string, '4.12.0.decaf', '<')
48
-               && version_compare($version_string, '4.11.0.decaf', '>=');
49
-    }
50
-
51
-
52
-    /**
53
-     * @return bool
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public function schema_changes_before_migration()
58
-    {
59
-        require_once EE_HELPERS . 'EEH_Activation.helper.php';
60
-
61
-        $table_name = 'esp_answer';
62
-        $sql        = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
16
+	/**
17
+	 *
18
+	 * @param EE_DMS_Core_4_11_0 $dms_4_11
19
+	 * @param TableManager|null  $table_manager
20
+	 * @param TableAnalysis|null $table_analysis
21
+	 */
22
+	public function __construct(
23
+		EE_DMS_Core_4_11_0 $dms_4_11,
24
+		TableManager $table_manager = null,
25
+		TableAnalysis $table_analysis = null
26
+	) {
27
+		$this->previous_dms      = $dms_4_11;
28
+		$this->_pretty_name      = esc_html__("Data Update to Event Espresso 4.12.0", "event_espresso");
29
+		$this->_priority         = 10;
30
+		$this->_migration_stages = [
31
+
32
+		];
33
+		parent::__construct($table_manager, $table_analysis);
34
+	}
35
+
36
+
37
+	/**
38
+	 * Whether to migrate or not.
39
+	 *
40
+	 * @param array $version_array
41
+	 * @return bool
42
+	 */
43
+	public function can_migrate_from_version($version_array)
44
+	{
45
+		$version_string = $version_array['Core'];
46
+		return $version_string
47
+			   && version_compare($version_string, '4.12.0.decaf', '<')
48
+			   && version_compare($version_string, '4.11.0.decaf', '>=');
49
+	}
50
+
51
+
52
+	/**
53
+	 * @return bool
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public function schema_changes_before_migration()
58
+	{
59
+		require_once EE_HELPERS . 'EEH_Activation.helper.php';
60
+
61
+		$table_name = 'esp_answer';
62
+		$sql        = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
63 63
 					REG_ID int(10) unsigned NOT NULL,
64 64
 					QST_ID int(10) unsigned NOT NULL,
65 65
 					ANS_value text NOT NULL,
66 66
 					PRIMARY KEY  (ANS_ID),
67 67
 					KEY REG_ID (REG_ID),
68 68
 					KEY QST_ID (QST_ID)";
69
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
69
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
70 70
 
71
-        $table_name = 'esp_attendee_meta';
72
-        $sql        = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
71
+		$table_name = 'esp_attendee_meta';
72
+		$sql        = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
73 73
 				ATT_ID bigint(20) unsigned NOT NULL,
74 74
 				ATT_fname varchar(45) NOT NULL,
75 75
 				ATT_lname varchar(45) NOT NULL,
@@ -86,10 +86,10 @@  discard block
 block discarded – undo
86 86
 				KEY ATT_email (ATT_email(191)),
87 87
 				KEY ATT_lname (ATT_lname),
88 88
 				KEY ATT_fname (ATT_fname)";
89
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
89
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
90 90
 
91
-        $table_name = 'esp_checkin';
92
-        $sql        = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
91
+		$table_name = 'esp_checkin';
92
+		$sql        = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
93 93
 				REG_ID int(10) unsigned NOT NULL,
94 94
 				DTT_ID int(10) unsigned NOT NULL,
95 95
 				CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -97,10 +97,10 @@  discard block
 block discarded – undo
97 97
 				PRIMARY KEY  (CHK_ID),
98 98
 				KEY REG_ID (REG_ID),
99 99
 				KEY DTT_ID (DTT_ID)";
100
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
100
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
101 101
 
102
-        $table_name = 'esp_country';
103
-        $sql        = "CNT_ISO varchar(2) NOT NULL,
102
+		$table_name = 'esp_country';
103
+		$sql        = "CNT_ISO varchar(2) NOT NULL,
104 104
 				CNT_ISO3 varchar(3) NOT NULL,
105 105
 				RGN_ID tinyint(3) unsigned DEFAULT NULL,
106 106
 				CNT_name varchar(45) NOT NULL,
@@ -116,32 +116,32 @@  discard block
 block discarded – undo
116 116
 				CNT_is_EU tinyint(1) DEFAULT '0',
117 117
 				CNT_active tinyint(1) DEFAULT '0',
118 118
 				PRIMARY KEY  (CNT_ISO)";
119
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
119
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
120 120
 
121
-        $table_name = 'esp_currency';
122
-        $sql        = "CUR_code varchar(6) NOT NULL,
121
+		$table_name = 'esp_currency';
122
+		$sql        = "CUR_code varchar(6) NOT NULL,
123 123
 				CUR_single varchar(45) DEFAULT 'dollar',
124 124
 				CUR_plural varchar(45) DEFAULT 'dollars',
125 125
 				CUR_sign varchar(45) DEFAULT '$',
126 126
 				CUR_dec_plc varchar(1) NOT NULL DEFAULT '2',
127 127
 				CUR_active tinyint(1) DEFAULT '0',
128 128
 				PRIMARY KEY  (CUR_code)";
129
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
130
-
131
-        // note: although this table is no longer in use,
132
-        // it hasn't been removed because then queries to the model will have errors.
133
-        // but you should expect this table and its corresponding model to be removed in
134
-        // the next few months
135
-        $table_name = 'esp_currency_payment_method';
136
-        $sql        = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
129
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
130
+
131
+		// note: although this table is no longer in use,
132
+		// it hasn't been removed because then queries to the model will have errors.
133
+		// but you should expect this table and its corresponding model to be removed in
134
+		// the next few months
135
+		$table_name = 'esp_currency_payment_method';
136
+		$sql        = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
137 137
 				CUR_code varchar(6) NOT NULL,
138 138
 				PMD_ID int(11) NOT NULL,
139 139
 				PRIMARY KEY  (CPM_ID),
140 140
 				KEY PMD_ID (PMD_ID)";
141
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
141
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
142 142
 
143
-        $table_name = 'esp_datetime';
144
-        $sql        = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
143
+		$table_name = 'esp_datetime';
144
+		$sql        = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
145 145
 				EVT_ID bigint(20) unsigned NOT NULL,
146 146
 				DTT_name varchar(255) NOT NULL DEFAULT '',
147 147
 				DTT_description text NOT NULL,
@@ -158,28 +158,28 @@  discard block
 block discarded – undo
158 158
 				KEY DTT_EVT_start (DTT_EVT_start),
159 159
 				KEY EVT_ID (EVT_ID),
160 160
 				KEY DTT_is_primary (DTT_is_primary)";
161
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
161
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
162 162
 
163
-        $table_name = "esp_datetime_ticket";
164
-        $sql        = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
163
+		$table_name = "esp_datetime_ticket";
164
+		$sql        = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
165 165
 				DTT_ID int(10) unsigned NOT NULL,
166 166
 				TKT_ID int(10) unsigned NOT NULL,
167 167
 				PRIMARY KEY  (DTK_ID),
168 168
 				KEY DTT_ID (DTT_ID),
169 169
 				KEY TKT_ID (TKT_ID)";
170
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
170
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
171 171
 
172
-        $table_name = 'esp_event_message_template';
173
-        $sql        = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
172
+		$table_name = 'esp_event_message_template';
173
+		$sql        = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
174 174
 				EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
175 175
 				GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
176 176
 				PRIMARY KEY  (EMT_ID),
177 177
 				KEY EVT_ID (EVT_ID),
178 178
 				KEY GRP_ID (GRP_ID)";
179
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
179
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
180 180
 
181
-        $table_name = 'esp_event_meta';
182
-        $sql        = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
181
+		$table_name = 'esp_event_meta';
182
+		$sql        = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
183 183
 				EVT_ID bigint(20) unsigned NOT NULL,
184 184
 				EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
185 185
 				EVT_display_ticket_selector tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -194,10 +194,10 @@  discard block
 block discarded – undo
194 194
 				EVT_donations tinyint(1) NULL,
195 195
 				PRIMARY KEY  (EVTM_ID),
196 196
 				KEY EVT_ID (EVT_ID)";
197
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
197
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
198 198
 
199
-        $table_name = 'esp_event_question_group';
200
-        $sql        = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
199
+		$table_name = 'esp_event_question_group';
200
+		$sql        = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
201 201
 				EVT_ID bigint(20) unsigned NOT NULL,
202 202
 				QSG_ID int(10) unsigned NOT NULL,
203 203
 				EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
@@ -205,28 +205,28 @@  discard block
 block discarded – undo
205 205
 				PRIMARY KEY  (EQG_ID),
206 206
 				KEY EVT_ID (EVT_ID),
207 207
 				KEY QSG_ID (QSG_ID)";
208
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
208
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
209 209
 
210
-        $table_name = 'esp_event_venue';
211
-        $sql        = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
210
+		$table_name = 'esp_event_venue';
211
+		$sql        = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
212 212
 				EVT_ID bigint(20) unsigned NOT NULL,
213 213
 				VNU_ID bigint(20) unsigned NOT NULL,
214 214
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
215 215
 				PRIMARY KEY  (EVV_ID)";
216
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
216
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
217 217
 
218
-        $table_name = 'esp_extra_meta';
219
-        $sql        = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
218
+		$table_name = 'esp_extra_meta';
219
+		$sql        = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
220 220
 				OBJ_ID int(11) DEFAULT NULL,
221 221
 				EXM_type varchar(45) DEFAULT NULL,
222 222
 				EXM_key varchar(45) DEFAULT NULL,
223 223
 				EXM_value text,
224 224
 				PRIMARY KEY  (EXM_ID),
225 225
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
226
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
226
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
227 227
 
228
-        $table_name = 'esp_extra_join';
229
-        $sql        = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
228
+		$table_name = 'esp_extra_join';
229
+		$sql        = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
230 230
 				EXJ_first_model_id varchar(6) NOT NULL,
231 231
 				EXJ_first_model_name varchar(20) NOT NULL,
232 232
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -234,10 +234,10 @@  discard block
 block discarded – undo
234 234
 				PRIMARY KEY  (EXJ_ID),
235 235
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
236 236
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
237
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
237
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
238 238
 
239
-        $table_name = 'esp_form_section';
240
-        $sql        = 'FSC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
239
+		$table_name = 'esp_form_section';
240
+		$sql        = 'FSC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
241 241
                 FSC_UUID binary(16) NOT NULL,
242 242
 				FSC_appliesTo tinytext NOT NULL,
243 243
 				FSC_belongsTo binary(16) NULL,
@@ -250,11 +250,11 @@  discard block
 block discarded – undo
250 250
 				UNIQUE KEY FSC_UUID_UNIQUE (FSC_UUID),
251 251
 				KEY FSC_belongsTo (FSC_belongsTo),
252 252
 				KEY FSC_order (FSC_order)';
253
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
253
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
254 254
 
255
-        $now_in_mysql = current_time('mysql', true);
256
-        $table_name   = 'esp_line_item';
257
-        $sql          = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
255
+		$now_in_mysql = current_time('mysql', true);
256
+		$table_name   = 'esp_line_item';
257
+		$sql          = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
258 258
 				LIN_code varchar(245) NOT NULL DEFAULT '',
259 259
 				TXN_ID int(11) DEFAULT NULL,
260 260
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -275,10 +275,10 @@  discard block
 block discarded – undo
275 275
 				KEY txn_type_timestamp (TXN_ID,LIN_type,LIN_timestamp),
276 276
 				KEY txn_obj_id_obj_type (TXN_ID,OBJ_ID,OBJ_type),
277 277
 				KEY obj_id_obj_type (OBJ_ID,OBJ_type)";
278
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
278
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
279 279
 
280
-        $table_name = 'esp_log';
281
-        $sql        = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
280
+		$table_name = 'esp_log';
281
+		$sql        = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
282 282
 				LOG_time datetime DEFAULT NULL,
283 283
 				OBJ_ID varchar(45) DEFAULT NULL,
284 284
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -289,10 +289,10 @@  discard block
 block discarded – undo
289 289
 				KEY LOG_time (LOG_time),
290 290
 				KEY OBJ (OBJ_type,OBJ_ID),
291 291
 				KEY LOG_type (LOG_type)";
292
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
292
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
293 293
 
294
-        $table_name = 'esp_message';
295
-        $sql        = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
294
+		$table_name = 'esp_message';
295
+		$sql        = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
296 296
 				GRP_ID int(10) unsigned NULL,
297 297
 				MSG_token varchar(255) NULL,
298 298
 				TXN_ID int(10) unsigned NULL,
@@ -324,20 +324,20 @@  discard block
 block discarded – undo
324 324
 				KEY STS_ID (STS_ID),
325 325
 				KEY MSG_created (MSG_created),
326 326
 				KEY MSG_modified (MSG_modified)";
327
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
327
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
328 328
 
329
-        $table_name = 'esp_message_template';
330
-        $sql        = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
329
+		$table_name = 'esp_message_template';
330
+		$sql        = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
331 331
 				GRP_ID int(10) unsigned NOT NULL,
332 332
 				MTP_context varchar(50) NOT NULL,
333 333
 				MTP_template_field varchar(30) NOT NULL,
334 334
 				MTP_content text NOT NULL,
335 335
 				PRIMARY KEY  (MTP_ID),
336 336
 				KEY GRP_ID (GRP_ID)";
337
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
337
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
338 338
 
339
-        $table_name = 'esp_message_template_group';
340
-        $sql        = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
339
+		$table_name = 'esp_message_template_group';
340
+		$sql        = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
341 341
 				MTP_user_id int(10) NOT NULL DEFAULT '1',
342 342
 				MTP_name varchar(245) NOT NULL DEFAULT '',
343 343
 				MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -349,10 +349,10 @@  discard block
 block discarded – undo
349 349
 				MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
350 350
 				PRIMARY KEY  (GRP_ID),
351 351
 				KEY MTP_user_id (MTP_user_id)";
352
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
352
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
353 353
 
354
-        $table_name = 'esp_payment';
355
-        $sql        = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
354
+		$table_name = 'esp_payment';
355
+		$sql        = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
356 356
 				TXN_ID int(10) unsigned DEFAULT NULL,
357 357
 				STS_ID varchar(3) DEFAULT NULL,
358 358
 				PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -369,10 +369,10 @@  discard block
 block discarded – undo
369 369
 				PRIMARY KEY  (PAY_ID),
370 370
 				KEY PAY_timestamp (PAY_timestamp),
371 371
 				KEY TXN_ID (TXN_ID)";
372
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
372
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
373 373
 
374
-        $table_name = 'esp_payment_method';
375
-        $sql        = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
374
+		$table_name = 'esp_payment_method';
375
+		$sql        = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
376 376
 				PMD_type varchar(124) DEFAULT NULL,
377 377
 				PMD_name varchar(255) DEFAULT NULL,
378 378
 				PMD_desc text,
@@ -388,10 +388,10 @@  discard block
 block discarded – undo
388 388
 				PRIMARY KEY  (PMD_ID),
389 389
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
390 390
 				KEY PMD_type (PMD_type)";
391
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
391
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
392 392
 
393
-        $table_name = "esp_price";
394
-        $sql        = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
393
+		$table_name = "esp_price";
394
+		$sql        = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
395 395
 				PRT_ID tinyint(3) unsigned NOT NULL,
396 396
 				PRC_amount decimal(12,3) NOT NULL DEFAULT '0.00',
397 397
 				PRC_name varchar(245) NOT NULL,
@@ -404,10 +404,10 @@  discard block
 block discarded – undo
404 404
 				PRC_parent int(10) unsigned DEFAULT 0,
405 405
 				PRIMARY KEY  (PRC_ID),
406 406
 				KEY PRT_ID (PRT_ID)";
407
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
407
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
408 408
 
409
-        $table_name = "esp_price_type";
410
-        $sql        = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
409
+		$table_name = "esp_price_type";
410
+		$sql        = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
411 411
 				PRT_name varchar(45) NOT NULL,
412 412
 				PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
413 413
 				PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -416,27 +416,27 @@  discard block
 block discarded – undo
416 416
 				PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
417 417
 				UNIQUE KEY PRT_name_UNIQUE (PRT_name),
418 418
 				PRIMARY KEY  (PRT_ID)";
419
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
419
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
420 420
 
421
-        $table_name = "esp_ticket_price";
422
-        $sql        = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
421
+		$table_name = "esp_ticket_price";
422
+		$sql        = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
423 423
 				TKT_ID int(10) unsigned NOT NULL,
424 424
 				PRC_ID int(10) unsigned NOT NULL,
425 425
 				PRIMARY KEY  (TKP_ID),
426 426
 				KEY TKT_ID (TKT_ID),
427 427
 				KEY PRC_ID (PRC_ID)";
428
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
428
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
429 429
 
430
-        $table_name = "esp_ticket_template";
431
-        $sql        = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
430
+		$table_name = "esp_ticket_template";
431
+		$sql        = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
432 432
 				TTM_name varchar(45) NOT NULL,
433 433
 				TTM_description text,
434 434
 				TTM_file varchar(45),
435 435
 				PRIMARY KEY  (TTM_ID)";
436
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
436
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
437 437
 
438
-        $table_name = 'esp_question';
439
-        $sql        = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
438
+		$table_name = 'esp_question';
439
+		$sql        = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
440 440
 				QST_display_text text NOT NULL,
441 441
 				QST_admin_label varchar(255) NOT NULL,
442 442
 				QST_system varchar(25) DEFAULT NULL,
@@ -450,10 +450,10 @@  discard block
 block discarded – undo
450 450
 				QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
451 451
 				PRIMARY KEY  (QST_ID),
452 452
 				KEY QST_order (QST_order)';
453
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
453
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
454 454
 
455
-        $table_name = 'esp_question_group';
456
-        $sql        = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
455
+		$table_name = 'esp_question_group';
456
+		$sql        = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
457 457
 				QSG_name varchar(255) NOT NULL,
458 458
 				QSG_identifier varchar(100) NOT NULL,
459 459
 				QSG_desc text NULL,
@@ -466,20 +466,20 @@  discard block
 block discarded – undo
466 466
 				PRIMARY KEY  (QSG_ID),
467 467
 				UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
468 468
 				KEY QSG_order (QSG_order)';
469
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
469
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
470 470
 
471
-        $table_name = 'esp_question_group_question';
472
-        $sql        = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
471
+		$table_name = 'esp_question_group_question';
472
+		$sql        = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
473 473
 				QSG_ID int(10) unsigned NOT NULL,
474 474
 				QST_ID int(10) unsigned NOT NULL,
475 475
 				QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
476 476
 				PRIMARY KEY  (QGQ_ID),
477 477
 				KEY QST_ID (QST_ID),
478 478
 				KEY QSG_ID_order (QSG_ID,QGQ_order)";
479
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
479
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
480 480
 
481
-        $table_name = 'esp_question_option';
482
-        $sql        = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
481
+		$table_name = 'esp_question_option';
482
+		$sql        = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
483 483
 				QSO_value varchar(255) NOT NULL,
484 484
 				QSO_desc text NOT NULL,
485 485
 				QST_ID int(10) unsigned NOT NULL,
@@ -489,10 +489,10 @@  discard block
 block discarded – undo
489 489
 				PRIMARY KEY  (QSO_ID),
490 490
 				KEY QST_ID (QST_ID),
491 491
 				KEY QSO_order (QSO_order)";
492
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
492
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
493 493
 
494
-        $table_name = 'esp_registration';
495
-        $sql        = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
494
+		$table_name = 'esp_registration';
495
+		$sql        = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
496 496
 				EVT_ID bigint(20) unsigned NOT NULL,
497 497
 				ATT_ID bigint(20) unsigned NOT NULL,
498 498
 				TXN_ID int(10) unsigned NOT NULL,
@@ -516,20 +516,20 @@  discard block
 block discarded – undo
516 516
 				KEY TKT_ID (TKT_ID),
517 517
 				KEY EVT_ID (EVT_ID),
518 518
 				KEY STS_ID (STS_ID)";
519
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
519
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
520 520
 
521
-        $table_name = 'esp_registration_payment';
522
-        $sql        = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
521
+		$table_name = 'esp_registration_payment';
522
+		$sql        = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
523 523
 					  REG_ID int(10) unsigned NOT NULL,
524 524
 					  PAY_ID int(10) unsigned NULL,
525 525
 					  RPY_amount decimal(12,3) NOT NULL DEFAULT '0.00',
526 526
 					  PRIMARY KEY  (RPY_ID),
527 527
 					  KEY REG_ID (REG_ID),
528 528
 					  KEY PAY_ID (PAY_ID)";
529
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
529
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
530 530
 
531
-        $table_name = 'esp_state';
532
-        $sql        = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
531
+		$table_name = 'esp_state';
532
+		$sql        = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
533 533
 				CNT_ISO varchar(2) NOT NULL,
534 534
 				STA_abbrev varchar(24) NOT NULL,
535 535
 				STA_name varchar(100) NOT NULL,
@@ -537,10 +537,10 @@  discard block
 block discarded – undo
537 537
 				PRIMARY KEY  (STA_ID),
538 538
 				KEY STA_abbrev (STA_abbrev),
539 539
 				KEY CNT_ISO (CNT_ISO)";
540
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
540
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
541 541
 
542
-        $table_name = 'esp_status';
543
-        $sql        = "STS_ID varchar(3) NOT NULL,
542
+		$table_name = 'esp_status';
543
+		$sql        = "STS_ID varchar(3) NOT NULL,
544 544
 				STS_code varchar(45) NOT NULL,
545 545
 				STS_type varchar(45) NOT NULL,
546 546
 				STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -548,10 +548,10 @@  discard block
 block discarded – undo
548 548
 				STS_open tinyint(1) NOT NULL DEFAULT 1,
549 549
 				UNIQUE KEY STS_ID_UNIQUE (STS_ID),
550 550
 				KEY STS_type (STS_type)";
551
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
551
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
552 552
 
553
-        $table_name = "esp_ticket";
554
-        $sql        = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
553
+		$table_name = "esp_ticket";
554
+		$sql        = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
555 555
 				TTM_ID int(10) unsigned NOT NULL,
556 556
 				TKT_name varchar(245) NOT NULL DEFAULT '',
557 557
 				TKT_description text NOT NULL,
@@ -576,10 +576,10 @@  discard block
 block discarded – undo
576 576
 				TKT_visibility smallint(6) unsigned NOT NULL DEFAULT 100,
577 577
 				PRIMARY KEY  (TKT_ID),
578 578
 				KEY TKT_start_date (TKT_start_date)";
579
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
579
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
580 580
 
581
-        $table_name = 'esp_transaction';
582
-        $sql        = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
581
+		$table_name = 'esp_transaction';
582
+		$sql        = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
583 583
 				TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
584 584
 				TXN_total decimal(12,3) DEFAULT '0.00',
585 585
 				TXN_paid decimal(12,3) NOT NULL DEFAULT '0.00',
@@ -591,10 +591,10 @@  discard block
 block discarded – undo
591 591
 				PRIMARY KEY  (TXN_ID),
592 592
 				KEY TXN_timestamp (TXN_timestamp),
593 593
 				KEY STS_ID (STS_ID)";
594
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
594
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
595 595
 
596
-        $table_name = 'esp_venue_meta';
597
-        $sql        = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
596
+		$table_name = 'esp_venue_meta';
597
+		$sql        = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
598 598
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
599 599
 			VNU_address varchar(255) DEFAULT NULL,
600 600
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -613,36 +613,36 @@  discard block
 block discarded – undo
613 613
 			KEY VNU_ID (VNU_ID),
614 614
 			KEY STA_ID (STA_ID),
615 615
 			KEY CNT_ISO (CNT_ISO)";
616
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
617
-
618
-        $this->insert_default_data();
619
-        return true;
620
-    }
621
-
622
-
623
-    /**
624
-     * Inserts default data on new installs
625
-     *
626
-     * @throws EE_Error
627
-     * @throws ReflectionException
628
-     * @since 4.10.0.p
629
-     */
630
-    public function insert_default_data()
631
-    {
632
-        $this->previous_dms->insert_default_data();
633
-    }
634
-
635
-
636
-    /**
637
-     * @return boolean
638
-     */
639
-    public function schema_changes_after_migration()
640
-    {
641
-        return true;
642
-    }
643
-
644
-
645
-    public function migration_page_hooks()
646
-    {
647
-    }
616
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
617
+
618
+		$this->insert_default_data();
619
+		return true;
620
+	}
621
+
622
+
623
+	/**
624
+	 * Inserts default data on new installs
625
+	 *
626
+	 * @throws EE_Error
627
+	 * @throws ReflectionException
628
+	 * @since 4.10.0.p
629
+	 */
630
+	public function insert_default_data()
631
+	{
632
+		$this->previous_dms->insert_default_data();
633
+	}
634
+
635
+
636
+	/**
637
+	 * @return boolean
638
+	 */
639
+	public function schema_changes_after_migration()
640
+	{
641
+		return true;
642
+	}
643
+
644
+
645
+	public function migration_page_hooks()
646
+	{
647
+	}
648 648
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@
 block discarded – undo
57 57
      */
58 58
     public function schema_changes_before_migration()
59 59
     {
60
-        require_once EE_HELPERS . 'EEH_Activation.helper.php';
60
+        require_once EE_HELPERS.'EEH_Activation.helper.php';
61 61
 
62 62
         $table_name = 'esp_answer';
63 63
         $sql        = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 2 patches
Indentation   +1044 added lines, -1044 removed lines patch added patch discarded remove patch
@@ -21,1048 +21,1048 @@
 block discarded – undo
21 21
 class EE_Dependency_Map
22 22
 {
23 23
 
24
-    /**
25
-     * This means that the requested class dependency is not present in the dependency map
26
-     */
27
-    const not_registered = 0;
28
-
29
-    /**
30
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
31
-     */
32
-    const load_new_object = 1;
33
-
34
-    /**
35
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
36
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
37
-     */
38
-    const load_from_cache = 2;
39
-
40
-    /**
41
-     * When registering a dependency,
42
-     * this indicates to keep any existing dependencies that already exist,
43
-     * and simply discard any new dependencies declared in the incoming data
44
-     */
45
-    const KEEP_EXISTING_DEPENDENCIES = 0;
46
-
47
-    /**
48
-     * When registering a dependency,
49
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
50
-     */
51
-    const OVERWRITE_DEPENDENCIES = 1;
52
-
53
-    /**
54
-     * @type EE_Dependency_Map $_instance
55
-     */
56
-    protected static $_instance;
57
-
58
-    /**
59
-     * @var ClassInterfaceCache $class_cache
60
-     */
61
-    private $class_cache;
62
-
63
-    /**
64
-     * @type RequestInterface $request
65
-     */
66
-    protected $request;
67
-
68
-    /**
69
-     * @type LegacyRequestInterface $legacy_request
70
-     */
71
-    protected $legacy_request;
72
-
73
-    /**
74
-     * @type ResponseInterface $response
75
-     */
76
-    protected $response;
77
-
78
-    /**
79
-     * @type LoaderInterface $loader
80
-     */
81
-    protected $loader;
82
-
83
-    /**
84
-     * @type array $_dependency_map
85
-     */
86
-    protected $_dependency_map = [];
87
-
88
-    /**
89
-     * @type array $_class_loaders
90
-     */
91
-    protected $_class_loaders = [];
92
-
93
-
94
-    /**
95
-     * EE_Dependency_Map constructor.
96
-     *
97
-     * @param ClassInterfaceCache $class_cache
98
-     */
99
-    protected function __construct(ClassInterfaceCache $class_cache)
100
-    {
101
-        $this->class_cache = $class_cache;
102
-        do_action('EE_Dependency_Map____construct', $this);
103
-    }
104
-
105
-
106
-    /**
107
-     * @return void
108
-     * @throws InvalidAliasException
109
-     */
110
-    public function initialize()
111
-    {
112
-        $this->_register_core_dependencies();
113
-        $this->_register_core_class_loaders();
114
-        $this->_register_core_aliases();
115
-    }
116
-
117
-
118
-    /**
119
-     * @singleton method used to instantiate class object
120
-     * @param ClassInterfaceCache|null $class_cache
121
-     * @return EE_Dependency_Map
122
-     */
123
-    public static function instance(ClassInterfaceCache $class_cache = null)
124
-    {
125
-        // check if class object is instantiated, and instantiated properly
126
-        if (
127
-            ! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
128
-            && $class_cache instanceof ClassInterfaceCache
129
-        ) {
130
-            EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
131
-        }
132
-        return EE_Dependency_Map::$_instance;
133
-    }
134
-
135
-
136
-    /**
137
-     * @param RequestInterface $request
138
-     */
139
-    public function setRequest(RequestInterface $request)
140
-    {
141
-        $this->request = $request;
142
-    }
143
-
144
-
145
-    /**
146
-     * @param LegacyRequestInterface $legacy_request
147
-     */
148
-    public function setLegacyRequest(LegacyRequestInterface $legacy_request)
149
-    {
150
-        $this->legacy_request = $legacy_request;
151
-    }
152
-
153
-
154
-    /**
155
-     * @param ResponseInterface $response
156
-     */
157
-    public function setResponse(ResponseInterface $response)
158
-    {
159
-        $this->response = $response;
160
-    }
161
-
162
-
163
-    /**
164
-     * @param LoaderInterface $loader
165
-     */
166
-    public function setLoader(LoaderInterface $loader)
167
-    {
168
-        $this->loader = $loader;
169
-    }
170
-
171
-
172
-    /**
173
-     * @param string $class
174
-     * @param array  $dependencies
175
-     * @param int    $overwrite
176
-     * @return bool
177
-     */
178
-    public static function register_dependencies(
179
-        $class,
180
-        array $dependencies,
181
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
182
-    ) {
183
-        return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
184
-    }
185
-
186
-
187
-    /**
188
-     * Assigns an array of class names and corresponding load sources (new or cached)
189
-     * to the class specified by the first parameter.
190
-     * IMPORTANT !!!
191
-     * The order of elements in the incoming $dependencies array MUST match
192
-     * the order of the constructor parameters for the class in question.
193
-     * This is especially important when overriding any existing dependencies that are registered.
194
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
195
-     *
196
-     * @param string $class
197
-     * @param array  $dependencies
198
-     * @param int    $overwrite
199
-     * @return bool
200
-     */
201
-    public function registerDependencies(
202
-        $class,
203
-        array $dependencies,
204
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
205
-    ) {
206
-        $class      = trim($class, '\\');
207
-        $registered = false;
208
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
209
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
210
-        }
211
-        // we need to make sure that any aliases used when registering a dependency
212
-        // get resolved to the correct class name
213
-        foreach ($dependencies as $dependency => $load_source) {
214
-            $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
215
-            if (
216
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
217
-                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
218
-            ) {
219
-                unset($dependencies[ $dependency ]);
220
-                $dependencies[ $alias ] = $load_source;
221
-                $registered             = true;
222
-            }
223
-        }
224
-        // now add our two lists of dependencies together.
225
-        // using Union (+=) favours the arrays in precedence from left to right,
226
-        // so $dependencies is NOT overwritten because it is listed first
227
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
228
-        // Union is way faster than array_merge() but should be used with caution...
229
-        // especially with numerically indexed arrays
230
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
231
-        // now we need to ensure that the resulting dependencies
232
-        // array only has the entries that are required for the class
233
-        // so first count how many dependencies were originally registered for the class
234
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
235
-        // if that count is non-zero (meaning dependencies were already registered)
236
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
237
-            // then truncate the  final array to match that count
238
-            ? array_slice($dependencies, 0, $dependency_count)
239
-            // otherwise just take the incoming array because nothing previously existed
240
-            : $dependencies;
241
-        return $registered;
242
-    }
243
-
244
-
245
-    /**
246
-     * @param string $class_name
247
-     * @param string $loader
248
-     * @return bool
249
-     * @throws DomainException
250
-     */
251
-    public static function register_class_loader($class_name, $loader = 'load_core')
252
-    {
253
-        return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader);
254
-    }
255
-
256
-
257
-    /**
258
-     * @param string $class_name
259
-     * @param string $loader
260
-     * @return bool
261
-     * @throws DomainException
262
-     */
263
-    public function registerClassLoader($class_name, $loader = 'load_core')
264
-    {
265
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
266
-            throw new DomainException(
267
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
268
-            );
269
-        }
270
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
271
-        if (
272
-            ! is_callable($loader)
273
-            && (
274
-                strpos($loader, 'load_') !== 0
275
-                || ! method_exists('EE_Registry', $loader)
276
-            )
277
-        ) {
278
-            throw new DomainException(
279
-                sprintf(
280
-                    esc_html__(
281
-                        '"%1$s" is not a valid loader method on EE_Registry.',
282
-                        'event_espresso'
283
-                    ),
284
-                    $loader
285
-                )
286
-            );
287
-        }
288
-        $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
289
-        if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
290
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
291
-            return true;
292
-        }
293
-        return false;
294
-    }
295
-
296
-
297
-    /**
298
-     * @return array
299
-     */
300
-    public function dependency_map()
301
-    {
302
-        return $this->_dependency_map;
303
-    }
304
-
305
-
306
-    /**
307
-     * returns TRUE if dependency map contains a listing for the provided class name
308
-     *
309
-     * @param string $class_name
310
-     * @return boolean
311
-     */
312
-    public function has($class_name = '')
313
-    {
314
-        // all legacy models have the same dependencies
315
-        if (strpos($class_name, 'EEM_') === 0) {
316
-            $class_name = 'LEGACY_MODELS';
317
-        }
318
-        return isset($this->_dependency_map[ $class_name ]);
319
-    }
320
-
321
-
322
-    /**
323
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
324
-     *
325
-     * @param string $class_name
326
-     * @param string $dependency
327
-     * @return bool
328
-     */
329
-    public function has_dependency_for_class($class_name = '', $dependency = '')
330
-    {
331
-        // all legacy models have the same dependencies
332
-        if (strpos($class_name, 'EEM_') === 0) {
333
-            $class_name = 'LEGACY_MODELS';
334
-        }
335
-        $dependency = $this->getFqnForAlias($dependency, $class_name);
336
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
337
-    }
338
-
339
-
340
-    /**
341
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
342
-     *
343
-     * @param string $class_name
344
-     * @param string $dependency
345
-     * @return int
346
-     */
347
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
348
-    {
349
-        // all legacy models have the same dependencies
350
-        if (strpos($class_name, 'EEM_') === 0) {
351
-            $class_name = 'LEGACY_MODELS';
352
-        }
353
-        $dependency = $this->getFqnForAlias($dependency);
354
-        return $this->has_dependency_for_class($class_name, $dependency)
355
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
356
-            : EE_Dependency_Map::not_registered;
357
-    }
358
-
359
-
360
-    /**
361
-     * @param string $class_name
362
-     * @return string | Closure
363
-     */
364
-    public function class_loader($class_name)
365
-    {
366
-        // all legacy models use load_model()
367
-        if (strpos($class_name, 'EEM_') === 0) {
368
-            return 'load_model';
369
-        }
370
-        // EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
371
-        // perform strpos() first to avoid loading regex every time we load a class
372
-        if (
373
-            strpos($class_name, 'EE_CPT_') === 0
374
-            && preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
375
-        ) {
376
-            return 'load_core';
377
-        }
378
-        $class_name = $this->getFqnForAlias($class_name);
379
-        return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
380
-    }
381
-
382
-
383
-    /**
384
-     * @return array
385
-     */
386
-    public function class_loaders()
387
-    {
388
-        return $this->_class_loaders;
389
-    }
390
-
391
-
392
-    /**
393
-     * adds an alias for a classname
394
-     *
395
-     * @param string $fqcn      the class name that should be used (concrete class to replace interface)
396
-     * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
397
-     * @param string $for_class the class that has the dependency (is type hinting for the interface)
398
-     * @throws InvalidAliasException
399
-     */
400
-    public function add_alias($fqcn, $alias, $for_class = '')
401
-    {
402
-        $this->class_cache->addAlias($fqcn, $alias, $for_class);
403
-    }
404
-
405
-
406
-    /**
407
-     * Returns TRUE if the provided fully qualified name IS an alias
408
-     * WHY?
409
-     * Because if a class is type hinting for a concretion,
410
-     * then why would we need to find another class to supply it?
411
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
412
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
413
-     * Don't go looking for some substitute.
414
-     * Whereas if a class is type hinting for an interface...
415
-     * then we need to find an actual class to use.
416
-     * So the interface IS the alias for some other FQN,
417
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
418
-     * represents some other class.
419
-     *
420
-     * @param string $fqn
421
-     * @param string $for_class
422
-     * @return bool
423
-     */
424
-    public function isAlias($fqn = '', $for_class = '')
425
-    {
426
-        return $this->class_cache->isAlias($fqn, $for_class);
427
-    }
428
-
429
-
430
-    /**
431
-     * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
432
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
433
-     *  for example:
434
-     *      if the following two entries were added to the _aliases array:
435
-     *          array(
436
-     *              'interface_alias'           => 'some\namespace\interface'
437
-     *              'some\namespace\interface'  => 'some\namespace\classname'
438
-     *          )
439
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
440
-     *      to load an instance of 'some\namespace\classname'
441
-     *
442
-     * @param string $alias
443
-     * @param string $for_class
444
-     * @return string
445
-     */
446
-    public function getFqnForAlias($alias = '', $for_class = '')
447
-    {
448
-        return (string) $this->class_cache->getFqnForAlias($alias, $for_class);
449
-    }
450
-
451
-
452
-    /**
453
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
454
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
455
-     * This is done by using the following class constants:
456
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
457
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
458
-     */
459
-    protected function _register_core_dependencies()
460
-    {
461
-        $this->_dependency_map = [
462
-            'EE_Request_Handler'                                                                                          => [
463
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
464
-            ],
465
-            'EE_System'                                                                                                   => [
466
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
467
-                'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
468
-                'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
469
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
470
-                'EventEspresso\core\services\routing\Router'  => EE_Dependency_Map::load_from_cache,
471
-            ],
472
-            'EE_Admin'                                                                                                    => [
473
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
474
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
475
-            ],
476
-            'EE_Cart'                                                                                                     => [
477
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
478
-            ],
479
-            'EE_Messenger_Collection_Loader'                                                                              => [
480
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
481
-            ],
482
-            'EE_Message_Type_Collection_Loader'                                                                           => [
483
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
484
-            ],
485
-            'EE_Message_Resource_Manager'                                                                                 => [
486
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
487
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
488
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
489
-            ],
490
-            'EE_Message_Factory'                                                                                          => [
491
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
492
-            ],
493
-            'EE_messages'                                                                                                 => [
494
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
-            ],
496
-            'EE_Messages_Generator'                                                                                       => [
497
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
498
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
499
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
500
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
501
-            ],
502
-            'EE_Messages_Processor'                                                                                       => [
503
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
504
-            ],
505
-            'EE_Messages_Queue'                                                                                           => [
506
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
507
-            ],
508
-            'EE_Messages_Template_Defaults'                                                                               => [
509
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
510
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
511
-            ],
512
-            'EE_Message_To_Generate_From_Request'                                                                         => [
513
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
514
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
515
-            ],
516
-            'EventEspresso\core\services\commands\CommandBus'                                                             => [
517
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
518
-            ],
519
-            'EventEspresso\services\commands\CommandHandler'                                                              => [
520
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
521
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
522
-            ],
523
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => [
524
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
525
-            ],
526
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => [
527
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
528
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
529
-            ],
530
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => [
531
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
532
-            ],
533
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => [
534
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
535
-            ],
536
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => [
537
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
538
-            ],
539
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => [
540
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
-            ],
542
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => [
543
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
544
-            ],
545
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
546
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
547
-            ],
548
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
549
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
-            ],
551
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
552
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
553
-            ],
554
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
555
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
556
-            ],
557
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
558
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
559
-            ],
560
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
561
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
-            ],
563
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => [
564
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
-            ],
566
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
567
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
568
-            ],
569
-            'EventEspresso\core\services\database\TableManager'                                                           => [
570
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
571
-            ],
572
-            'EE_Data_Migration_Class_Base'                                                                                => [
573
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
574
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
575
-            ],
576
-            'EE_DMS_Core_4_1_0'                                                                                           => [
577
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
578
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
579
-            ],
580
-            'EE_DMS_Core_4_2_0'                                                                                           => [
581
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
582
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
583
-            ],
584
-            'EE_DMS_Core_4_3_0'                                                                                           => [
585
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
586
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
587
-            ],
588
-            'EE_DMS_Core_4_4_0'                                                                                           => [
589
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
590
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
591
-            ],
592
-            'EE_DMS_Core_4_5_0'                                                                                           => [
593
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
594
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
595
-            ],
596
-            'EE_DMS_Core_4_6_0'                                                                                           => [
597
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
598
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
599
-            ],
600
-            'EE_DMS_Core_4_7_0'                                                                                           => [
601
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
602
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
603
-            ],
604
-            'EE_DMS_Core_4_8_0'                                                                                           => [
605
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
606
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
607
-            ],
608
-            'EE_DMS_Core_4_9_0'                                                                                           => [
609
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
610
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
611
-            ],
612
-            'EE_DMS_Core_4_10_0'                                                                                          => [
613
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
614
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
615
-                'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
616
-            ],
617
-            'EE_DMS_Core_4_11_0'                                                                                          => [
618
-                'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
619
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
-            ],
622
-            'EE_DMS_Core_4_12_0' => [
623
-                'EE_DMS_Core_4_11_0'                                 => EE_Dependency_Map::load_from_cache,
624
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
625
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
626
-            ],
627
-            'EventEspresso\core\services\assets\Registry'                                                                 => [
628
-                'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_new_object,
629
-                'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
630
-            ],
631
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                         => [
632
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
633
-            ],
634
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => [
635
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
636
-            ],
637
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                  => [
638
-                'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
639
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
640
-            ],
641
-            'EventEspresso\core\domain\values\EmailAddress'                                                               => [
642
-                null,
643
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
644
-            ],
645
-            'EventEspresso\core\services\orm\ModelFieldFactory'                                                           => [
646
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
647
-            ],
648
-            'LEGACY_MODELS'                                                                                               => [
649
-                null,
650
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
651
-            ],
652
-            'EE_Module_Request_Router'                                                                                    => [
653
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
654
-            ],
655
-            'EE_Registration_Processor'                                                                                   => [
656
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
657
-            ],
658
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                      => [
659
-                null,
660
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
661
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
662
-            ],
663
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                    => [
664
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
665
-                'EE_Session'             => EE_Dependency_Map::load_from_cache,
666
-            ],
667
-            'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                 => [
668
-                'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
669
-            ],
670
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                 => [
671
-                'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
672
-                'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
673
-                'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
674
-                'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
675
-                'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
676
-            ],
677
-            'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                     => [
678
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
679
-            ],
680
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                              => [
681
-                'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
682
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
683
-            ],
684
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                => [
685
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
686
-            ],
687
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                               => [
688
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
689
-            ],
690
-            'EE_CPT_Strategy'                                                                                             => [
691
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
692
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
693
-            ],
694
-            'EventEspresso\core\services\loaders\ObjectIdentifier'                                                        => [
695
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
696
-            ],
697
-            'EventEspresso\core\CPTs\CptQueryModifier'                                                                    => [
698
-                null,
699
-                null,
700
-                null,
701
-                'EE_Request_Handler'                          => EE_Dependency_Map::load_from_cache,
702
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
703
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
704
-            ],
705
-            'EventEspresso\core\services\dependencies\DependencyResolver'                                                 => [
706
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
707
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
708
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
709
-            ],
710
-            'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                               => [
711
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
712
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
713
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
714
-            ],
715
-            'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                          => [
716
-                'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
717
-                'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
718
-            ],
719
-            'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                          => [
720
-                'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
721
-                'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
722
-            ],
723
-            'EE_URL_Validation_Strategy'                                                                                  => [
724
-                null,
725
-                null,
726
-                'EventEspresso\core\services\validators\URLValidator' => EE_Dependency_Map::load_from_cache,
727
-            ],
728
-            'EventEspresso\core\services\request\files\FilesDataHandler'                                                  => [
729
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
730
-            ],
731
-            'EventEspressoBatchRequest\BatchRequestProcessor'                                                             => [
732
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
733
-            ],
734
-            'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                => [
735
-                'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
736
-                'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
737
-                'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
738
-                null,
739
-            ],
740
-            'EventEspresso\core\services\routing\RouteHandler'                                                            => [
741
-                'EventEspresso\core\services\json\JsonDataNodeHandler' => EE_Dependency_Map::load_from_cache,
742
-                'EventEspresso\core\services\loaders\Loader'           => EE_Dependency_Map::load_from_cache,
743
-                'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
744
-                'EventEspresso\core\services\routing\RouteCollection'  => EE_Dependency_Map::load_from_cache,
745
-            ],
746
-            'EventEspresso\core\services\json\JsonDataNodeHandler'                                                        => [
747
-                'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
748
-            ],
749
-            'EventEspresso\core\services\routing\Router'                                                                  => [
750
-                'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
751
-                'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
752
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
753
-            ],
754
-            'EventEspresso\core\services\assets\AssetManifest'                                                            => [
755
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
756
-            ],
757
-            'EventEspresso\core\services\assets\AssetManifestFactory'                                                     => [
758
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
759
-            ],
760
-            'EventEspresso\core\services\assets\BaristaFactory'                                                           => [
761
-                'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
762
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
763
-            ],
764
-            'EventEspresso\core\domain\services\capabilities\FeatureFlags'                                                => [
765
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
766
-            ],
767
-            'EventEspresso\core\services\addon\AddonManager' => [
768
-                'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
769
-                'EventEspresso\core\Psr4Autoloader'                              => EE_Dependency_Map::load_from_cache,
770
-                'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
771
-                'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
772
-                'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
773
-            ],
774
-            'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler' => [
775
-                'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
776
-            ],
777
-            'EventEspressoBatchRequest\JobHandlers\ExecuteBatchDeletion' => [
778
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
779
-            ],
780
-            'EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion' => [
781
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
782
-            ],
783
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion' => [
784
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
785
-                'EEM_Event' => EE_Dependency_Map::load_from_cache,
786
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
787
-                'EEM_Registration' => EE_Dependency_Map::load_from_cache
788
-            ],
789
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion' => [
790
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
791
-            ],
792
-            'EventEspresso\core\domain\entities\users\CurrentUser' => [
793
-                'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
794
-            ],
795
-        ];
796
-    }
797
-
798
-
799
-    /**
800
-     * Registers how core classes are loaded.
801
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
802
-     *        'EE_Request_Handler' => 'load_core'
803
-     *        'EE_Messages_Queue'  => 'load_lib'
804
-     *        'EEH_Debug_Tools'    => 'load_helper'
805
-     * or, if greater control is required, by providing a custom closure. For example:
806
-     *        'Some_Class' => function () {
807
-     *            return new Some_Class();
808
-     *        },
809
-     * This is required for instantiating dependencies
810
-     * where an interface has been type hinted in a class constructor. For example:
811
-     *        'Required_Interface' => function () {
812
-     *            return new A_Class_That_Implements_Required_Interface();
813
-     *        },
814
-     */
815
-    protected function _register_core_class_loaders()
816
-    {
817
-        $this->_class_loaders = [
818
-            // load_core
819
-            'EE_Dependency_Map'                            => function () {
820
-                return $this;
821
-            },
822
-            'EE_Capabilities'                              => 'load_core',
823
-            'EE_Encryption'                                => 'load_core',
824
-            'EE_Front_Controller'                          => 'load_core',
825
-            'EE_Module_Request_Router'                     => 'load_core',
826
-            'EE_Registry'                                  => 'load_core',
827
-            'EE_Request'                                   => function () {
828
-                return $this->legacy_request;
829
-            },
830
-            'EventEspresso\core\services\request\Request'  => function () {
831
-                return $this->request;
832
-            },
833
-            'EventEspresso\core\services\request\Response' => function () {
834
-                return $this->response;
835
-            },
836
-            'EE_Base'                                      => 'load_core',
837
-            'EE_Request_Handler'                           => 'load_core',
838
-            'EE_Session'                                   => 'load_core',
839
-            'EE_Cron_Tasks'                                => 'load_core',
840
-            'EE_System'                                    => 'load_core',
841
-            'EE_Maintenance_Mode'                          => 'load_core',
842
-            'EE_Register_CPTs'                             => 'load_core',
843
-            'EE_Admin'                                     => 'load_core',
844
-            'EE_CPT_Strategy'                              => 'load_core',
845
-            // load_class
846
-            'EE_Registration_Processor'                    => 'load_class',
847
-            // load_lib
848
-            'EE_Message_Resource_Manager'                  => 'load_lib',
849
-            'EE_Message_Type_Collection'                   => 'load_lib',
850
-            'EE_Message_Type_Collection_Loader'            => 'load_lib',
851
-            'EE_Messenger_Collection'                      => 'load_lib',
852
-            'EE_Messenger_Collection_Loader'               => 'load_lib',
853
-            'EE_Messages_Processor'                        => 'load_lib',
854
-            'EE_Message_Repository'                        => 'load_lib',
855
-            'EE_Messages_Queue'                            => 'load_lib',
856
-            'EE_Messages_Data_Handler_Collection'          => 'load_lib',
857
-            'EE_Message_Template_Group_Collection'         => 'load_lib',
858
-            'EE_Payment_Method_Manager'                    => 'load_lib',
859
-            'EE_DMS_Core_4_1_0'                            => 'load_dms',
860
-            'EE_DMS_Core_4_2_0'                            => 'load_dms',
861
-            'EE_DMS_Core_4_3_0'                            => 'load_dms',
862
-            'EE_DMS_Core_4_5_0'                            => 'load_dms',
863
-            'EE_DMS_Core_4_6_0'                            => 'load_dms',
864
-            'EE_DMS_Core_4_7_0'                            => 'load_dms',
865
-            'EE_DMS_Core_4_8_0'                            => 'load_dms',
866
-            'EE_DMS_Core_4_9_0'                            => 'load_dms',
867
-            'EE_DMS_Core_4_10_0'                           => 'load_dms',
868
-            'EE_DMS_Core_4_11_0'                           => 'load_dms',
869
-            'EE_DMS_Core_4_12_0'                           => 'load_dms',
870
-            'EE_Messages_Generator'                        => static function () {
871
-                return EE_Registry::instance()->load_lib(
872
-                    'Messages_Generator',
873
-                    [],
874
-                    false,
875
-                    false
876
-                );
877
-            },
878
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
879
-                return EE_Registry::instance()->load_lib(
880
-                    'Messages_Template_Defaults',
881
-                    $arguments,
882
-                    false,
883
-                    false
884
-                );
885
-            },
886
-            // load_helper
887
-            'EEH_Parse_Shortcodes'                         => static function () {
888
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
889
-                    return new EEH_Parse_Shortcodes();
890
-                }
891
-                return null;
892
-            },
893
-            'EE_Template_Config'                           => static function () {
894
-                return EE_Config::instance()->template_settings;
895
-            },
896
-            'EE_Currency_Config'                           => static function () {
897
-                return EE_Config::instance()->currency;
898
-            },
899
-            'EE_Registration_Config'                       => static function () {
900
-                return EE_Config::instance()->registration;
901
-            },
902
-            'EE_Core_Config'                               => static function () {
903
-                return EE_Config::instance()->core;
904
-            },
905
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
906
-                return LoaderFactory::getLoader();
907
-            },
908
-            'EE_Network_Config'                            => static function () {
909
-                return EE_Network_Config::instance();
910
-            },
911
-            'EE_Config'                                    => static function () {
912
-                return EE_Config::instance();
913
-            },
914
-            'EventEspresso\core\domain\Domain'             => static function () {
915
-                return DomainFactory::getEventEspressoCoreDomain();
916
-            },
917
-            'EE_Admin_Config'                              => static function () {
918
-                return EE_Config::instance()->admin;
919
-            },
920
-            'EE_Organization_Config'                       => static function () {
921
-                return EE_Config::instance()->organization;
922
-            },
923
-            'EE_Network_Core_Config'                       => static function () {
924
-                return EE_Network_Config::instance()->core;
925
-            },
926
-            'EE_Environment_Config'                        => static function () {
927
-                return EE_Config::instance()->environment;
928
-            },
929
-            'EED_Core_Rest_Api'                            => static function () {
930
-                return EED_Core_Rest_Api::instance();
931
-            },
932
-            'WP_REST_Server'                               => static function () {
933
-                return rest_get_server();
934
-            },
935
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
936
-                return EE_Psr4AutoloaderInit::psr4_loader();
937
-            },
938
-        ];
939
-    }
940
-
941
-
942
-    /**
943
-     * can be used for supplying alternate names for classes,
944
-     * or for connecting interface names to instantiable classes
945
-     *
946
-     * @throws InvalidAliasException
947
-     */
948
-    protected function _register_core_aliases()
949
-    {
950
-        $aliases = [
951
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
952
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
953
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
954
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
955
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
956
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
957
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
958
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
959
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
960
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
961
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
962
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
963
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
964
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
965
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
966
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
967
-            'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
968
-            'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
969
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
970
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
971
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
972
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
973
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
974
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
975
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
976
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
977
-            'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
978
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
979
-            'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
980
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
981
-            'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
982
-            'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
983
-            'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
984
-            'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
985
-            'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
986
-            'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
987
-            'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
988
-            'Registration_Processor'                                                       => 'EE_Registration_Processor',
989
-            'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
990
-        ];
991
-        foreach ($aliases as $alias => $fqn) {
992
-            if (is_array($fqn)) {
993
-                foreach ($fqn as $class => $for_class) {
994
-                    $this->class_cache->addAlias($class, $alias, $for_class);
995
-                }
996
-                continue;
997
-            }
998
-            $this->class_cache->addAlias($fqn, $alias);
999
-        }
1000
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1001
-            $this->class_cache->addAlias(
1002
-                'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1003
-                'EventEspresso\core\services\notices\NoticeConverterInterface'
1004
-            );
1005
-        }
1006
-    }
1007
-
1008
-
1009
-    /**
1010
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1011
-     * request Primarily used by unit tests.
1012
-     */
1013
-    public function reset()
1014
-    {
1015
-        $this->_register_core_class_loaders();
1016
-        $this->_register_core_dependencies();
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * PLZ NOTE: a better name for this method would be is_alias()
1022
-     * because it returns TRUE if the provided fully qualified name IS an alias
1023
-     * WHY?
1024
-     * Because if a class is type hinting for a concretion,
1025
-     * then why would we need to find another class to supply it?
1026
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1027
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1028
-     * Don't go looking for some substitute.
1029
-     * Whereas if a class is type hinting for an interface...
1030
-     * then we need to find an actual class to use.
1031
-     * So the interface IS the alias for some other FQN,
1032
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1033
-     * represents some other class.
1034
-     *
1035
-     * @param string $fqn
1036
-     * @param string $for_class
1037
-     * @return bool
1038
-     * @deprecated 4.9.62.p
1039
-     */
1040
-    public function has_alias($fqn = '', $for_class = '')
1041
-    {
1042
-        return $this->isAlias($fqn, $for_class);
1043
-    }
1044
-
1045
-
1046
-    /**
1047
-     * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1048
-     * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1049
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
1050
-     *  for example:
1051
-     *      if the following two entries were added to the _aliases array:
1052
-     *          array(
1053
-     *              'interface_alias'           => 'some\namespace\interface'
1054
-     *              'some\namespace\interface'  => 'some\namespace\classname'
1055
-     *          )
1056
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1057
-     *      to load an instance of 'some\namespace\classname'
1058
-     *
1059
-     * @param string $alias
1060
-     * @param string $for_class
1061
-     * @return string
1062
-     * @deprecated 4.9.62.p
1063
-     */
1064
-    public function get_alias($alias = '', $for_class = '')
1065
-    {
1066
-        return $this->getFqnForAlias($alias, $for_class);
1067
-    }
24
+	/**
25
+	 * This means that the requested class dependency is not present in the dependency map
26
+	 */
27
+	const not_registered = 0;
28
+
29
+	/**
30
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
31
+	 */
32
+	const load_new_object = 1;
33
+
34
+	/**
35
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
36
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
37
+	 */
38
+	const load_from_cache = 2;
39
+
40
+	/**
41
+	 * When registering a dependency,
42
+	 * this indicates to keep any existing dependencies that already exist,
43
+	 * and simply discard any new dependencies declared in the incoming data
44
+	 */
45
+	const KEEP_EXISTING_DEPENDENCIES = 0;
46
+
47
+	/**
48
+	 * When registering a dependency,
49
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
50
+	 */
51
+	const OVERWRITE_DEPENDENCIES = 1;
52
+
53
+	/**
54
+	 * @type EE_Dependency_Map $_instance
55
+	 */
56
+	protected static $_instance;
57
+
58
+	/**
59
+	 * @var ClassInterfaceCache $class_cache
60
+	 */
61
+	private $class_cache;
62
+
63
+	/**
64
+	 * @type RequestInterface $request
65
+	 */
66
+	protected $request;
67
+
68
+	/**
69
+	 * @type LegacyRequestInterface $legacy_request
70
+	 */
71
+	protected $legacy_request;
72
+
73
+	/**
74
+	 * @type ResponseInterface $response
75
+	 */
76
+	protected $response;
77
+
78
+	/**
79
+	 * @type LoaderInterface $loader
80
+	 */
81
+	protected $loader;
82
+
83
+	/**
84
+	 * @type array $_dependency_map
85
+	 */
86
+	protected $_dependency_map = [];
87
+
88
+	/**
89
+	 * @type array $_class_loaders
90
+	 */
91
+	protected $_class_loaders = [];
92
+
93
+
94
+	/**
95
+	 * EE_Dependency_Map constructor.
96
+	 *
97
+	 * @param ClassInterfaceCache $class_cache
98
+	 */
99
+	protected function __construct(ClassInterfaceCache $class_cache)
100
+	{
101
+		$this->class_cache = $class_cache;
102
+		do_action('EE_Dependency_Map____construct', $this);
103
+	}
104
+
105
+
106
+	/**
107
+	 * @return void
108
+	 * @throws InvalidAliasException
109
+	 */
110
+	public function initialize()
111
+	{
112
+		$this->_register_core_dependencies();
113
+		$this->_register_core_class_loaders();
114
+		$this->_register_core_aliases();
115
+	}
116
+
117
+
118
+	/**
119
+	 * @singleton method used to instantiate class object
120
+	 * @param ClassInterfaceCache|null $class_cache
121
+	 * @return EE_Dependency_Map
122
+	 */
123
+	public static function instance(ClassInterfaceCache $class_cache = null)
124
+	{
125
+		// check if class object is instantiated, and instantiated properly
126
+		if (
127
+			! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
128
+			&& $class_cache instanceof ClassInterfaceCache
129
+		) {
130
+			EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
131
+		}
132
+		return EE_Dependency_Map::$_instance;
133
+	}
134
+
135
+
136
+	/**
137
+	 * @param RequestInterface $request
138
+	 */
139
+	public function setRequest(RequestInterface $request)
140
+	{
141
+		$this->request = $request;
142
+	}
143
+
144
+
145
+	/**
146
+	 * @param LegacyRequestInterface $legacy_request
147
+	 */
148
+	public function setLegacyRequest(LegacyRequestInterface $legacy_request)
149
+	{
150
+		$this->legacy_request = $legacy_request;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @param ResponseInterface $response
156
+	 */
157
+	public function setResponse(ResponseInterface $response)
158
+	{
159
+		$this->response = $response;
160
+	}
161
+
162
+
163
+	/**
164
+	 * @param LoaderInterface $loader
165
+	 */
166
+	public function setLoader(LoaderInterface $loader)
167
+	{
168
+		$this->loader = $loader;
169
+	}
170
+
171
+
172
+	/**
173
+	 * @param string $class
174
+	 * @param array  $dependencies
175
+	 * @param int    $overwrite
176
+	 * @return bool
177
+	 */
178
+	public static function register_dependencies(
179
+		$class,
180
+		array $dependencies,
181
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
182
+	) {
183
+		return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
184
+	}
185
+
186
+
187
+	/**
188
+	 * Assigns an array of class names and corresponding load sources (new or cached)
189
+	 * to the class specified by the first parameter.
190
+	 * IMPORTANT !!!
191
+	 * The order of elements in the incoming $dependencies array MUST match
192
+	 * the order of the constructor parameters for the class in question.
193
+	 * This is especially important when overriding any existing dependencies that are registered.
194
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
195
+	 *
196
+	 * @param string $class
197
+	 * @param array  $dependencies
198
+	 * @param int    $overwrite
199
+	 * @return bool
200
+	 */
201
+	public function registerDependencies(
202
+		$class,
203
+		array $dependencies,
204
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
205
+	) {
206
+		$class      = trim($class, '\\');
207
+		$registered = false;
208
+		if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
209
+			EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
210
+		}
211
+		// we need to make sure that any aliases used when registering a dependency
212
+		// get resolved to the correct class name
213
+		foreach ($dependencies as $dependency => $load_source) {
214
+			$alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
215
+			if (
216
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
217
+				|| ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
218
+			) {
219
+				unset($dependencies[ $dependency ]);
220
+				$dependencies[ $alias ] = $load_source;
221
+				$registered             = true;
222
+			}
223
+		}
224
+		// now add our two lists of dependencies together.
225
+		// using Union (+=) favours the arrays in precedence from left to right,
226
+		// so $dependencies is NOT overwritten because it is listed first
227
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
228
+		// Union is way faster than array_merge() but should be used with caution...
229
+		// especially with numerically indexed arrays
230
+		$dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
231
+		// now we need to ensure that the resulting dependencies
232
+		// array only has the entries that are required for the class
233
+		// so first count how many dependencies were originally registered for the class
234
+		$dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
235
+		// if that count is non-zero (meaning dependencies were already registered)
236
+		EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
237
+			// then truncate the  final array to match that count
238
+			? array_slice($dependencies, 0, $dependency_count)
239
+			// otherwise just take the incoming array because nothing previously existed
240
+			: $dependencies;
241
+		return $registered;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @param string $class_name
247
+	 * @param string $loader
248
+	 * @return bool
249
+	 * @throws DomainException
250
+	 */
251
+	public static function register_class_loader($class_name, $loader = 'load_core')
252
+	{
253
+		return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader);
254
+	}
255
+
256
+
257
+	/**
258
+	 * @param string $class_name
259
+	 * @param string $loader
260
+	 * @return bool
261
+	 * @throws DomainException
262
+	 */
263
+	public function registerClassLoader($class_name, $loader = 'load_core')
264
+	{
265
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
266
+			throw new DomainException(
267
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
268
+			);
269
+		}
270
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
271
+		if (
272
+			! is_callable($loader)
273
+			&& (
274
+				strpos($loader, 'load_') !== 0
275
+				|| ! method_exists('EE_Registry', $loader)
276
+			)
277
+		) {
278
+			throw new DomainException(
279
+				sprintf(
280
+					esc_html__(
281
+						'"%1$s" is not a valid loader method on EE_Registry.',
282
+						'event_espresso'
283
+					),
284
+					$loader
285
+				)
286
+			);
287
+		}
288
+		$class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
289
+		if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
290
+			EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
291
+			return true;
292
+		}
293
+		return false;
294
+	}
295
+
296
+
297
+	/**
298
+	 * @return array
299
+	 */
300
+	public function dependency_map()
301
+	{
302
+		return $this->_dependency_map;
303
+	}
304
+
305
+
306
+	/**
307
+	 * returns TRUE if dependency map contains a listing for the provided class name
308
+	 *
309
+	 * @param string $class_name
310
+	 * @return boolean
311
+	 */
312
+	public function has($class_name = '')
313
+	{
314
+		// all legacy models have the same dependencies
315
+		if (strpos($class_name, 'EEM_') === 0) {
316
+			$class_name = 'LEGACY_MODELS';
317
+		}
318
+		return isset($this->_dependency_map[ $class_name ]);
319
+	}
320
+
321
+
322
+	/**
323
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
324
+	 *
325
+	 * @param string $class_name
326
+	 * @param string $dependency
327
+	 * @return bool
328
+	 */
329
+	public function has_dependency_for_class($class_name = '', $dependency = '')
330
+	{
331
+		// all legacy models have the same dependencies
332
+		if (strpos($class_name, 'EEM_') === 0) {
333
+			$class_name = 'LEGACY_MODELS';
334
+		}
335
+		$dependency = $this->getFqnForAlias($dependency, $class_name);
336
+		return isset($this->_dependency_map[ $class_name ][ $dependency ]);
337
+	}
338
+
339
+
340
+	/**
341
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
342
+	 *
343
+	 * @param string $class_name
344
+	 * @param string $dependency
345
+	 * @return int
346
+	 */
347
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
348
+	{
349
+		// all legacy models have the same dependencies
350
+		if (strpos($class_name, 'EEM_') === 0) {
351
+			$class_name = 'LEGACY_MODELS';
352
+		}
353
+		$dependency = $this->getFqnForAlias($dependency);
354
+		return $this->has_dependency_for_class($class_name, $dependency)
355
+			? $this->_dependency_map[ $class_name ][ $dependency ]
356
+			: EE_Dependency_Map::not_registered;
357
+	}
358
+
359
+
360
+	/**
361
+	 * @param string $class_name
362
+	 * @return string | Closure
363
+	 */
364
+	public function class_loader($class_name)
365
+	{
366
+		// all legacy models use load_model()
367
+		if (strpos($class_name, 'EEM_') === 0) {
368
+			return 'load_model';
369
+		}
370
+		// EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
371
+		// perform strpos() first to avoid loading regex every time we load a class
372
+		if (
373
+			strpos($class_name, 'EE_CPT_') === 0
374
+			&& preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
375
+		) {
376
+			return 'load_core';
377
+		}
378
+		$class_name = $this->getFqnForAlias($class_name);
379
+		return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
380
+	}
381
+
382
+
383
+	/**
384
+	 * @return array
385
+	 */
386
+	public function class_loaders()
387
+	{
388
+		return $this->_class_loaders;
389
+	}
390
+
391
+
392
+	/**
393
+	 * adds an alias for a classname
394
+	 *
395
+	 * @param string $fqcn      the class name that should be used (concrete class to replace interface)
396
+	 * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
397
+	 * @param string $for_class the class that has the dependency (is type hinting for the interface)
398
+	 * @throws InvalidAliasException
399
+	 */
400
+	public function add_alias($fqcn, $alias, $for_class = '')
401
+	{
402
+		$this->class_cache->addAlias($fqcn, $alias, $for_class);
403
+	}
404
+
405
+
406
+	/**
407
+	 * Returns TRUE if the provided fully qualified name IS an alias
408
+	 * WHY?
409
+	 * Because if a class is type hinting for a concretion,
410
+	 * then why would we need to find another class to supply it?
411
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
412
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
413
+	 * Don't go looking for some substitute.
414
+	 * Whereas if a class is type hinting for an interface...
415
+	 * then we need to find an actual class to use.
416
+	 * So the interface IS the alias for some other FQN,
417
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
418
+	 * represents some other class.
419
+	 *
420
+	 * @param string $fqn
421
+	 * @param string $for_class
422
+	 * @return bool
423
+	 */
424
+	public function isAlias($fqn = '', $for_class = '')
425
+	{
426
+		return $this->class_cache->isAlias($fqn, $for_class);
427
+	}
428
+
429
+
430
+	/**
431
+	 * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
432
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
433
+	 *  for example:
434
+	 *      if the following two entries were added to the _aliases array:
435
+	 *          array(
436
+	 *              'interface_alias'           => 'some\namespace\interface'
437
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
438
+	 *          )
439
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
440
+	 *      to load an instance of 'some\namespace\classname'
441
+	 *
442
+	 * @param string $alias
443
+	 * @param string $for_class
444
+	 * @return string
445
+	 */
446
+	public function getFqnForAlias($alias = '', $for_class = '')
447
+	{
448
+		return (string) $this->class_cache->getFqnForAlias($alias, $for_class);
449
+	}
450
+
451
+
452
+	/**
453
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
454
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
455
+	 * This is done by using the following class constants:
456
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
457
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
458
+	 */
459
+	protected function _register_core_dependencies()
460
+	{
461
+		$this->_dependency_map = [
462
+			'EE_Request_Handler'                                                                                          => [
463
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
464
+			],
465
+			'EE_System'                                                                                                   => [
466
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
467
+				'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
468
+				'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
469
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
470
+				'EventEspresso\core\services\routing\Router'  => EE_Dependency_Map::load_from_cache,
471
+			],
472
+			'EE_Admin'                                                                                                    => [
473
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
474
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
475
+			],
476
+			'EE_Cart'                                                                                                     => [
477
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
478
+			],
479
+			'EE_Messenger_Collection_Loader'                                                                              => [
480
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
481
+			],
482
+			'EE_Message_Type_Collection_Loader'                                                                           => [
483
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
484
+			],
485
+			'EE_Message_Resource_Manager'                                                                                 => [
486
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
487
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
488
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
489
+			],
490
+			'EE_Message_Factory'                                                                                          => [
491
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
492
+			],
493
+			'EE_messages'                                                                                                 => [
494
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
+			],
496
+			'EE_Messages_Generator'                                                                                       => [
497
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
498
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
499
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
500
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
501
+			],
502
+			'EE_Messages_Processor'                                                                                       => [
503
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
504
+			],
505
+			'EE_Messages_Queue'                                                                                           => [
506
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
507
+			],
508
+			'EE_Messages_Template_Defaults'                                                                               => [
509
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
510
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
511
+			],
512
+			'EE_Message_To_Generate_From_Request'                                                                         => [
513
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
514
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
515
+			],
516
+			'EventEspresso\core\services\commands\CommandBus'                                                             => [
517
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
518
+			],
519
+			'EventEspresso\services\commands\CommandHandler'                                                              => [
520
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
521
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
522
+			],
523
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => [
524
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
525
+			],
526
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => [
527
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
528
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
529
+			],
530
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => [
531
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
532
+			],
533
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => [
534
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
535
+			],
536
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => [
537
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
538
+			],
539
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => [
540
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
+			],
542
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => [
543
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
544
+			],
545
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
546
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
547
+			],
548
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
549
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
+			],
551
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
552
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
553
+			],
554
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
555
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
556
+			],
557
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
558
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
559
+			],
560
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
561
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
+			],
563
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => [
564
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
+			],
566
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
567
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
568
+			],
569
+			'EventEspresso\core\services\database\TableManager'                                                           => [
570
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
571
+			],
572
+			'EE_Data_Migration_Class_Base'                                                                                => [
573
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
574
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
575
+			],
576
+			'EE_DMS_Core_4_1_0'                                                                                           => [
577
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
578
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
579
+			],
580
+			'EE_DMS_Core_4_2_0'                                                                                           => [
581
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
582
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
583
+			],
584
+			'EE_DMS_Core_4_3_0'                                                                                           => [
585
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
586
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
587
+			],
588
+			'EE_DMS_Core_4_4_0'                                                                                           => [
589
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
590
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
591
+			],
592
+			'EE_DMS_Core_4_5_0'                                                                                           => [
593
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
594
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
595
+			],
596
+			'EE_DMS_Core_4_6_0'                                                                                           => [
597
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
598
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
599
+			],
600
+			'EE_DMS_Core_4_7_0'                                                                                           => [
601
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
602
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
603
+			],
604
+			'EE_DMS_Core_4_8_0'                                                                                           => [
605
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
606
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
607
+			],
608
+			'EE_DMS_Core_4_9_0'                                                                                           => [
609
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
610
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
611
+			],
612
+			'EE_DMS_Core_4_10_0'                                                                                          => [
613
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
614
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
615
+				'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
616
+			],
617
+			'EE_DMS_Core_4_11_0'                                                                                          => [
618
+				'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
619
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
+			],
622
+			'EE_DMS_Core_4_12_0' => [
623
+				'EE_DMS_Core_4_11_0'                                 => EE_Dependency_Map::load_from_cache,
624
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
625
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
626
+			],
627
+			'EventEspresso\core\services\assets\Registry'                                                                 => [
628
+				'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_new_object,
629
+				'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
630
+			],
631
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                         => [
632
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
633
+			],
634
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => [
635
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
636
+			],
637
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                  => [
638
+				'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
639
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
640
+			],
641
+			'EventEspresso\core\domain\values\EmailAddress'                                                               => [
642
+				null,
643
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
644
+			],
645
+			'EventEspresso\core\services\orm\ModelFieldFactory'                                                           => [
646
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
647
+			],
648
+			'LEGACY_MODELS'                                                                                               => [
649
+				null,
650
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
651
+			],
652
+			'EE_Module_Request_Router'                                                                                    => [
653
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
654
+			],
655
+			'EE_Registration_Processor'                                                                                   => [
656
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
657
+			],
658
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                      => [
659
+				null,
660
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
661
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
662
+			],
663
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                    => [
664
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
665
+				'EE_Session'             => EE_Dependency_Map::load_from_cache,
666
+			],
667
+			'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                 => [
668
+				'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
669
+			],
670
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                 => [
671
+				'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
672
+				'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
673
+				'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
674
+				'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
675
+				'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
676
+			],
677
+			'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                     => [
678
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
679
+			],
680
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                              => [
681
+				'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
682
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
683
+			],
684
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                => [
685
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
686
+			],
687
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                               => [
688
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
689
+			],
690
+			'EE_CPT_Strategy'                                                                                             => [
691
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
692
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
693
+			],
694
+			'EventEspresso\core\services\loaders\ObjectIdentifier'                                                        => [
695
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
696
+			],
697
+			'EventEspresso\core\CPTs\CptQueryModifier'                                                                    => [
698
+				null,
699
+				null,
700
+				null,
701
+				'EE_Request_Handler'                          => EE_Dependency_Map::load_from_cache,
702
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
703
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
704
+			],
705
+			'EventEspresso\core\services\dependencies\DependencyResolver'                                                 => [
706
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
707
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
708
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
709
+			],
710
+			'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                               => [
711
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
712
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
713
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
714
+			],
715
+			'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                          => [
716
+				'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
717
+				'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
718
+			],
719
+			'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                          => [
720
+				'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
721
+				'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
722
+			],
723
+			'EE_URL_Validation_Strategy'                                                                                  => [
724
+				null,
725
+				null,
726
+				'EventEspresso\core\services\validators\URLValidator' => EE_Dependency_Map::load_from_cache,
727
+			],
728
+			'EventEspresso\core\services\request\files\FilesDataHandler'                                                  => [
729
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
730
+			],
731
+			'EventEspressoBatchRequest\BatchRequestProcessor'                                                             => [
732
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
733
+			],
734
+			'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                => [
735
+				'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
736
+				'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
737
+				'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
738
+				null,
739
+			],
740
+			'EventEspresso\core\services\routing\RouteHandler'                                                            => [
741
+				'EventEspresso\core\services\json\JsonDataNodeHandler' => EE_Dependency_Map::load_from_cache,
742
+				'EventEspresso\core\services\loaders\Loader'           => EE_Dependency_Map::load_from_cache,
743
+				'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
744
+				'EventEspresso\core\services\routing\RouteCollection'  => EE_Dependency_Map::load_from_cache,
745
+			],
746
+			'EventEspresso\core\services\json\JsonDataNodeHandler'                                                        => [
747
+				'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
748
+			],
749
+			'EventEspresso\core\services\routing\Router'                                                                  => [
750
+				'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
751
+				'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
752
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
753
+			],
754
+			'EventEspresso\core\services\assets\AssetManifest'                                                            => [
755
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
756
+			],
757
+			'EventEspresso\core\services\assets\AssetManifestFactory'                                                     => [
758
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
759
+			],
760
+			'EventEspresso\core\services\assets\BaristaFactory'                                                           => [
761
+				'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
762
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
763
+			],
764
+			'EventEspresso\core\domain\services\capabilities\FeatureFlags'                                                => [
765
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
766
+			],
767
+			'EventEspresso\core\services\addon\AddonManager' => [
768
+				'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
769
+				'EventEspresso\core\Psr4Autoloader'                              => EE_Dependency_Map::load_from_cache,
770
+				'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
771
+				'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
772
+				'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
773
+			],
774
+			'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler' => [
775
+				'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
776
+			],
777
+			'EventEspressoBatchRequest\JobHandlers\ExecuteBatchDeletion' => [
778
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
779
+			],
780
+			'EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion' => [
781
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
782
+			],
783
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion' => [
784
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
785
+				'EEM_Event' => EE_Dependency_Map::load_from_cache,
786
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
787
+				'EEM_Registration' => EE_Dependency_Map::load_from_cache
788
+			],
789
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion' => [
790
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
791
+			],
792
+			'EventEspresso\core\domain\entities\users\CurrentUser' => [
793
+				'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
794
+			],
795
+		];
796
+	}
797
+
798
+
799
+	/**
800
+	 * Registers how core classes are loaded.
801
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
802
+	 *        'EE_Request_Handler' => 'load_core'
803
+	 *        'EE_Messages_Queue'  => 'load_lib'
804
+	 *        'EEH_Debug_Tools'    => 'load_helper'
805
+	 * or, if greater control is required, by providing a custom closure. For example:
806
+	 *        'Some_Class' => function () {
807
+	 *            return new Some_Class();
808
+	 *        },
809
+	 * This is required for instantiating dependencies
810
+	 * where an interface has been type hinted in a class constructor. For example:
811
+	 *        'Required_Interface' => function () {
812
+	 *            return new A_Class_That_Implements_Required_Interface();
813
+	 *        },
814
+	 */
815
+	protected function _register_core_class_loaders()
816
+	{
817
+		$this->_class_loaders = [
818
+			// load_core
819
+			'EE_Dependency_Map'                            => function () {
820
+				return $this;
821
+			},
822
+			'EE_Capabilities'                              => 'load_core',
823
+			'EE_Encryption'                                => 'load_core',
824
+			'EE_Front_Controller'                          => 'load_core',
825
+			'EE_Module_Request_Router'                     => 'load_core',
826
+			'EE_Registry'                                  => 'load_core',
827
+			'EE_Request'                                   => function () {
828
+				return $this->legacy_request;
829
+			},
830
+			'EventEspresso\core\services\request\Request'  => function () {
831
+				return $this->request;
832
+			},
833
+			'EventEspresso\core\services\request\Response' => function () {
834
+				return $this->response;
835
+			},
836
+			'EE_Base'                                      => 'load_core',
837
+			'EE_Request_Handler'                           => 'load_core',
838
+			'EE_Session'                                   => 'load_core',
839
+			'EE_Cron_Tasks'                                => 'load_core',
840
+			'EE_System'                                    => 'load_core',
841
+			'EE_Maintenance_Mode'                          => 'load_core',
842
+			'EE_Register_CPTs'                             => 'load_core',
843
+			'EE_Admin'                                     => 'load_core',
844
+			'EE_CPT_Strategy'                              => 'load_core',
845
+			// load_class
846
+			'EE_Registration_Processor'                    => 'load_class',
847
+			// load_lib
848
+			'EE_Message_Resource_Manager'                  => 'load_lib',
849
+			'EE_Message_Type_Collection'                   => 'load_lib',
850
+			'EE_Message_Type_Collection_Loader'            => 'load_lib',
851
+			'EE_Messenger_Collection'                      => 'load_lib',
852
+			'EE_Messenger_Collection_Loader'               => 'load_lib',
853
+			'EE_Messages_Processor'                        => 'load_lib',
854
+			'EE_Message_Repository'                        => 'load_lib',
855
+			'EE_Messages_Queue'                            => 'load_lib',
856
+			'EE_Messages_Data_Handler_Collection'          => 'load_lib',
857
+			'EE_Message_Template_Group_Collection'         => 'load_lib',
858
+			'EE_Payment_Method_Manager'                    => 'load_lib',
859
+			'EE_DMS_Core_4_1_0'                            => 'load_dms',
860
+			'EE_DMS_Core_4_2_0'                            => 'load_dms',
861
+			'EE_DMS_Core_4_3_0'                            => 'load_dms',
862
+			'EE_DMS_Core_4_5_0'                            => 'load_dms',
863
+			'EE_DMS_Core_4_6_0'                            => 'load_dms',
864
+			'EE_DMS_Core_4_7_0'                            => 'load_dms',
865
+			'EE_DMS_Core_4_8_0'                            => 'load_dms',
866
+			'EE_DMS_Core_4_9_0'                            => 'load_dms',
867
+			'EE_DMS_Core_4_10_0'                           => 'load_dms',
868
+			'EE_DMS_Core_4_11_0'                           => 'load_dms',
869
+			'EE_DMS_Core_4_12_0'                           => 'load_dms',
870
+			'EE_Messages_Generator'                        => static function () {
871
+				return EE_Registry::instance()->load_lib(
872
+					'Messages_Generator',
873
+					[],
874
+					false,
875
+					false
876
+				);
877
+			},
878
+			'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
879
+				return EE_Registry::instance()->load_lib(
880
+					'Messages_Template_Defaults',
881
+					$arguments,
882
+					false,
883
+					false
884
+				);
885
+			},
886
+			// load_helper
887
+			'EEH_Parse_Shortcodes'                         => static function () {
888
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
889
+					return new EEH_Parse_Shortcodes();
890
+				}
891
+				return null;
892
+			},
893
+			'EE_Template_Config'                           => static function () {
894
+				return EE_Config::instance()->template_settings;
895
+			},
896
+			'EE_Currency_Config'                           => static function () {
897
+				return EE_Config::instance()->currency;
898
+			},
899
+			'EE_Registration_Config'                       => static function () {
900
+				return EE_Config::instance()->registration;
901
+			},
902
+			'EE_Core_Config'                               => static function () {
903
+				return EE_Config::instance()->core;
904
+			},
905
+			'EventEspresso\core\services\loaders\Loader'   => static function () {
906
+				return LoaderFactory::getLoader();
907
+			},
908
+			'EE_Network_Config'                            => static function () {
909
+				return EE_Network_Config::instance();
910
+			},
911
+			'EE_Config'                                    => static function () {
912
+				return EE_Config::instance();
913
+			},
914
+			'EventEspresso\core\domain\Domain'             => static function () {
915
+				return DomainFactory::getEventEspressoCoreDomain();
916
+			},
917
+			'EE_Admin_Config'                              => static function () {
918
+				return EE_Config::instance()->admin;
919
+			},
920
+			'EE_Organization_Config'                       => static function () {
921
+				return EE_Config::instance()->organization;
922
+			},
923
+			'EE_Network_Core_Config'                       => static function () {
924
+				return EE_Network_Config::instance()->core;
925
+			},
926
+			'EE_Environment_Config'                        => static function () {
927
+				return EE_Config::instance()->environment;
928
+			},
929
+			'EED_Core_Rest_Api'                            => static function () {
930
+				return EED_Core_Rest_Api::instance();
931
+			},
932
+			'WP_REST_Server'                               => static function () {
933
+				return rest_get_server();
934
+			},
935
+			'EventEspresso\core\Psr4Autoloader'            => static function () {
936
+				return EE_Psr4AutoloaderInit::psr4_loader();
937
+			},
938
+		];
939
+	}
940
+
941
+
942
+	/**
943
+	 * can be used for supplying alternate names for classes,
944
+	 * or for connecting interface names to instantiable classes
945
+	 *
946
+	 * @throws InvalidAliasException
947
+	 */
948
+	protected function _register_core_aliases()
949
+	{
950
+		$aliases = [
951
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
952
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
953
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
954
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
955
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
956
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
957
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
958
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
959
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
960
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
961
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
962
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
963
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
964
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
965
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
966
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
967
+			'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
968
+			'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
969
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
970
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
971
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
972
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
973
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
974
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
975
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
976
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
977
+			'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
978
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
979
+			'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
980
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
981
+			'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
982
+			'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
983
+			'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
984
+			'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
985
+			'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
986
+			'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
987
+			'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
988
+			'Registration_Processor'                                                       => 'EE_Registration_Processor',
989
+			'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
990
+		];
991
+		foreach ($aliases as $alias => $fqn) {
992
+			if (is_array($fqn)) {
993
+				foreach ($fqn as $class => $for_class) {
994
+					$this->class_cache->addAlias($class, $alias, $for_class);
995
+				}
996
+				continue;
997
+			}
998
+			$this->class_cache->addAlias($fqn, $alias);
999
+		}
1000
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1001
+			$this->class_cache->addAlias(
1002
+				'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1003
+				'EventEspresso\core\services\notices\NoticeConverterInterface'
1004
+			);
1005
+		}
1006
+	}
1007
+
1008
+
1009
+	/**
1010
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1011
+	 * request Primarily used by unit tests.
1012
+	 */
1013
+	public function reset()
1014
+	{
1015
+		$this->_register_core_class_loaders();
1016
+		$this->_register_core_dependencies();
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * PLZ NOTE: a better name for this method would be is_alias()
1022
+	 * because it returns TRUE if the provided fully qualified name IS an alias
1023
+	 * WHY?
1024
+	 * Because if a class is type hinting for a concretion,
1025
+	 * then why would we need to find another class to supply it?
1026
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1027
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1028
+	 * Don't go looking for some substitute.
1029
+	 * Whereas if a class is type hinting for an interface...
1030
+	 * then we need to find an actual class to use.
1031
+	 * So the interface IS the alias for some other FQN,
1032
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1033
+	 * represents some other class.
1034
+	 *
1035
+	 * @param string $fqn
1036
+	 * @param string $for_class
1037
+	 * @return bool
1038
+	 * @deprecated 4.9.62.p
1039
+	 */
1040
+	public function has_alias($fqn = '', $for_class = '')
1041
+	{
1042
+		return $this->isAlias($fqn, $for_class);
1043
+	}
1044
+
1045
+
1046
+	/**
1047
+	 * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1048
+	 * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1049
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
1050
+	 *  for example:
1051
+	 *      if the following two entries were added to the _aliases array:
1052
+	 *          array(
1053
+	 *              'interface_alias'           => 'some\namespace\interface'
1054
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
1055
+	 *          )
1056
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1057
+	 *      to load an instance of 'some\namespace\classname'
1058
+	 *
1059
+	 * @param string $alias
1060
+	 * @param string $for_class
1061
+	 * @return string
1062
+	 * @deprecated 4.9.62.p
1063
+	 */
1064
+	public function get_alias($alias = '', $for_class = '')
1065
+	{
1066
+		return $this->getFqnForAlias($alias, $for_class);
1067
+	}
1068 1068
 }
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -205,8 +205,8 @@  discard block
 block discarded – undo
205 205
     ) {
206 206
         $class      = trim($class, '\\');
207 207
         $registered = false;
208
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
209
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
208
+        if (empty(EE_Dependency_Map::$_instance->_dependency_map[$class])) {
209
+            EE_Dependency_Map::$_instance->_dependency_map[$class] = [];
210 210
         }
211 211
         // we need to make sure that any aliases used when registering a dependency
212 212
         // get resolved to the correct class name
@@ -214,10 +214,10 @@  discard block
 block discarded – undo
214 214
             $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
215 215
             if (
216 216
                 $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
217
-                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
217
+                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[$class][$alias])
218 218
             ) {
219
-                unset($dependencies[ $dependency ]);
220
-                $dependencies[ $alias ] = $load_source;
219
+                unset($dependencies[$dependency]);
220
+                $dependencies[$alias] = $load_source;
221 221
                 $registered             = true;
222 222
             }
223 223
         }
@@ -227,13 +227,13 @@  discard block
 block discarded – undo
227 227
         // ie: with A = B + C, entries in B take precedence over duplicate entries in C
228 228
         // Union is way faster than array_merge() but should be used with caution...
229 229
         // especially with numerically indexed arrays
230
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
230
+        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[$class];
231 231
         // now we need to ensure that the resulting dependencies
232 232
         // array only has the entries that are required for the class
233 233
         // so first count how many dependencies were originally registered for the class
234
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
234
+        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[$class]);
235 235
         // if that count is non-zero (meaning dependencies were already registered)
236
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
236
+        EE_Dependency_Map::$_instance->_dependency_map[$class] = $dependency_count
237 237
             // then truncate the  final array to match that count
238 238
             ? array_slice($dependencies, 0, $dependency_count)
239 239
             // otherwise just take the incoming array because nothing previously existed
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
      */
263 263
     public function registerClassLoader($class_name, $loader = 'load_core')
264 264
     {
265
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
265
+        if ( ! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
266 266
             throw new DomainException(
267 267
                 esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
268 268
             );
@@ -286,8 +286,8 @@  discard block
 block discarded – undo
286 286
             );
287 287
         }
288 288
         $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
289
-        if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
290
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
289
+        if ( ! isset(EE_Dependency_Map::$_instance->_class_loaders[$class_name])) {
290
+            EE_Dependency_Map::$_instance->_class_loaders[$class_name] = $loader;
291 291
             return true;
292 292
         }
293 293
         return false;
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
         if (strpos($class_name, 'EEM_') === 0) {
316 316
             $class_name = 'LEGACY_MODELS';
317 317
         }
318
-        return isset($this->_dependency_map[ $class_name ]);
318
+        return isset($this->_dependency_map[$class_name]);
319 319
     }
320 320
 
321 321
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
             $class_name = 'LEGACY_MODELS';
334 334
         }
335 335
         $dependency = $this->getFqnForAlias($dependency, $class_name);
336
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
336
+        return isset($this->_dependency_map[$class_name][$dependency]);
337 337
     }
338 338
 
339 339
 
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
         }
353 353
         $dependency = $this->getFqnForAlias($dependency);
354 354
         return $this->has_dependency_for_class($class_name, $dependency)
355
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
355
+            ? $this->_dependency_map[$class_name][$dependency]
356 356
             : EE_Dependency_Map::not_registered;
357 357
     }
358 358
 
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
             return 'load_core';
377 377
         }
378 378
         $class_name = $this->getFqnForAlias($class_name);
379
-        return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
379
+        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
380 380
     }
381 381
 
382 382
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
     {
817 817
         $this->_class_loaders = [
818 818
             // load_core
819
-            'EE_Dependency_Map'                            => function () {
819
+            'EE_Dependency_Map'                            => function() {
820 820
                 return $this;
821 821
             },
822 822
             'EE_Capabilities'                              => 'load_core',
@@ -824,13 +824,13 @@  discard block
 block discarded – undo
824 824
             'EE_Front_Controller'                          => 'load_core',
825 825
             'EE_Module_Request_Router'                     => 'load_core',
826 826
             'EE_Registry'                                  => 'load_core',
827
-            'EE_Request'                                   => function () {
827
+            'EE_Request'                                   => function() {
828 828
                 return $this->legacy_request;
829 829
             },
830
-            'EventEspresso\core\services\request\Request'  => function () {
830
+            'EventEspresso\core\services\request\Request'  => function() {
831 831
                 return $this->request;
832 832
             },
833
-            'EventEspresso\core\services\request\Response' => function () {
833
+            'EventEspresso\core\services\request\Response' => function() {
834 834
                 return $this->response;
835 835
             },
836 836
             'EE_Base'                                      => 'load_core',
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
             'EE_DMS_Core_4_10_0'                           => 'load_dms',
868 868
             'EE_DMS_Core_4_11_0'                           => 'load_dms',
869 869
             'EE_DMS_Core_4_12_0'                           => 'load_dms',
870
-            'EE_Messages_Generator'                        => static function () {
870
+            'EE_Messages_Generator'                        => static function() {
871 871
                 return EE_Registry::instance()->load_lib(
872 872
                     'Messages_Generator',
873 873
                     [],
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
                     false
876 876
                 );
877 877
             },
878
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
878
+            'EE_Messages_Template_Defaults'                => static function($arguments = []) {
879 879
                 return EE_Registry::instance()->load_lib(
880 880
                     'Messages_Template_Defaults',
881 881
                     $arguments,
@@ -884,55 +884,55 @@  discard block
 block discarded – undo
884 884
                 );
885 885
             },
886 886
             // load_helper
887
-            'EEH_Parse_Shortcodes'                         => static function () {
887
+            'EEH_Parse_Shortcodes'                         => static function() {
888 888
                 if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
889 889
                     return new EEH_Parse_Shortcodes();
890 890
                 }
891 891
                 return null;
892 892
             },
893
-            'EE_Template_Config'                           => static function () {
893
+            'EE_Template_Config'                           => static function() {
894 894
                 return EE_Config::instance()->template_settings;
895 895
             },
896
-            'EE_Currency_Config'                           => static function () {
896
+            'EE_Currency_Config'                           => static function() {
897 897
                 return EE_Config::instance()->currency;
898 898
             },
899
-            'EE_Registration_Config'                       => static function () {
899
+            'EE_Registration_Config'                       => static function() {
900 900
                 return EE_Config::instance()->registration;
901 901
             },
902
-            'EE_Core_Config'                               => static function () {
902
+            'EE_Core_Config'                               => static function() {
903 903
                 return EE_Config::instance()->core;
904 904
             },
905
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
905
+            'EventEspresso\core\services\loaders\Loader'   => static function() {
906 906
                 return LoaderFactory::getLoader();
907 907
             },
908
-            'EE_Network_Config'                            => static function () {
908
+            'EE_Network_Config'                            => static function() {
909 909
                 return EE_Network_Config::instance();
910 910
             },
911
-            'EE_Config'                                    => static function () {
911
+            'EE_Config'                                    => static function() {
912 912
                 return EE_Config::instance();
913 913
             },
914
-            'EventEspresso\core\domain\Domain'             => static function () {
914
+            'EventEspresso\core\domain\Domain'             => static function() {
915 915
                 return DomainFactory::getEventEspressoCoreDomain();
916 916
             },
917
-            'EE_Admin_Config'                              => static function () {
917
+            'EE_Admin_Config'                              => static function() {
918 918
                 return EE_Config::instance()->admin;
919 919
             },
920
-            'EE_Organization_Config'                       => static function () {
920
+            'EE_Organization_Config'                       => static function() {
921 921
                 return EE_Config::instance()->organization;
922 922
             },
923
-            'EE_Network_Core_Config'                       => static function () {
923
+            'EE_Network_Core_Config'                       => static function() {
924 924
                 return EE_Network_Config::instance()->core;
925 925
             },
926
-            'EE_Environment_Config'                        => static function () {
926
+            'EE_Environment_Config'                        => static function() {
927 927
                 return EE_Config::instance()->environment;
928 928
             },
929
-            'EED_Core_Rest_Api'                            => static function () {
929
+            'EED_Core_Rest_Api'                            => static function() {
930 930
                 return EED_Core_Rest_Api::instance();
931 931
             },
932
-            'WP_REST_Server'                               => static function () {
932
+            'WP_REST_Server'                               => static function() {
933 933
                 return rest_get_server();
934 934
             },
935
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
935
+            'EventEspresso\core\Psr4Autoloader'            => static function() {
936 936
                 return EE_Psr4AutoloaderInit::psr4_loader();
937 937
             },
938 938
         ];
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
             }
998 998
             $this->class_cache->addAlias($fqn, $alias);
999 999
         }
1000
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1000
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1001 1001
             $this->class_cache->addAlias(
1002 1002
                 'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1003 1003
                 'EventEspresso\core\services\notices\NoticeConverterInterface'
Please login to merge, or discard this patch.
core/db_models/EEM_Form_Section.model.php 2 patches
Indentation   +283 added lines, -283 removed lines patch added patch discarded remove patch
@@ -20,287 +20,287 @@
 block discarded – undo
20 20
  */
21 21
 class EEM_Form_Section extends EEM_Soft_Delete_Base
22 22
 {
23
-    const APPLIES_TO_ALL         = 'all';
24
-
25
-    const APPLIES_TO_PRIMARY     = 'primary';
26
-
27
-    const APPLIES_TO_PURCHASER   = 'purchaser';
28
-
29
-    const APPLIES_TO_REGISTRANTS = 'registrants';
30
-
31
-    const STATUS_ACTIVE          = 'active';
32
-
33
-    const STATUS_ARCHIVED        = 'archived';
34
-
35
-    const STATUS_DEFAULT         = 'default';
36
-
37
-    const STATUS_TRASHED         = 'trashed';
38
-
39
-    /**
40
-     * @var EEM_Form_Section
41
-     */
42
-    protected static $_instance;
43
-
44
-    /**
45
-     * @var RequestInterface
46
-     */
47
-    private $request;
48
-
49
-    /**
50
-     * @var array
51
-     */
52
-    private $valid_applies_to_options;
53
-
54
-    /**
55
-     * @var array
56
-     */
57
-    private $valid_status_options;
58
-
59
-
60
-    protected function __construct($timezone = null)
61
-    {
62
-        $this->valid_applies_to_options = apply_filters(
63
-            'FHEE__EEM_Form_Section__valid_applies_to_options',
64
-            [
65
-                EEM_Form_Section::APPLIES_TO_ALL         => esc_html__('All Registrants', 'event_espresso'),
66
-                EEM_Form_Section::APPLIES_TO_PRIMARY     => esc_html__('Primary Registrant Only', 'event_espresso'),
67
-                EEM_Form_Section::APPLIES_TO_PURCHASER   => esc_html__('Purchasing Agent', 'event_espresso'),
68
-                eem_form_section::APPLIES_TO_REGISTRANTS => esc_html__('Additional Registrants', 'event_espresso'),
69
-            ]
70
-        );
71
-        $this->valid_status_options     = apply_filters(
72
-            'FHEE__EEM_Form_Section__valid_status_options',
73
-            [
74
-                EEM_Form_Section::STATUS_ACTIVE   => esc_html__('Active', 'event_espresso'),
75
-                EEM_Form_Section::STATUS_ARCHIVED => esc_html__('Archived', 'event_espresso'),
76
-                EEM_Form_Section::STATUS_DEFAULT  => esc_html__('Default', 'event_espresso'),
77
-                eem_form_section::STATUS_TRASHED  => esc_html__('Trashed', 'event_espresso'),
78
-            ]
79
-        );
80
-
81
-        $related_entity_types = apply_filters(
82
-            'FHEE__EEM_Form_Section__related_entity_types',
83
-            [
84
-                'Datetime',
85
-                'Event',
86
-                'Form_Section',
87
-                'Ticket',
88
-                'Venue',
89
-            ]
90
-        );
91
-
92
-        $this->singular_item = esc_html__('Form Section', 'event_espresso');
93
-        $this->plural_item   = esc_html__('Form Sections', 'event_espresso');
94
-
95
-        $this->_tables          = [
96
-            'Form_Section' => new EE_Primary_Table('esp_form_section', 'FSC_ID'),
97
-        ];
98
-        $this->_fields          = [
99
-            'Form_Section' => [
100
-                'FSC_ID'        => new EE_Integer_Field(
101
-                    'FSC_ID',
102
-                    esc_html__('Form Section ID (autoincrement db id)', 'event_espresso'),
103
-                    false
104
-                ),
105
-                'FSC_UUID'      => new EE_Primary_Key_String_Field(
106
-                    'FSC_UUID',
107
-                    esc_html__('Form Section UUID (universally unique identifier)', 'event_espresso')
108
-                ),
109
-                'FSC_appliesTo' => new EE_Enum_Text_Field(
110
-                    'FSC_appliesTo',
111
-                    esc_html__(
112
-                        'Form user types that this form section should be presented to. Values correspond to the EEM_Form_Section::APPLIES_TO_* constants.',
113
-                        'event_espresso'
114
-                    ),
115
-                    false,
116
-                    EEM_Form_Section::APPLIES_TO_ALL,
117
-                    $this->valid_applies_to_options
118
-                ),
119
-                'FSC_belongsTo' => new EE_Foreign_Key_String_Field(
120
-                    'FSC_belongsTo',
121
-                    esc_html__('UUID or ID of related entity this form section belongs to.', 'event_espresso'),
122
-                    true,
123
-                    null,
124
-                    $related_entity_types
125
-                ),
126
-                'FSC_htmlClass' => new EE_Plain_Text_Field(
127
-                    'FSC_htmlClass',
128
-                    esc_html__('HTML classes to be applied to this form section\'s container.', 'event_espresso'),
129
-                    true,
130
-                    null
131
-                ),
132
-                'FSC_order'     => new EE_Integer_Field(
133
-                    'FSC_order',
134
-                    esc_html__('Order in which form section appears in a form.', 'event_espresso'),
135
-                    false,
136
-                    0
137
-                ),
138
-                'FSC_relation'  => new EE_Any_Foreign_Model_Name_Field(
139
-                    'FSC_relation',
140
-                    esc_html__('Related model type.', 'event_espresso'),
141
-                    true,
142
-                    null,
143
-                    $related_entity_types
144
-                ),
145
-                'FSC_status'    => new EE_Enum_Text_Field(
146
-                    'FSC_status',
147
-                    esc_html__(
148
-                        'Whether form section is active, archived, trashed, or used as a default on new forms. Values correspond to the EEM_Form_Section::STATUS_TO_* constants.',
149
-                        'event_espresso'
150
-                    ),
151
-                    false,
152
-                    EEM_Form_Section::STATUS_ACTIVE,
153
-                    $this->valid_status_options
154
-                ),
155
-                'FSC_wpUser'    => new EE_WP_User_Field(
156
-                    'FSC_wpUser',
157
-                    esc_html__('ID of the WP User that created this form section.', 'event_espresso'),
158
-                    false
159
-                ),
160
-            ],
161
-        ];
162
-        $this->_model_relations = [];
163
-        foreach ($related_entity_types as $model) {
164
-            $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
165
-        }
166
-        // this model is generally available for reading
167
-        $restrictions                              = [];
168
-        $restrictions[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Public();
169
-        $restrictions[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
170
-        $restrictions[ EEM_Base::caps_edit ]       = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
171
-        $restrictions[ EEM_Base::caps_delete ]     = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
172
-        $this->_cap_restriction_generators         = $restrictions;
173
-        parent::__construct($timezone);
174
-        $this->request = $this->getLoader()->getShared('EventEspresso\core\services\request\RequestInterface');
175
-    }
176
-
177
-
178
-    /**
179
-     * @param bool $constants_only
180
-     * @return array
181
-     */
182
-    public function validAppliesToOptions(bool $constants_only = false): array
183
-    {
184
-        return $constants_only
185
-            ? array_keys($this->valid_applies_to_options)
186
-            : $this->valid_applies_to_options;
187
-    }
188
-
189
-
190
-    /**
191
-     * @param bool $constants_only
192
-     * @return array
193
-     */
194
-    public function validStatusOptions(bool $constants_only = false): array
195
-    {
196
-        return $constants_only
197
-            ? array_keys($this->valid_status_options)
198
-            : $this->valid_status_options;
199
-    }
200
-
201
-
202
-    /**
203
-     * returns an array of Form Sections for the specified Form Section
204
-     *
205
-     * @param string $FSC_UUID
206
-     * @return EE_Form_Section[]
207
-     * @throws EE_Error
208
-     */
209
-    public function getFormSectionChildren(string $FSC_UUID): array
210
-    {
211
-        return $this->getFormSectionsFor('FormSection.FSC_UUID', $FSC_UUID);
212
-    }
213
-
214
-
215
-    /**
216
-     * returns an array of Form Sections for the specified Event
217
-     *
218
-     * @param string $EVT_ID
219
-     * @return EE_Form_Section[]
220
-     * @throws EE_Error
221
-     */
222
-    public function getFormSectionsForEvent(string $EVT_ID): array
223
-    {
224
-        return $this->getFormSectionsFor('Event.EVT_ID', $EVT_ID);
225
-    }
226
-
227
-
228
-    /**
229
-     * returns an array of Form Sections for the specified Datetime
230
-     *
231
-     * @param string $DTT_ID
232
-     * @return EE_Form_Section[]
233
-     * @throws EE_Error
234
-     */
235
-    public function getFormSectionsForDatetime(string $DTT_ID): array
236
-    {
237
-        return $this->getFormSectionsFor('Datetime.DTT_ID', $DTT_ID);
238
-    }
239
-
240
-
241
-    /**
242
-     * returns an array of Form Sections for the specified Ticket
243
-     *
244
-     * @param string $TKT_ID
245
-     * @return EE_Form_Section[]
246
-     * @throws EE_Error
247
-     */
248
-    public function getFormSectionsForTicket(string $TKT_ID): array
249
-    {
250
-        return $this->getFormSectionsFor('Ticket.TKT_ID', $TKT_ID);
251
-    }
252
-
253
-
254
-    /**
255
-     * returns an array of Form Sections for the specified Venue
256
-     *
257
-     * @param string $VNU_ID
258
-     * @return EE_Form_Section[]
259
-     * @throws EE_Error
260
-     */
261
-    public function getFormSectionsForVenue(string $VNU_ID): array
262
-    {
263
-        return $this->getFormSectionsFor('Venue.VNU_ID', $VNU_ID);
264
-    }
265
-
266
-
267
-    /**
268
-     * @return EE_Form_Section[]
269
-     * @throws EE_Error
270
-     */
271
-    private function getFormSectionsFor(string $relation, string $related_UUID): array
272
-    {
273
-        $where_params = [$relation => $related_UUID];
274
-        $query_params = $this->addDefaultWhereConditions([$where_params]);
275
-        $query_params = $this->addOrderByQueryParams($query_params);
276
-        return $this->get_all($query_params);
277
-    }
278
-
279
-
280
-    /**
281
-     * @param array $query_params
282
-     * @return array
283
-     */
284
-    private function addDefaultWhereConditions(array $query_params): array
285
-    {
286
-        // might need to add a way to identify GQL requests for admin domains
287
-        $admin_request                            = $this->request->isAdmin() || $this->request->isAdminAjax();
288
-        $query_params['default_where_conditions'] = $admin_request
289
-            ? EEM_Base::default_where_conditions_none
290
-            : EEM_Base::default_where_conditions_all;
291
-        return $query_params;
292
-    }
293
-
294
-
295
-    /**
296
-     * form sections should always be sorted in ascending order via the FSC_order field
297
-     *
298
-     * @param array $query_params
299
-     * @return array
300
-     */
301
-    private function addOrderByQueryParams(array $query_params): array
302
-    {
303
-        $query_params['order_by'] = ['FSC_order' => 'ASC'];
304
-        return $query_params;
305
-    }
23
+	const APPLIES_TO_ALL         = 'all';
24
+
25
+	const APPLIES_TO_PRIMARY     = 'primary';
26
+
27
+	const APPLIES_TO_PURCHASER   = 'purchaser';
28
+
29
+	const APPLIES_TO_REGISTRANTS = 'registrants';
30
+
31
+	const STATUS_ACTIVE          = 'active';
32
+
33
+	const STATUS_ARCHIVED        = 'archived';
34
+
35
+	const STATUS_DEFAULT         = 'default';
36
+
37
+	const STATUS_TRASHED         = 'trashed';
38
+
39
+	/**
40
+	 * @var EEM_Form_Section
41
+	 */
42
+	protected static $_instance;
43
+
44
+	/**
45
+	 * @var RequestInterface
46
+	 */
47
+	private $request;
48
+
49
+	/**
50
+	 * @var array
51
+	 */
52
+	private $valid_applies_to_options;
53
+
54
+	/**
55
+	 * @var array
56
+	 */
57
+	private $valid_status_options;
58
+
59
+
60
+	protected function __construct($timezone = null)
61
+	{
62
+		$this->valid_applies_to_options = apply_filters(
63
+			'FHEE__EEM_Form_Section__valid_applies_to_options',
64
+			[
65
+				EEM_Form_Section::APPLIES_TO_ALL         => esc_html__('All Registrants', 'event_espresso'),
66
+				EEM_Form_Section::APPLIES_TO_PRIMARY     => esc_html__('Primary Registrant Only', 'event_espresso'),
67
+				EEM_Form_Section::APPLIES_TO_PURCHASER   => esc_html__('Purchasing Agent', 'event_espresso'),
68
+				eem_form_section::APPLIES_TO_REGISTRANTS => esc_html__('Additional Registrants', 'event_espresso'),
69
+			]
70
+		);
71
+		$this->valid_status_options     = apply_filters(
72
+			'FHEE__EEM_Form_Section__valid_status_options',
73
+			[
74
+				EEM_Form_Section::STATUS_ACTIVE   => esc_html__('Active', 'event_espresso'),
75
+				EEM_Form_Section::STATUS_ARCHIVED => esc_html__('Archived', 'event_espresso'),
76
+				EEM_Form_Section::STATUS_DEFAULT  => esc_html__('Default', 'event_espresso'),
77
+				eem_form_section::STATUS_TRASHED  => esc_html__('Trashed', 'event_espresso'),
78
+			]
79
+		);
80
+
81
+		$related_entity_types = apply_filters(
82
+			'FHEE__EEM_Form_Section__related_entity_types',
83
+			[
84
+				'Datetime',
85
+				'Event',
86
+				'Form_Section',
87
+				'Ticket',
88
+				'Venue',
89
+			]
90
+		);
91
+
92
+		$this->singular_item = esc_html__('Form Section', 'event_espresso');
93
+		$this->plural_item   = esc_html__('Form Sections', 'event_espresso');
94
+
95
+		$this->_tables          = [
96
+			'Form_Section' => new EE_Primary_Table('esp_form_section', 'FSC_ID'),
97
+		];
98
+		$this->_fields          = [
99
+			'Form_Section' => [
100
+				'FSC_ID'        => new EE_Integer_Field(
101
+					'FSC_ID',
102
+					esc_html__('Form Section ID (autoincrement db id)', 'event_espresso'),
103
+					false
104
+				),
105
+				'FSC_UUID'      => new EE_Primary_Key_String_Field(
106
+					'FSC_UUID',
107
+					esc_html__('Form Section UUID (universally unique identifier)', 'event_espresso')
108
+				),
109
+				'FSC_appliesTo' => new EE_Enum_Text_Field(
110
+					'FSC_appliesTo',
111
+					esc_html__(
112
+						'Form user types that this form section should be presented to. Values correspond to the EEM_Form_Section::APPLIES_TO_* constants.',
113
+						'event_espresso'
114
+					),
115
+					false,
116
+					EEM_Form_Section::APPLIES_TO_ALL,
117
+					$this->valid_applies_to_options
118
+				),
119
+				'FSC_belongsTo' => new EE_Foreign_Key_String_Field(
120
+					'FSC_belongsTo',
121
+					esc_html__('UUID or ID of related entity this form section belongs to.', 'event_espresso'),
122
+					true,
123
+					null,
124
+					$related_entity_types
125
+				),
126
+				'FSC_htmlClass' => new EE_Plain_Text_Field(
127
+					'FSC_htmlClass',
128
+					esc_html__('HTML classes to be applied to this form section\'s container.', 'event_espresso'),
129
+					true,
130
+					null
131
+				),
132
+				'FSC_order'     => new EE_Integer_Field(
133
+					'FSC_order',
134
+					esc_html__('Order in which form section appears in a form.', 'event_espresso'),
135
+					false,
136
+					0
137
+				),
138
+				'FSC_relation'  => new EE_Any_Foreign_Model_Name_Field(
139
+					'FSC_relation',
140
+					esc_html__('Related model type.', 'event_espresso'),
141
+					true,
142
+					null,
143
+					$related_entity_types
144
+				),
145
+				'FSC_status'    => new EE_Enum_Text_Field(
146
+					'FSC_status',
147
+					esc_html__(
148
+						'Whether form section is active, archived, trashed, or used as a default on new forms. Values correspond to the EEM_Form_Section::STATUS_TO_* constants.',
149
+						'event_espresso'
150
+					),
151
+					false,
152
+					EEM_Form_Section::STATUS_ACTIVE,
153
+					$this->valid_status_options
154
+				),
155
+				'FSC_wpUser'    => new EE_WP_User_Field(
156
+					'FSC_wpUser',
157
+					esc_html__('ID of the WP User that created this form section.', 'event_espresso'),
158
+					false
159
+				),
160
+			],
161
+		];
162
+		$this->_model_relations = [];
163
+		foreach ($related_entity_types as $model) {
164
+			$this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
165
+		}
166
+		// this model is generally available for reading
167
+		$restrictions                              = [];
168
+		$restrictions[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Public();
169
+		$restrictions[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
170
+		$restrictions[ EEM_Base::caps_edit ]       = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
171
+		$restrictions[ EEM_Base::caps_delete ]     = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
172
+		$this->_cap_restriction_generators         = $restrictions;
173
+		parent::__construct($timezone);
174
+		$this->request = $this->getLoader()->getShared('EventEspresso\core\services\request\RequestInterface');
175
+	}
176
+
177
+
178
+	/**
179
+	 * @param bool $constants_only
180
+	 * @return array
181
+	 */
182
+	public function validAppliesToOptions(bool $constants_only = false): array
183
+	{
184
+		return $constants_only
185
+			? array_keys($this->valid_applies_to_options)
186
+			: $this->valid_applies_to_options;
187
+	}
188
+
189
+
190
+	/**
191
+	 * @param bool $constants_only
192
+	 * @return array
193
+	 */
194
+	public function validStatusOptions(bool $constants_only = false): array
195
+	{
196
+		return $constants_only
197
+			? array_keys($this->valid_status_options)
198
+			: $this->valid_status_options;
199
+	}
200
+
201
+
202
+	/**
203
+	 * returns an array of Form Sections for the specified Form Section
204
+	 *
205
+	 * @param string $FSC_UUID
206
+	 * @return EE_Form_Section[]
207
+	 * @throws EE_Error
208
+	 */
209
+	public function getFormSectionChildren(string $FSC_UUID): array
210
+	{
211
+		return $this->getFormSectionsFor('FormSection.FSC_UUID', $FSC_UUID);
212
+	}
213
+
214
+
215
+	/**
216
+	 * returns an array of Form Sections for the specified Event
217
+	 *
218
+	 * @param string $EVT_ID
219
+	 * @return EE_Form_Section[]
220
+	 * @throws EE_Error
221
+	 */
222
+	public function getFormSectionsForEvent(string $EVT_ID): array
223
+	{
224
+		return $this->getFormSectionsFor('Event.EVT_ID', $EVT_ID);
225
+	}
226
+
227
+
228
+	/**
229
+	 * returns an array of Form Sections for the specified Datetime
230
+	 *
231
+	 * @param string $DTT_ID
232
+	 * @return EE_Form_Section[]
233
+	 * @throws EE_Error
234
+	 */
235
+	public function getFormSectionsForDatetime(string $DTT_ID): array
236
+	{
237
+		return $this->getFormSectionsFor('Datetime.DTT_ID', $DTT_ID);
238
+	}
239
+
240
+
241
+	/**
242
+	 * returns an array of Form Sections for the specified Ticket
243
+	 *
244
+	 * @param string $TKT_ID
245
+	 * @return EE_Form_Section[]
246
+	 * @throws EE_Error
247
+	 */
248
+	public function getFormSectionsForTicket(string $TKT_ID): array
249
+	{
250
+		return $this->getFormSectionsFor('Ticket.TKT_ID', $TKT_ID);
251
+	}
252
+
253
+
254
+	/**
255
+	 * returns an array of Form Sections for the specified Venue
256
+	 *
257
+	 * @param string $VNU_ID
258
+	 * @return EE_Form_Section[]
259
+	 * @throws EE_Error
260
+	 */
261
+	public function getFormSectionsForVenue(string $VNU_ID): array
262
+	{
263
+		return $this->getFormSectionsFor('Venue.VNU_ID', $VNU_ID);
264
+	}
265
+
266
+
267
+	/**
268
+	 * @return EE_Form_Section[]
269
+	 * @throws EE_Error
270
+	 */
271
+	private function getFormSectionsFor(string $relation, string $related_UUID): array
272
+	{
273
+		$where_params = [$relation => $related_UUID];
274
+		$query_params = $this->addDefaultWhereConditions([$where_params]);
275
+		$query_params = $this->addOrderByQueryParams($query_params);
276
+		return $this->get_all($query_params);
277
+	}
278
+
279
+
280
+	/**
281
+	 * @param array $query_params
282
+	 * @return array
283
+	 */
284
+	private function addDefaultWhereConditions(array $query_params): array
285
+	{
286
+		// might need to add a way to identify GQL requests for admin domains
287
+		$admin_request                            = $this->request->isAdmin() || $this->request->isAdminAjax();
288
+		$query_params['default_where_conditions'] = $admin_request
289
+			? EEM_Base::default_where_conditions_none
290
+			: EEM_Base::default_where_conditions_all;
291
+		return $query_params;
292
+	}
293
+
294
+
295
+	/**
296
+	 * form sections should always be sorted in ascending order via the FSC_order field
297
+	 *
298
+	 * @param array $query_params
299
+	 * @return array
300
+	 */
301
+	private function addOrderByQueryParams(array $query_params): array
302
+	{
303
+		$query_params['order_by'] = ['FSC_order' => 'ASC'];
304
+		return $query_params;
305
+	}
306 306
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
                 eem_form_section::APPLIES_TO_REGISTRANTS => esc_html__('Additional Registrants', 'event_espresso'),
69 69
             ]
70 70
         );
71
-        $this->valid_status_options     = apply_filters(
71
+        $this->valid_status_options = apply_filters(
72 72
             'FHEE__EEM_Form_Section__valid_status_options',
73 73
             [
74 74
                 EEM_Form_Section::STATUS_ACTIVE   => esc_html__('Active', 'event_espresso'),
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
         ];
162 162
         $this->_model_relations = [];
163 163
         foreach ($related_entity_types as $model) {
164
-            $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
164
+            $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
165 165
         }
166 166
         // this model is generally available for reading
167 167
         $restrictions                              = [];
168
-        $restrictions[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Public();
169
-        $restrictions[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
170
-        $restrictions[ EEM_Base::caps_edit ]       = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
171
-        $restrictions[ EEM_Base::caps_delete ]     = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
168
+        $restrictions[EEM_Base::caps_read]       = new EE_Restriction_Generator_Public();
169
+        $restrictions[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
170
+        $restrictions[EEM_Base::caps_edit]       = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
171
+        $restrictions[EEM_Base::caps_delete]     = new EE_Restriction_Generator_Reg_Form('FSC_applies_to');
172 172
         $this->_cap_restriction_generators         = $restrictions;
173 173
         parent::__construct($timezone);
174 174
         $this->request = $this->getLoader()->getShared('EventEspresso\core\services\request\RequestInterface');
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -37,122 +37,122 @@
 block discarded – undo
37 37
  * @since           4.0
38 38
  */
39 39
 if (function_exists('espresso_version')) {
40
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
-        /**
42
-         *    espresso_duplicate_plugin_error
43
-         *    displays if more than one version of EE is activated at the same time
44
-         */
45
-        function espresso_duplicate_plugin_error()
46
-        {
47
-            ?>
40
+	if (! function_exists('espresso_duplicate_plugin_error')) {
41
+		/**
42
+		 *    espresso_duplicate_plugin_error
43
+		 *    displays if more than one version of EE is activated at the same time
44
+		 */
45
+		function espresso_duplicate_plugin_error()
46
+		{
47
+			?>
48 48
             <div class="error">
49 49
                 <p>
50 50
                     <?php
51
-                    echo esc_html__(
52
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
-                        'event_espresso'
54
-                    ); ?>
51
+					echo esc_html__(
52
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
+						'event_espresso'
54
+					); ?>
55 55
                 </p>
56 56
             </div>
57 57
             <?php
58
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
59
-        }
60
-    }
61
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
58
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
59
+		}
60
+	}
61
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62 62
 } else {
63
-    define('EE_MIN_PHP_VER_REQUIRED', '7.1.0');
64
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
-        /**
66
-         * espresso_minimum_php_version_error
67
-         *
68
-         * @return void
69
-         */
70
-        function espresso_minimum_php_version_error()
71
-        {
72
-            ?>
63
+	define('EE_MIN_PHP_VER_REQUIRED', '7.1.0');
64
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
+		/**
66
+		 * espresso_minimum_php_version_error
67
+		 *
68
+		 * @return void
69
+		 */
70
+		function espresso_minimum_php_version_error()
71
+		{
72
+			?>
73 73
             <div class="error">
74 74
                 <p>
75 75
                     <?php
76
-                    printf(
77
-                        esc_html__(
78
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
-                            'event_espresso'
80
-                        ),
81
-                        EE_MIN_PHP_VER_REQUIRED,
82
-                        PHP_VERSION,
83
-                        '<br/>',
84
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
-                    );
86
-                    ?>
76
+					printf(
77
+						esc_html__(
78
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
+							'event_espresso'
80
+						),
81
+						EE_MIN_PHP_VER_REQUIRED,
82
+						PHP_VERSION,
83
+						'<br/>',
84
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
+					);
86
+					?>
87 87
                 </p>
88 88
             </div>
89 89
             <?php
90
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
91
-        }
90
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
91
+		}
92 92
 
93
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
-    } else {
95
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.12.0.rc.001');
105
-        }
93
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
+	} else {
95
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.12.0.rc.001');
105
+		}
106 106
 
107
-        /**
108
-         * espresso_plugin_activation
109
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
110
-         */
111
-        function espresso_plugin_activation()
112
-        {
113
-            update_option('ee_espresso_activation', true);
107
+		/**
108
+		 * espresso_plugin_activation
109
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
110
+		 */
111
+		function espresso_plugin_activation()
112
+		{
113
+			update_option('ee_espresso_activation', true);
114 114
 
115
-            // Run WP GraphQL activation callback
116
-            if (! class_exists('WPGraphQL')) {
117
-                require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
118
-            }
119
-            graphql_activation_callback();
120
-        }
115
+			// Run WP GraphQL activation callback
116
+			if (! class_exists('WPGraphQL')) {
117
+				require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
118
+			}
119
+			graphql_activation_callback();
120
+		}
121 121
 
122
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
122
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
123 123
 
124
-        /**
125
-         * espresso_plugin_deactivation
126
-         */
127
-        function espresso_plugin_deactivation()
128
-        {
129
-            // Run WP GraphQL deactivation callback
130
-            if (! class_exists('WPGraphQL')) {
131
-                require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
132
-            }
133
-            graphql_deactivation_callback();
134
-        }
135
-        register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
124
+		/**
125
+		 * espresso_plugin_deactivation
126
+		 */
127
+		function espresso_plugin_deactivation()
128
+		{
129
+			// Run WP GraphQL deactivation callback
130
+			if (! class_exists('WPGraphQL')) {
131
+				require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
132
+			}
133
+			graphql_deactivation_callback();
134
+		}
135
+		register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
136 136
 
137
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
138
-        bootstrap_espresso();
139
-    }
137
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
138
+		bootstrap_espresso();
139
+	}
140 140
 }
141 141
 if (! function_exists('espresso_deactivate_plugin')) {
142
-    /**
143
-     *    deactivate_plugin
144
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
145
-     *
146
-     * @access public
147
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
148
-     * @return    void
149
-     */
150
-    function espresso_deactivate_plugin($plugin_basename = '')
151
-    {
152
-        if (! function_exists('deactivate_plugins')) {
153
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
154
-        }
155
-        unset($_GET['activate'], $_REQUEST['activate']);
156
-        deactivate_plugins($plugin_basename);
157
-    }
142
+	/**
143
+	 *    deactivate_plugin
144
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
145
+	 *
146
+	 * @access public
147
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
148
+	 * @return    void
149
+	 */
150
+	function espresso_deactivate_plugin($plugin_basename = '')
151
+	{
152
+		if (! function_exists('deactivate_plugins')) {
153
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
154
+		}
155
+		unset($_GET['activate'], $_REQUEST['activate']);
156
+		deactivate_plugins($plugin_basename);
157
+	}
158 158
 }
Please login to merge, or discard this patch.