Completed
Branch fix/kses-13 (4c4ad1)
by
unknown
24:21 queued 22:17
created
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6478 added lines, -6478 removed lines patch added patch discarded remove patch
@@ -36,6484 +36,6484 @@
 block discarded – undo
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38 38
 
39
-    /**
40
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
-     * They almost always WILL NOT, but it's not necessarily a requirement.
43
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
-     *
45
-     * @var boolean
46
-     */
47
-    private $_values_already_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we assume
51
-     * the data is just like form input that needs to have the model fields'
52
-     * prepare_for_set and prepare_for_use_in_db called on it
53
-     */
54
-    const not_prepared_by_model_object = 0;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we
58
-     * assume this value is coming from a model object and doesn't need to have
59
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
60
-     */
61
-    const prepared_by_model_object = 1;
62
-
63
-    /**
64
-     * when $_values_already_prepared_by_model_object equals this, we assume
65
-     * the values are already to be used in the database (ie no processing is done
66
-     * on them by the model's fields)
67
-     */
68
-    const prepared_for_use_in_db = 2;
69
-
70
-
71
-    protected $singular_item = 'Item';
72
-
73
-    protected $plural_item   = 'Items';
74
-
75
-    /**
76
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
-     */
78
-    protected $_tables;
79
-
80
-    /**
81
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
-     *
85
-     * @var \EE_Model_Field_Base[][] $_fields
86
-     */
87
-    protected $_fields;
88
-
89
-    /**
90
-     * array of different kinds of relations
91
-     *
92
-     * @var \EE_Model_Relation_Base[] $_model_relations
93
-     */
94
-    protected $_model_relations;
95
-
96
-    /**
97
-     * @var \EE_Index[] $_indexes
98
-     */
99
-    protected $_indexes = array();
100
-
101
-    /**
102
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
103
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
-     * by setting the same columns as used in these queries in the query yourself.
105
-     *
106
-     * @var EE_Default_Where_Conditions
107
-     */
108
-    protected $_default_where_conditions_strategy;
109
-
110
-    /**
111
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
-     * This is particularly useful when you want something between 'none' and 'default'
113
-     *
114
-     * @var EE_Default_Where_Conditions
115
-     */
116
-    protected $_minimum_where_conditions_strategy;
117
-
118
-    /**
119
-     * String describing how to find the "owner" of this model's objects.
120
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
-     * But when there isn't, this indicates which related model, or transiently-related model,
122
-     * has the foreign key to the wp_users table.
123
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
-     * related to events, and events have a foreign key to wp_users.
125
-     * On EEM_Transaction, this would be 'Transaction.Event'
126
-     *
127
-     * @var string
128
-     */
129
-    protected $_model_chain_to_wp_user = '';
130
-
131
-    /**
132
-     * String describing how to find the model with a password controlling access to this model. This property has the
133
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
-     * This value is the path of models to follow to arrive at the model with the password field.
135
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
-     * model with a password that should affect reading this on the front-end.
137
-     * Eg this is an empty string for the Event model because it has a password.
138
-     * This is null for the Registration model, because its event's password has no bearing on whether
139
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
-     * should hide tickets for datetimes for events that have a password set.
142
-     * @var string |null
143
-     */
144
-    protected $model_chain_to_password = null;
145
-
146
-    /**
147
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
-     * don't need it (particularly CPT models)
149
-     *
150
-     * @var bool
151
-     */
152
-    protected $_ignore_where_strategy = false;
153
-
154
-    /**
155
-     * String used in caps relating to this model. Eg, if the caps relating to this
156
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
-     *
158
-     * @var string. If null it hasn't been initialized yet. If false then we
159
-     * have indicated capabilities don't apply to this
160
-     */
161
-    protected $_caps_slug = null;
162
-
163
-    /**
164
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
-     * and next-level keys are capability names, and each's value is a
166
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
-     * they specify which context to use (ie, frontend, backend, edit or delete)
168
-     * and then each capability in the corresponding sub-array that they're missing
169
-     * adds the where conditions onto the query.
170
-     *
171
-     * @var array
172
-     */
173
-    protected $_cap_restrictions = array(
174
-        self::caps_read       => array(),
175
-        self::caps_read_admin => array(),
176
-        self::caps_edit       => array(),
177
-        self::caps_delete     => array(),
178
-    );
179
-
180
-    /**
181
-     * Array defining which cap restriction generators to use to create default
182
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
183
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
-     * automatically set this to false (not just null).
186
-     *
187
-     * @var EE_Restriction_Generator_Base[]
188
-     */
189
-    protected $_cap_restriction_generators = array();
190
-
191
-    /**
192
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
-     */
194
-    const caps_read       = 'read';
195
-
196
-    const caps_read_admin = 'read_admin';
197
-
198
-    const caps_edit       = 'edit';
199
-
200
-    const caps_delete     = 'delete';
201
-
202
-    /**
203
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
-     * maps to 'read' because when looking for relevant permissions we're going to use
206
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
207
-     *
208
-     * @var array
209
-     */
210
-    protected $_cap_contexts_to_cap_action_map = array(
211
-        self::caps_read       => 'read',
212
-        self::caps_read_admin => 'read',
213
-        self::caps_edit       => 'edit',
214
-        self::caps_delete     => 'delete',
215
-    );
216
-
217
-    /**
218
-     * Timezone
219
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
-     * EE_Datetime_Field data type will have access to it.
223
-     *
224
-     * @var string
225
-     */
226
-    protected $_timezone;
227
-
228
-
229
-    /**
230
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
-     * multisite.
232
-     *
233
-     * @var int
234
-     */
235
-    protected static $_model_query_blog_id;
236
-
237
-    /**
238
-     * A copy of _fields, except the array keys are the model names pointed to by
239
-     * the field
240
-     *
241
-     * @var EE_Model_Field_Base[]
242
-     */
243
-    private $_cache_foreign_key_to_fields = array();
244
-
245
-    /**
246
-     * Cached list of all the fields on the model, indexed by their name
247
-     *
248
-     * @var EE_Model_Field_Base[]
249
-     */
250
-    private $_cached_fields = null;
251
-
252
-    /**
253
-     * Cached list of all the fields on the model, except those that are
254
-     * marked as only pertinent to the database
255
-     *
256
-     * @var EE_Model_Field_Base[]
257
-     */
258
-    private $_cached_fields_non_db_only = null;
259
-
260
-    /**
261
-     * A cached reference to the primary key for quick lookup
262
-     *
263
-     * @var EE_Model_Field_Base
264
-     */
265
-    private $_primary_key_field = null;
266
-
267
-    /**
268
-     * Flag indicating whether this model has a primary key or not
269
-     *
270
-     * @var boolean
271
-     */
272
-    protected $_has_primary_key_field = null;
273
-
274
-    /**
275
-     * array in the format:  [ FK alias => full PK ]
276
-     * where keys are local column name aliases for foreign keys
277
-     * and values are the fully qualified column name for the primary key they represent
278
-     *  ex:
279
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
-     *
281
-     * @var array $foreign_key_aliases
282
-     */
283
-    protected $foreign_key_aliases = [];
284
-
285
-    /**
286
-     * Whether or not this model is based off a table in WP core only (CPTs should set
287
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
-     * This should be true for models that deal with data that should exist independent of EE.
289
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
291
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
293
-     * @var boolean
294
-     */
295
-    protected $_wp_core_model = false;
296
-
297
-    /**
298
-     * @var bool stores whether this model has a password field or not.
299
-     * null until initialized by hasPasswordField()
300
-     */
301
-    protected $has_password_field;
302
-
303
-    /**
304
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
-     */
306
-    protected $password_field;
307
-
308
-    /**
309
-     *    List of valid operators that can be used for querying.
310
-     * The keys are all operators we'll accept, the values are the real SQL
311
-     * operators used
312
-     *
313
-     * @var array
314
-     */
315
-    protected $_valid_operators = array(
316
-        '='           => '=',
317
-        '<='          => '<=',
318
-        '<'           => '<',
319
-        '>='          => '>=',
320
-        '>'           => '>',
321
-        '!='          => '!=',
322
-        'LIKE'        => 'LIKE',
323
-        'like'        => 'LIKE',
324
-        'NOT_LIKE'    => 'NOT LIKE',
325
-        'not_like'    => 'NOT LIKE',
326
-        'NOT LIKE'    => 'NOT LIKE',
327
-        'not like'    => 'NOT LIKE',
328
-        'IN'          => 'IN',
329
-        'in'          => 'IN',
330
-        'NOT_IN'      => 'NOT IN',
331
-        'not_in'      => 'NOT IN',
332
-        'NOT IN'      => 'NOT IN',
333
-        'not in'      => 'NOT IN',
334
-        'between'     => 'BETWEEN',
335
-        'BETWEEN'     => 'BETWEEN',
336
-        'IS_NOT_NULL' => 'IS NOT NULL',
337
-        'is_not_null' => 'IS NOT NULL',
338
-        'IS NOT NULL' => 'IS NOT NULL',
339
-        'is not null' => 'IS NOT NULL',
340
-        'IS_NULL'     => 'IS NULL',
341
-        'is_null'     => 'IS NULL',
342
-        'IS NULL'     => 'IS NULL',
343
-        'is null'     => 'IS NULL',
344
-        'REGEXP'      => 'REGEXP',
345
-        'regexp'      => 'REGEXP',
346
-        'NOT_REGEXP'  => 'NOT REGEXP',
347
-        'not_regexp'  => 'NOT REGEXP',
348
-        'NOT REGEXP'  => 'NOT REGEXP',
349
-        'not regexp'  => 'NOT REGEXP',
350
-    );
351
-
352
-    /**
353
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
-     *
355
-     * @var array
356
-     */
357
-    protected $_in_style_operators = array('IN', 'NOT IN');
358
-
359
-    /**
360
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
-     * '12-31-2012'"
362
-     *
363
-     * @var array
364
-     */
365
-    protected $_between_style_operators = array('BETWEEN');
366
-
367
-    /**
368
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
-     * @var array
370
-     */
371
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
-    /**
373
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
-     * on a join table.
375
-     *
376
-     * @var array
377
-     */
378
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
-
380
-    /**
381
-     * Allowed values for $query_params['order'] for ordering in queries
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
-
387
-    /**
388
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
390
-     *
391
-     * @var array
392
-     */
393
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
-
395
-    /**
396
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
398
-     *
399
-     * @var array
400
-     */
401
-    private $_allowed_query_params = array(
402
-        0,
403
-        'limit',
404
-        'order_by',
405
-        'group_by',
406
-        'having',
407
-        'force_join',
408
-        'order',
409
-        'on_join_limit',
410
-        'default_where_conditions',
411
-        'caps',
412
-        'extra_selects',
413
-        'exclude_protected',
414
-    );
415
-
416
-    /**
417
-     * All the data types that can be used in $wpdb->prepare statements.
418
-     *
419
-     * @var array
420
-     */
421
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
-
423
-    /**
424
-     * @var EE_Registry $EE
425
-     */
426
-    protected $EE = null;
427
-
428
-
429
-    /**
430
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
-     *
432
-     * @var int
433
-     */
434
-    protected $_show_next_x_db_queries = 0;
435
-
436
-    /**
437
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
-     * WHERE, GROUP_BY, etc.
440
-     *
441
-     * @var CustomSelects
442
-     */
443
-    protected $_custom_selections = array();
444
-
445
-    /**
446
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
-     * caches every model object we've fetched from the DB on this request
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_entity_map;
452
-
453
-    /**
454
-     * @var LoaderInterface $loader
455
-     */
456
-    protected static $loader;
457
-
458
-
459
-    /**
460
-     * constant used to show EEM_Base has not yet verified the db on this http request
461
-     */
462
-    const db_verified_none = 0;
463
-
464
-    /**
465
-     * constant used to show EEM_Base has verified the EE core db on this http request,
466
-     * but not the addons' dbs
467
-     */
468
-    const db_verified_core = 1;
469
-
470
-    /**
471
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
-     * the EE core db too)
473
-     */
474
-    const db_verified_addons = 2;
475
-
476
-    /**
477
-     * indicates whether an EEM_Base child has already re-verified the DB
478
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
479
-     * looking like EEM_Base::db_verified_*
480
-     *
481
-     * @var int - 0 = none, 1 = core, 2 = addons
482
-     */
483
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
484
-
485
-    /**
486
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
-     *        registrations for non-trashed tickets for non-trashed datetimes)
489
-     */
490
-    const default_where_conditions_all = 'all';
491
-
492
-    /**
493
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
-     *        models which share tables with other models, this can return data for the wrong model.
498
-     */
499
-    const default_where_conditions_this_only = 'this_model_only';
500
-
501
-    /**
502
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
-     */
506
-    const default_where_conditions_others_only = 'other_models_only';
507
-
508
-    /**
509
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
512
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
-     *        (regardless of whether those events and venues are trashed)
514
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
-     *        events.
516
-     */
517
-    const default_where_conditions_minimum_all = 'minimum';
518
-
519
-    /**
520
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
-     *        not)
524
-     */
525
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
-
527
-    /**
528
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
-     *        it's possible it will return table entries for other models. You should use
531
-     *        EEM_Base::default_where_conditions_minimum_all instead.
532
-     */
533
-    const default_where_conditions_none = 'none';
534
-
535
-
536
-
537
-    /**
538
-     * About all child constructors:
539
-     * they should define the _tables, _fields and _model_relations arrays.
540
-     * Should ALWAYS be called after child constructor.
541
-     * In order to make the child constructors to be as simple as possible, this parent constructor
542
-     * finalizes constructing all the object's attributes.
543
-     * Generally, rather than requiring a child to code
544
-     * $this->_tables = array(
545
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
-     *        ...);
547
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
-     * each EE_Table has a function to set the table's alias after the constructor, using
549
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
-     * do something similar.
551
-     *
552
-     * @param null $timezone
553
-     * @throws EE_Error
554
-     */
555
-    protected function __construct($timezone = null)
556
-    {
557
-        // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
-            throw new EE_Error(
560
-                sprintf(
561
-                    esc_html__(
562
-                        '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.',
563
-                        'event_espresso'
564
-                    ),
565
-                    get_class($this)
566
-                )
567
-            );
568
-        }
569
-        /**
570
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
-         */
572
-        if (empty(EEM_Base::$_model_query_blog_id)) {
573
-            EEM_Base::set_model_query_blog_id();
574
-        }
575
-        /**
576
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
-         * just use EE_Register_Model_Extension
578
-         *
579
-         * @var EE_Table_Base[] $_tables
580
-         */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
-        foreach ($this->_tables as $table_alias => $table_obj) {
583
-            /** @var $table_obj EE_Table_Base */
584
-            $table_obj->_construct_finalize_with_alias($table_alias);
585
-            if ($table_obj instanceof EE_Secondary_Table) {
586
-                /** @var $table_obj EE_Secondary_Table */
587
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
-            }
589
-        }
590
-        /**
591
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
-         * EE_Register_Model_Extension
593
-         *
594
-         * @param EE_Model_Field_Base[] $_fields
595
-         */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
-        $this->_invalidate_field_caches();
598
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
600
-                throw new EE_Error(sprintf(esc_html__(
601
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
-                    'event_espresso'
603
-                ), $table_alias, implode(",", $this->_fields)));
604
-            }
605
-            foreach ($fields_for_table as $field_name => $field_obj) {
606
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
-                // primary key field base has a slightly different _construct_finalize
608
-                /** @var $field_obj EE_Model_Field_Base */
609
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
-            }
611
-        }
612
-        // everything is related to Extra_Meta
613
-        if (get_class($this) !== 'EEM_Extra_Meta') {
614
-            // make extra meta related to everything, but don't block deleting things just
615
-            // because they have related extra meta info. For now just orphan those extra meta
616
-            // in the future we should automatically delete them
617
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
-        }
619
-        // and change logs
620
-        if (get_class($this) !== 'EEM_Change_Log') {
621
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
-        }
623
-        /**
624
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
-         * EE_Register_Model_Extension
626
-         *
627
-         * @param EE_Model_Relation_Base[] $_model_relations
628
-         */
629
-        $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
631
-            $this->_model_relations
632
-        );
633
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
634
-            /** @var $relation_obj EE_Model_Relation_Base */
635
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
-        }
637
-        foreach ($this->_indexes as $index_name => $index_obj) {
638
-            /** @var $index_obj EE_Index */
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 ($this->_cap_restriction_generators !== false) {
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 ($this->_cap_restriction_generators !== false) {
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
-                            esc_html__(
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
-                EEM_Base::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
-                EEM_Base::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
-    private static function getLoader()
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
-                            esc_html__(
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
-                    esc_html__('$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(esc_html__(
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(esc_html__('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
-                    esc_html__('$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(esc_html__(
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
-                    esc_html__('$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
-                    esc_html__(
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
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
-            }
2181
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
-            $ways_to_identify_a_row = array();
2184
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
-                $values_for_each_combined_primary_key_for_a_row = array();
2186
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
-                }
2189
-                $ways_to_identify_a_row[] = '('
2190
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
-                                            . ')';
2192
-            }
2193
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2194
-        }
2195
-        return $query_part;
2196
-    }
2197
-
2198
-
2199
-
2200
-    /**
2201
-     * Gets the model field by the fully qualified name
2202
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
-     * @return EE_Model_Field_Base
2204
-     */
2205
-    public function get_field_by_column($qualified_column_name)
2206
-    {
2207
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
-                return $field_obj;
2210
-            }
2211
-        }
2212
-        throw new EE_Error(
2213
-            sprintf(
2214
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
-                $this->get_this_model_name(),
2216
-                $qualified_column_name
2217
-            )
2218
-        );
2219
-    }
2220
-
2221
-
2222
-
2223
-    /**
2224
-     * Count all the rows that match criteria the model query params.
2225
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
-     * column
2227
-     *
2228
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
-     * @param string $field_to_count field on model to count by (not column name)
2230
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
-     *                               that by the setting $distinct to TRUE;
2232
-     * @return int
2233
-     * @throws EE_Error
2234
-     */
2235
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
-    {
2237
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
-        if ($field_to_count) {
2239
-            $field_obj = $this->field_settings_for($field_to_count);
2240
-            $column_to_count = $field_obj->get_qualified_column();
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $pk_field_obj = $this->get_primary_key_field();
2243
-            $column_to_count = $pk_field_obj->get_qualified_column();
2244
-        } else {
2245
-            // there's no primary key
2246
-            // if we're counting distinct items, and there's no primary key,
2247
-            // we need to list out the columns for distinction;
2248
-            // otherwise we can just use star
2249
-            if ($distinct) {
2250
-                $columns_to_use = array();
2251
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2253
-                }
2254
-                $column_to_count = implode(',', $columns_to_use);
2255
-            } else {
2256
-                $column_to_count = '*';
2257
-            }
2258
-        }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
-    }
2263
-
2264
-
2265
-
2266
-    /**
2267
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
-     *
2269
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
-     * @param string $field_to_sum name of field (array key in $_fields array)
2271
-     * @return float
2272
-     * @throws EE_Error
2273
-     */
2274
-    public function sum($query_params, $field_to_sum = null)
2275
-    {
2276
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
-        if ($field_to_sum) {
2278
-            $field_obj = $this->field_settings_for($field_to_sum);
2279
-        } else {
2280
-            $field_obj = $this->get_primary_key_field();
2281
-        }
2282
-        $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
-        $data_type = $field_obj->get_wpdb_data_type();
2286
-        if ($data_type === '%d' || $data_type === '%s') {
2287
-            return (float) $return_value;
2288
-        }
2289
-        // must be %f
2290
-        return (float) $return_value;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Just calls the specified method on $wpdb with the given arguments
2297
-     * Consolidates a little extra error handling code
2298
-     *
2299
-     * @param string $wpdb_method
2300
-     * @param array  $arguments_to_provide
2301
-     * @throws EE_Error
2302
-     * @global wpdb  $wpdb
2303
-     * @return mixed
2304
-     */
2305
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
-    {
2307
-        // if we're in maintenance mode level 2, DON'T run any queries
2308
-        // because level 2 indicates the database needs updating and
2309
-        // is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
-            throw new EE_Error(sprintf(esc_html__(
2312
-                "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.",
2313
-                "event_espresso"
2314
-            )));
2315
-        }
2316
-        /** @type WPDB $wpdb */
2317
-        global $wpdb;
2318
-        if (! method_exists($wpdb, $wpdb_method)) {
2319
-            throw new EE_Error(sprintf(esc_html__(
2320
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2321
-                'event_espresso'
2322
-            ), $wpdb_method));
2323
-        }
2324
-        if (WP_DEBUG) {
2325
-            $old_show_errors_value = $wpdb->show_errors;
2326
-            $wpdb->show_errors(false);
2327
-        }
2328
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2330
-        if (WP_DEBUG) {
2331
-            $wpdb->show_errors($old_show_errors_value);
2332
-            if (! empty($wpdb->last_error)) {
2333
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
-            }
2335
-            if ($result === false) {
2336
-                throw new EE_Error(sprintf(esc_html__(
2337
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
-                    'event_espresso'
2339
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2340
-            }
2341
-        } elseif ($result === false) {
2342
-            EE_Error::add_error(
2343
-                sprintf(
2344
-                    esc_html__(
2345
-                        '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"',
2346
-                        'event_espresso'
2347
-                    ),
2348
-                    $wpdb_method,
2349
-                    var_export($arguments_to_provide, true),
2350
-                    $wpdb->last_error
2351
-                ),
2352
-                __FILE__,
2353
-                __FUNCTION__,
2354
-                __LINE__
2355
-            );
2356
-        }
2357
-        return $result;
2358
-    }
2359
-
2360
-
2361
-
2362
-    /**
2363
-     * Attempts to run the indicated WPDB method with the provided arguments,
2364
-     * and if there's an error tries to verify the DB is correct. Uses
2365
-     * the static property EEM_Base::$_db_verification_level to determine whether
2366
-     * we should try to fix the EE core db, the addons, or just give up
2367
-     *
2368
-     * @param string $wpdb_method
2369
-     * @param array  $arguments_to_provide
2370
-     * @return mixed
2371
-     */
2372
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        /** @type WPDB $wpdb */
2375
-        global $wpdb;
2376
-        $wpdb->last_error = null;
2377
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
-        // was there an error running the query? but we don't care on new activations
2379
-        // (we're going to setup the DB anyway on new activations)
2380
-        if (
2381
-            ($result === false || ! empty($wpdb->last_error))
2382
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
-        ) {
2384
-            switch (EEM_Base::$_db_verification_level) {
2385
-                case EEM_Base::db_verified_none:
2386
-                    // let's double-check core's DB
2387
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
-                    break;
2389
-                case EEM_Base::db_verified_core:
2390
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
-                    break;
2393
-                case EEM_Base::db_verified_addons:
2394
-                    // ummmm... you in trouble
2395
-                    return $result;
2396
-                    break;
2397
-            }
2398
-            if (! empty($error_message)) {
2399
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
-                trigger_error($error_message);
2401
-            }
2402
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
-        }
2404
-        return $result;
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Verifies the EE core database is up-to-date and records that we've done it on
2411
-     * EEM_Base::$_db_verification_level
2412
-     *
2413
-     * @param string $wpdb_method
2414
-     * @param array  $arguments_to_provide
2415
-     * @return string
2416
-     */
2417
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
-    {
2419
-        /** @type WPDB $wpdb */
2420
-        global $wpdb;
2421
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2422
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
-        $error_message = sprintf(
2424
-            esc_html__(
2425
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
-                'event_espresso'
2427
-            ),
2428
-            $wpdb->last_error,
2429
-            $wpdb_method,
2430
-            wp_json_encode($arguments_to_provide)
2431
-        );
2432
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
-        return $error_message;
2434
-    }
2435
-
2436
-
2437
-
2438
-    /**
2439
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
-     * EEM_Base::$_db_verification_level
2441
-     *
2442
-     * @param $wpdb_method
2443
-     * @param $arguments_to_provide
2444
-     * @return string
2445
-     */
2446
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
-    {
2448
-        /** @type WPDB $wpdb */
2449
-        global $wpdb;
2450
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
-        $error_message = sprintf(
2453
-            esc_html__(
2454
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
-                'event_espresso'
2456
-            ),
2457
-            $wpdb->last_error,
2458
-            $wpdb_method,
2459
-            wp_json_encode($arguments_to_provide)
2460
-        );
2461
-        EE_System::instance()->initialize_addons();
2462
-        return $error_message;
2463
-    }
2464
-
2465
-
2466
-
2467
-    /**
2468
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
-     * ..."
2472
-     *
2473
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2474
-     * @return string
2475
-     */
2476
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
-    {
2478
-        return " FROM " . $model_query_info->get_full_join_sql() .
2479
-               $model_query_info->get_where_sql() .
2480
-               $model_query_info->get_group_by_sql() .
2481
-               $model_query_info->get_having_sql() .
2482
-               $model_query_info->get_order_by_sql() .
2483
-               $model_query_info->get_limit_sql();
2484
-    }
2485
-
2486
-
2487
-
2488
-    /**
2489
-     * Set to easily debug the next X queries ran from this model.
2490
-     *
2491
-     * @param int $count
2492
-     */
2493
-    public function show_next_x_db_queries($count = 1)
2494
-    {
2495
-        $this->_show_next_x_db_queries = $count;
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * @param $sql_query
2502
-     */
2503
-    public function show_db_query_if_previously_requested($sql_query)
2504
-    {
2505
-        if ($this->_show_next_x_db_queries > 0) {
2506
-            echo esc_html($sql_query);
2507
-            $this->_show_next_x_db_queries--;
2508
-        }
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
-     * There are the 3 cases:
2516
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
-     * $otherModelObject has no ID, it is first saved.
2518
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
-     * has no ID, it is first saved.
2520
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
-     * join table
2523
-     *
2524
-     * @param        EE_Base_Class                     /int $thisModelObject
2525
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
-     * @param string $relationName                     , key in EEM_Base::_relations
2527
-     *                                                 an attendee to a group, you also want to specify which role they
2528
-     *                                                 will have in that group. So you would use this parameter to
2529
-     *                                                 specify array('role-column-name'=>'role-id')
2530
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
-     *                                                 to for relation to methods that allow you to further specify
2532
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
-     *                                                 because these will be inserted in any new rows created as well.
2535
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
-     * @throws EE_Error
2537
-     */
2538
-    public function add_relationship_to(
2539
-        $id_or_obj,
2540
-        $other_model_id_or_obj,
2541
-        $relationName,
2542
-        $extra_join_model_fields_n_values = array()
2543
-    ) {
2544
-        $relation_obj = $this->related_settings_for($relationName);
2545
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
-    }
2547
-
2548
-
2549
-
2550
-    /**
2551
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
-     * There are the 3 cases:
2553
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
-     * error
2555
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
-     * an error
2557
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
-     *
2559
-     * @param        EE_Base_Class /int $id_or_obj
2560
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
-     * @param string $relationName key in EEM_Base::_relations
2562
-     * @return boolean of success
2563
-     * @throws EE_Error
2564
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
-     *                             because these will be inserted in any new rows created as well.
2568
-     */
2569
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
-    {
2571
-        $relation_obj = $this->related_settings_for($relationName);
2572
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
-    }
2574
-
2575
-
2576
-
2577
-    /**
2578
-     * @param mixed           $id_or_obj
2579
-     * @param string          $relationName
2580
-     * @param array           $where_query_params
2581
-     * @param EE_Base_Class[] objects to which relations were removed
2582
-     * @return \EE_Base_Class[]
2583
-     * @throws EE_Error
2584
-     */
2585
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
-    {
2587
-        $relation_obj = $this->related_settings_for($relationName);
2588
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
-    }
2590
-
2591
-
2592
-
2593
-    /**
2594
-     * Gets all the related items of the specified $model_name, using $query_params.
2595
-     * Note: by default, we remove the "default query params"
2596
-     * because we want to get even deleted items etc.
2597
-     *
2598
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
-     * @return EE_Base_Class[]
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
-    {
2606
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2607
-        $relation_settings = $this->related_settings_for($model_name);
2608
-        return $relation_settings->get_all_related($model_obj, $query_params);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Deletes all the model objects across the relation indicated by $model_name
2615
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2617
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
-     *
2619
-     * @param EE_Base_Class|int|string $id_or_obj
2620
-     * @param string                   $model_name
2621
-     * @param array                    $query_params
2622
-     * @return int how many deleted
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
-    {
2627
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2628
-        $relation_settings = $this->related_settings_for($model_name);
2629
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2630
-    }
2631
-
2632
-
2633
-
2634
-    /**
2635
-     * Hard deletes all the model objects across the relation indicated by $model_name
2636
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
-     * the model objects can't be hard deleted because of blocking related model objects,
2638
-     * just does a soft-delete on them instead.
2639
-     *
2640
-     * @param EE_Base_Class|int|string $id_or_obj
2641
-     * @param string                   $model_name
2642
-     * @param array                    $query_params
2643
-     * @return int how many deleted
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
-    {
2648
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2649
-        $relation_settings = $this->related_settings_for($model_name);
2650
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
-    }
2652
-
2653
-
2654
-
2655
-    /**
2656
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
-     * unless otherwise specified in the $query_params
2658
-     *
2659
-     * @param        int             /EE_Base_Class $id_or_obj
2660
-     * @param string $model_name     like 'Event', or 'Registration'
2661
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2663
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
-     *                               that by the setting $distinct to TRUE;
2665
-     * @return int
2666
-     * @throws EE_Error
2667
-     */
2668
-    public function count_related(
2669
-        $id_or_obj,
2670
-        $model_name,
2671
-        $query_params = array(),
2672
-        $field_to_count = null,
2673
-        $distinct = false
2674
-    ) {
2675
-        $related_model = $this->get_related_model_obj($model_name);
2676
-        // we're just going to use the query params on the related model's normal get_all query,
2677
-        // except add a condition to say to match the current mod
2678
-        if (! isset($query_params['default_where_conditions'])) {
2679
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
-        }
2681
-        $this_model_name = $this->get_this_model_name();
2682
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
-        return $related_model->count($query_params, $field_to_count, $distinct);
2685
-    }
2686
-
2687
-
2688
-
2689
-    /**
2690
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
-     *
2693
-     * @param        int           /EE_Base_Class $id_or_obj
2694
-     * @param string $model_name   like 'Event', or 'Registration'
2695
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
-     * @return float
2698
-     * @throws EE_Error
2699
-     */
2700
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
-    {
2702
-        $related_model = $this->get_related_model_obj($model_name);
2703
-        if (! is_array($query_params)) {
2704
-            EE_Error::doing_it_wrong(
2705
-                'EEM_Base::sum_related',
2706
-                sprintf(
2707
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
-                    gettype($query_params)
2709
-                ),
2710
-                '4.6.0'
2711
-            );
2712
-            $query_params = array();
2713
-        }
2714
-        // we're just going to use the query params on the related model's normal get_all query,
2715
-        // except add a condition to say to match the current mod
2716
-        if (! isset($query_params['default_where_conditions'])) {
2717
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
-        }
2719
-        $this_model_name = $this->get_this_model_name();
2720
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
-        return $related_model->sum($query_params, $field_to_sum);
2723
-    }
2724
-
2725
-
2726
-
2727
-    /**
2728
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
-     * $modelObject
2730
-     *
2731
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
-     * @return EE_Base_Class
2735
-     * @throws EE_Error
2736
-     */
2737
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
-    {
2739
-        $query_params['limit'] = 1;
2740
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
-        if ($results) {
2742
-            return array_shift($results);
2743
-        }
2744
-        return null;
2745
-    }
2746
-
2747
-
2748
-
2749
-    /**
2750
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
-     *
2752
-     * @return string
2753
-     */
2754
-    public function get_this_model_name()
2755
-    {
2756
-        return str_replace("EEM_", "", get_class($this));
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
-     *
2764
-     * @return EE_Any_Foreign_Model_Name_Field
2765
-     * @throws EE_Error
2766
-     */
2767
-    public function get_field_containing_related_model_name()
2768
-    {
2769
-        foreach ($this->field_settings(true) as $field) {
2770
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
-                $field_with_model_name = $field;
2772
-            }
2773
-        }
2774
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
-            throw new EE_Error(sprintf(
2776
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
-                $this->get_this_model_name()
2778
-            ));
2779
-        }
2780
-        return $field_with_model_name;
2781
-    }
2782
-
2783
-
2784
-
2785
-    /**
2786
-     * Inserts a new entry into the database, for each table.
2787
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
-     *
2794
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
-     *                              of EEM_Base)
2798
-     * @return int|string new primary key on main table that got inserted
2799
-     * @throws EE_Error
2800
-     */
2801
-    public function insert($field_n_values)
2802
-    {
2803
-        /**
2804
-         * Filters the fields and their values before inserting an item using the models
2805
-         *
2806
-         * @param array    $fields_n_values keys are the fields and values are their new values
2807
-         * @param EEM_Base $model           the model used
2808
-         */
2809
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
-            $main_table = $this->_get_main_table();
2812
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
-            if ($new_id !== false) {
2814
-                foreach ($this->_get_other_tables() as $other_table) {
2815
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
-                }
2817
-            }
2818
-            /**
2819
-             * Done just after attempting to insert a new model object
2820
-             *
2821
-             * @param EEM_Base   $model           used
2822
-             * @param array      $fields_n_values fields and their values
2823
-             * @param int|string the              ID of the newly-inserted model object
2824
-             */
2825
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
-            return $new_id;
2827
-        }
2828
-        return false;
2829
-    }
2830
-
2831
-
2832
-
2833
-    /**
2834
-     * Checks that the result would satisfy the unique indexes on this model
2835
-     *
2836
-     * @param array  $field_n_values
2837
-     * @param string $action
2838
-     * @return boolean
2839
-     * @throws EE_Error
2840
-     */
2841
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
-    {
2843
-        foreach ($this->unique_indexes() as $index_name => $index) {
2844
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
-            if ($this->exists(array($uniqueness_where_params))) {
2846
-                EE_Error::add_error(
2847
-                    sprintf(
2848
-                        esc_html__(
2849
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
-                            "event_espresso"
2851
-                        ),
2852
-                        $action,
2853
-                        $this->_get_class_name(),
2854
-                        $index_name,
2855
-                        implode(",", $index->field_names()),
2856
-                        http_build_query($uniqueness_where_params)
2857
-                    ),
2858
-                    __FILE__,
2859
-                    __FUNCTION__,
2860
-                    __LINE__
2861
-                );
2862
-                return false;
2863
-            }
2864
-        }
2865
-        return true;
2866
-    }
2867
-
2868
-
2869
-
2870
-    /**
2871
-     * Checks the database for an item that conflicts (ie, if this item were
2872
-     * saved to the DB would break some uniqueness requirement, like a primary key
2873
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
-     * can be either an EE_Base_Class or an array of fields n values
2875
-     *
2876
-     * @param EE_Base_Class|array $obj_or_fields_array
2877
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2878
-     *                                                 when looking for conflicts
2879
-     *                                                 (ie, if false, we ignore the model object's primary key
2880
-     *                                                 when finding "conflicts". If true, it's also considered).
2881
-     *                                                 Only works for INT primary key,
2882
-     *                                                 STRING primary keys cannot be ignored
2883
-     * @throws EE_Error
2884
-     * @return EE_Base_Class|array
2885
-     */
2886
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
-    {
2888
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2890
-        } elseif (is_array($obj_or_fields_array)) {
2891
-            $fields_n_values = $obj_or_fields_array;
2892
-        } else {
2893
-            throw new EE_Error(
2894
-                sprintf(
2895
-                    esc_html__(
2896
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
-                        "event_espresso"
2898
-                    ),
2899
-                    get_class($this),
2900
-                    $obj_or_fields_array
2901
-                )
2902
-            );
2903
-        }
2904
-        $query_params = array();
2905
-        if (
2906
-            $this->has_primary_key_field()
2907
-            && ($include_primary_key
2908
-                || $this->get_primary_key_field()
2909
-                   instanceof
2910
-                   EE_Primary_Key_String_Field)
2911
-            && isset($fields_n_values[ $this->primary_key_name() ])
2912
-        ) {
2913
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
-        }
2915
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
-        }
2919
-        // if there is nothing to base this search on, then we shouldn't find anything
2920
-        if (empty($query_params)) {
2921
-            return array();
2922
-        }
2923
-        return $this->get_one($query_params);
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Like count, but is optimized and returns a boolean instead of an int
2930
-     *
2931
-     * @param array $query_params
2932
-     * @return boolean
2933
-     * @throws EE_Error
2934
-     */
2935
-    public function exists($query_params)
2936
-    {
2937
-        $query_params['limit'] = 1;
2938
-        return $this->count($query_params) > 0;
2939
-    }
2940
-
2941
-
2942
-
2943
-    /**
2944
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
-     *
2946
-     * @param int|string $id
2947
-     * @return boolean
2948
-     * @throws EE_Error
2949
-     */
2950
-    public function exists_by_ID($id)
2951
-    {
2952
-        return $this->exists(
2953
-            array(
2954
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
-                array(
2956
-                    $this->primary_key_name() => $id,
2957
-                ),
2958
-            )
2959
-        );
2960
-    }
2961
-
2962
-
2963
-
2964
-    /**
2965
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
-     * on the main table)
2969
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
-     * cases where we want to call it directly rather than via insert().
2971
-     *
2972
-     * @access   protected
2973
-     * @param EE_Table_Base $table
2974
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
-     *                                       float
2976
-     * @param int           $new_id          for now we assume only int keys
2977
-     * @throws EE_Error
2978
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
-     * @return int ID of new row inserted, or FALSE on failure
2980
-     */
2981
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
-    {
2983
-        global $wpdb;
2984
-        $insertion_col_n_values = array();
2985
-        $format_for_insertion = array();
2986
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
-        foreach ($fields_on_table as $field_name => $field_obj) {
2988
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
-            if ($field_obj->is_auto_increment()) {
2990
-                continue;
2991
-            }
2992
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
-            if ($prepared_value !== null) {
2995
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
-            }
2998
-        }
2999
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3000
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3001
-            // so add the fk to the main table as a column
3002
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
-        }
3005
-        // insert the new entry
3006
-        $result = $this->_do_wpdb_query(
3007
-            'insert',
3008
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
-        );
3010
-        if ($result === false) {
3011
-            return false;
3012
-        }
3013
-        // ok, now what do we return for the ID of the newly-inserted thing?
3014
-        if ($this->has_primary_key_field()) {
3015
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3016
-                return $wpdb->insert_id;
3017
-            }
3018
-            // it's not an auto-increment primary key, so
3019
-            // it must have been supplied
3020
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
-        }
3022
-        // we can't return a  primary key because there is none. instead return
3023
-        // a unique string indicating this model
3024
-        return $this->get_index_primary_key_string($fields_n_values);
3025
-    }
3026
-
3027
-
3028
-
3029
-    /**
3030
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
-     * and there is no default, we pass it along. WPDB will take care of it)
3033
-     *
3034
-     * @param EE_Model_Field_Base $field_obj
3035
-     * @param array               $fields_n_values
3036
-     * @return mixed string|int|float depending on what the table column will be expecting
3037
-     * @throws EE_Error
3038
-     */
3039
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
-    {
3041
-        // if this field doesn't allow nullable, don't allow it
3042
-        if (
3043
-            ! $field_obj->is_nullable()
3044
-            && (
3045
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3046
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
-            )
3048
-        ) {
3049
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
-        }
3051
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
-            : null;
3054
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
-     * the field's prepare_for_set() method.
3063
-     *
3064
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
-     *                                   top of file)
3067
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
-     *                                   $value is a custom selection
3069
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
-     */
3071
-    private function _prepare_value_for_use_in_db($value, $field)
3072
-    {
3073
-        if ($field && $field instanceof EE_Model_Field_Base) {
3074
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
-            switch ($this->_values_already_prepared_by_model_object) {
3076
-                /** @noinspection PhpMissingBreakStatementInspection */
3077
-                case self::not_prepared_by_model_object:
3078
-                    $value = $field->prepare_for_set($value);
3079
-                // purposefully left out "return"
3080
-                case self::prepared_by_model_object:
3081
-                    /** @noinspection SuspiciousAssignmentsInspection */
3082
-                    $value = $field->prepare_for_use_in_db($value);
3083
-                case self::prepared_for_use_in_db:
3084
-                    // leave the value alone
3085
-            }
3086
-            return $value;
3087
-            // phpcs:enable
3088
-        }
3089
-        return $value;
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Returns the main table on this model
3096
-     *
3097
-     * @return EE_Primary_Table
3098
-     * @throws EE_Error
3099
-     */
3100
-    protected function _get_main_table()
3101
-    {
3102
-        foreach ($this->_tables as $table) {
3103
-            if ($table instanceof EE_Primary_Table) {
3104
-                return $table;
3105
-            }
3106
-        }
3107
-        throw new EE_Error(sprintf(esc_html__(
3108
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
-            'event_espresso'
3110
-        ), get_class($this)));
3111
-    }
3112
-
3113
-
3114
-
3115
-    /**
3116
-     * table
3117
-     * returns EE_Primary_Table table name
3118
-     *
3119
-     * @return string
3120
-     * @throws EE_Error
3121
-     */
3122
-    public function table()
3123
-    {
3124
-        return $this->_get_main_table()->get_table_name();
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * table
3131
-     * returns first EE_Secondary_Table table name
3132
-     *
3133
-     * @return string
3134
-     */
3135
-    public function second_table()
3136
-    {
3137
-        // grab second table from tables array
3138
-        $second_table = end($this->_tables);
3139
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
-    }
3141
-
3142
-
3143
-
3144
-    /**
3145
-     * get_table_obj_by_alias
3146
-     * returns table name given it's alias
3147
-     *
3148
-     * @param string $table_alias
3149
-     * @return EE_Primary_Table | EE_Secondary_Table
3150
-     */
3151
-    public function get_table_obj_by_alias($table_alias = '')
3152
-    {
3153
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
-     *
3161
-     * @return EE_Secondary_Table[]
3162
-     */
3163
-    protected function _get_other_tables()
3164
-    {
3165
-        $other_tables = array();
3166
-        foreach ($this->_tables as $table_alias => $table) {
3167
-            if ($table instanceof EE_Secondary_Table) {
3168
-                $other_tables[ $table_alias ] = $table;
3169
-            }
3170
-        }
3171
-        return $other_tables;
3172
-    }
3173
-
3174
-
3175
-
3176
-    /**
3177
-     * Finds all the fields that correspond to the given table
3178
-     *
3179
-     * @param string $table_alias , array key in EEM_Base::_tables
3180
-     * @return EE_Model_Field_Base[]
3181
-     */
3182
-    public function _get_fields_for_table($table_alias)
3183
-    {
3184
-        return $this->_fields[ $table_alias ];
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * Recurses through all the where parameters, and finds all the related models we'll need
3191
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
-     * related Registration, Transaction, and Payment models.
3195
-     *
3196
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
-     * @return EE_Model_Query_Info_Carrier
3198
-     * @throws EE_Error
3199
-     */
3200
-    public function _extract_related_models_from_query($query_params)
3201
-    {
3202
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
-        if (array_key_exists(0, $query_params)) {
3204
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
-        }
3206
-        if (array_key_exists('group_by', $query_params)) {
3207
-            if (is_array($query_params['group_by'])) {
3208
-                $this->_extract_related_models_from_sub_params_array_values(
3209
-                    $query_params['group_by'],
3210
-                    $query_info_carrier,
3211
-                    'group_by'
3212
-                );
3213
-            } elseif (! empty($query_params['group_by'])) {
3214
-                $this->_extract_related_model_info_from_query_param(
3215
-                    $query_params['group_by'],
3216
-                    $query_info_carrier,
3217
-                    'group_by'
3218
-                );
3219
-            }
3220
-        }
3221
-        if (array_key_exists('having', $query_params)) {
3222
-            $this->_extract_related_models_from_sub_params_array_keys(
3223
-                $query_params[0],
3224
-                $query_info_carrier,
3225
-                'having'
3226
-            );
3227
-        }
3228
-        if (array_key_exists('order_by', $query_params)) {
3229
-            if (is_array($query_params['order_by'])) {
3230
-                $this->_extract_related_models_from_sub_params_array_keys(
3231
-                    $query_params['order_by'],
3232
-                    $query_info_carrier,
3233
-                    'order_by'
3234
-                );
3235
-            } elseif (! empty($query_params['order_by'])) {
3236
-                $this->_extract_related_model_info_from_query_param(
3237
-                    $query_params['order_by'],
3238
-                    $query_info_carrier,
3239
-                    'order_by'
3240
-                );
3241
-            }
3242
-        }
3243
-        if (array_key_exists('force_join', $query_params)) {
3244
-            $this->_extract_related_models_from_sub_params_array_values(
3245
-                $query_params['force_join'],
3246
-                $query_info_carrier,
3247
-                'force_join'
3248
-            );
3249
-        }
3250
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
-        return $query_info_carrier;
3252
-    }
3253
-
3254
-
3255
-
3256
-    /**
3257
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
-     *
3259
-     * @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
3260
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3262
-     * @throws EE_Error
3263
-     * @return \EE_Model_Query_Info_Carrier
3264
-     */
3265
-    private function _extract_related_models_from_sub_params_array_keys(
3266
-        $sub_query_params,
3267
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
-        $query_param_type
3269
-    ) {
3270
-        if (! empty($sub_query_params)) {
3271
-            $sub_query_params = (array) $sub_query_params;
3272
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
-                $this->_extract_related_model_info_from_query_param(
3275
-                    $param,
3276
-                    $model_query_info_carrier,
3277
-                    $query_param_type
3278
-                );
3279
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
-                // of array('Registration.TXN_ID'=>23)
3283
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3286
-                        throw new EE_Error(sprintf(
3287
-                            esc_html__(
3288
-                                "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'))",
3289
-                                "event_espresso"
3290
-                            ),
3291
-                            $param,
3292
-                            $possibly_array_of_params
3293
-                        ));
3294
-                    }
3295
-                    $this->_extract_related_models_from_sub_params_array_keys(
3296
-                        $possibly_array_of_params,
3297
-                        $model_query_info_carrier,
3298
-                        $query_param_type
3299
-                    );
3300
-                } elseif (
3301
-                    $query_param_type === 0 // ie WHERE
3302
-                          && is_array($possibly_array_of_params)
3303
-                          && isset($possibly_array_of_params[2])
3304
-                          && $possibly_array_of_params[2] == true
3305
-                ) {
3306
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3308
-                    // from which we should extract query parameters!
3309
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
-                        throw new EE_Error(sprintf(esc_html__(
3311
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
-                            "event_espresso"
3313
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3314
-                    }
3315
-                    $this->_extract_related_model_info_from_query_param(
3316
-                        $possibly_array_of_params[1],
3317
-                        $model_query_info_carrier,
3318
-                        $query_param_type
3319
-                    );
3320
-                }
3321
-            }
3322
-        }
3323
-        return $model_query_info_carrier;
3324
-    }
3325
-
3326
-
3327
-
3328
-    /**
3329
-     * For extracting related models from forced_joins, where the array values contain the info about what
3330
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
-     *
3332
-     * @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
3333
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3335
-     * @throws EE_Error
3336
-     * @return \EE_Model_Query_Info_Carrier
3337
-     */
3338
-    private function _extract_related_models_from_sub_params_array_values(
3339
-        $sub_query_params,
3340
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
-        $query_param_type
3342
-    ) {
3343
-        if (! empty($sub_query_params)) {
3344
-            if (! is_array($sub_query_params)) {
3345
-                throw new EE_Error(sprintf(
3346
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
-                    $sub_query_params
3348
-                ));
3349
-            }
3350
-            foreach ($sub_query_params as $param) {
3351
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
-                $this->_extract_related_model_info_from_query_param(
3353
-                    $param,
3354
-                    $model_query_info_carrier,
3355
-                    $query_param_type
3356
-                );
3357
-            }
3358
-        }
3359
-        return $model_query_info_carrier;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Extract all the query parts from  model query params
3365
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
-     * but use them in a different order. Eg, we need to know what models we are querying
3368
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
-     * other models before we can finalize the where clause SQL.
3370
-     *
3371
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
-     * @throws EE_Error
3373
-     * @return EE_Model_Query_Info_Carrier
3374
-     * @throws ModelConfigurationException
3375
-     */
3376
-    public function _create_model_query_info_carrier($query_params)
3377
-    {
3378
-        if (! is_array($query_params)) {
3379
-            EE_Error::doing_it_wrong(
3380
-                'EEM_Base::_create_model_query_info_carrier',
3381
-                sprintf(
3382
-                    esc_html__(
3383
-                        '$query_params should be an array, you passed a variable of type %s',
3384
-                        'event_espresso'
3385
-                    ),
3386
-                    gettype($query_params)
3387
-                ),
3388
-                '4.6.0'
3389
-            );
3390
-            $query_params = array();
3391
-        }
3392
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
-        // first check if we should alter the query to account for caps or not
3394
-        // because the caps might require us to do extra joins
3395
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
-            $query_params[0] = array_replace_recursive(
3397
-                $query_params[0],
3398
-                $this->caps_where_conditions(
3399
-                    $query_params['caps']
3400
-                )
3401
-            );
3402
-        }
3403
-
3404
-        // check if we should alter the query to remove data related to protected
3405
-        // custom post types
3406
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
-            $where_param_key_for_password = $this->modelChainAndPassword();
3408
-            // only include if related to a cpt where no password has been set
3409
-            $query_params[0]['OR*nopassword'] = array(
3410
-                $where_param_key_for_password => '',
3411
-                $where_param_key_for_password . '*' => array('IS_NULL')
3412
-            );
3413
-        }
3414
-        $query_object = $this->_extract_related_models_from_query($query_params);
3415
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
-        foreach ($query_params[0] as $key => $value) {
3417
-            if (is_int($key)) {
3418
-                throw new EE_Error(
3419
-                    sprintf(
3420
-                        esc_html__(
3421
-                            "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.",
3422
-                            "event_espresso"
3423
-                        ),
3424
-                        $key,
3425
-                        var_export($value, true),
3426
-                        var_export($query_params, true),
3427
-                        get_class($this)
3428
-                    )
3429
-                );
3430
-            }
3431
-        }
3432
-        if (
3433
-            array_key_exists('default_where_conditions', $query_params)
3434
-            && ! empty($query_params['default_where_conditions'])
3435
-        ) {
3436
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3437
-        } else {
3438
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
-        }
3440
-        $query_params[0] = array_merge(
3441
-            $this->_get_default_where_conditions_for_models_in_query(
3442
-                $query_object,
3443
-                $use_default_where_conditions,
3444
-                $query_params[0]
3445
-            ),
3446
-            $query_params[0]
3447
-        );
3448
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
-        // So we need to setup a subquery and use that for the main join.
3451
-        // Note for now this only works on the primary table for the model.
3452
-        // So for instance, you could set the limit array like this:
3453
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
-            $query_object->set_main_model_join_sql(
3456
-                $this->_construct_limit_join_select(
3457
-                    $query_params['on_join_limit'][0],
3458
-                    $query_params['on_join_limit'][1]
3459
-                )
3460
-            );
3461
-        }
3462
-        // set limit
3463
-        if (array_key_exists('limit', $query_params)) {
3464
-            if (is_array($query_params['limit'])) {
3465
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
-                    $e = sprintf(
3467
-                        esc_html__(
3468
-                            "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)",
3469
-                            "event_espresso"
3470
-                        ),
3471
-                        http_build_query($query_params['limit'])
3472
-                    );
3473
-                    throw new EE_Error($e . "|" . $e);
3474
-                }
3475
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
-            } elseif (! empty($query_params['limit'])) {
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
-            }
3480
-        }
3481
-        // set order by
3482
-        if (array_key_exists('order_by', $query_params)) {
3483
-            if (is_array($query_params['order_by'])) {
3484
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
-                if (array_key_exists('order', $query_params)) {
3488
-                    throw new EE_Error(
3489
-                        sprintf(
3490
-                            esc_html__(
3491
-                                "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 ",
3492
-                                "event_espresso"
3493
-                            ),
3494
-                            get_class($this),
3495
-                            implode(", ", array_keys($query_params['order_by'])),
3496
-                            implode(", ", $query_params['order_by']),
3497
-                            $query_params['order']
3498
-                        )
3499
-                    );
3500
-                }
3501
-                $this->_extract_related_models_from_sub_params_array_keys(
3502
-                    $query_params['order_by'],
3503
-                    $query_object,
3504
-                    'order_by'
3505
-                );
3506
-                // assume it's an array of fields to order by
3507
-                $order_array = array();
3508
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
-                    $order = $this->_extract_order($order);
3510
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
-                }
3512
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
-            } elseif (! empty($query_params['order_by'])) {
3514
-                $this->_extract_related_model_info_from_query_param(
3515
-                    $query_params['order_by'],
3516
-                    $query_object,
3517
-                    'order',
3518
-                    $query_params['order_by']
3519
-                );
3520
-                $order = isset($query_params['order'])
3521
-                    ? $this->_extract_order($query_params['order'])
3522
-                    : 'DESC';
3523
-                $query_object->set_order_by_sql(
3524
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
-                );
3526
-            }
3527
-        }
3528
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
-        if (
3530
-            ! array_key_exists('order_by', $query_params)
3531
-            && array_key_exists('order', $query_params)
3532
-            && ! empty($query_params['order'])
3533
-        ) {
3534
-            $pk_field = $this->get_primary_key_field();
3535
-            $order = $this->_extract_order($query_params['order']);
3536
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
-        }
3538
-        // set group by
3539
-        if (array_key_exists('group_by', $query_params)) {
3540
-            if (is_array($query_params['group_by'])) {
3541
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3542
-                $group_by_array = array();
3543
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
-                }
3546
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
-            } elseif (! empty($query_params['group_by'])) {
3548
-                $query_object->set_group_by_sql(
3549
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
-                );
3551
-            }
3552
-        }
3553
-        // set having
3554
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
-        }
3557
-        // now, just verify they didn't pass anything wack
3558
-        foreach ($query_params as $query_key => $query_value) {
3559
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
-                throw new EE_Error(
3561
-                    sprintf(
3562
-                        esc_html__(
3563
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
-                            'event_espresso'
3565
-                        ),
3566
-                        $query_key,
3567
-                        get_class($this),
3568
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3569
-                        implode(',', $this->_allowed_query_params)
3570
-                    )
3571
-                );
3572
-            }
3573
-        }
3574
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3575
-        if (empty($main_model_join_sql)) {
3576
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
-        }
3578
-        return $query_object;
3579
-    }
3580
-
3581
-
3582
-
3583
-    /**
3584
-     * Gets the where conditions that should be imposed on the query based on the
3585
-     * context (eg reading frontend, backend, edit or delete).
3586
-     *
3587
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3588
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
-     * @throws EE_Error
3590
-     */
3591
-    public function caps_where_conditions($context = self::caps_read)
3592
-    {
3593
-        EEM_Base::verify_is_valid_cap_context($context);
3594
-        $cap_where_conditions = array();
3595
-        $cap_restrictions = $this->caps_missing($context);
3596
-        /**
3597
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
-         */
3599
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
-            $cap_where_conditions = array_replace_recursive(
3601
-                $cap_where_conditions,
3602
-                $restriction_if_no_cap->get_default_where_conditions()
3603
-            );
3604
-        }
3605
-        return apply_filters(
3606
-            'FHEE__EEM_Base__caps_where_conditions__return',
3607
-            $cap_where_conditions,
3608
-            $this,
3609
-            $context,
3610
-            $cap_restrictions
3611
-        );
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
-     * otherwise throws an exception
3619
-     *
3620
-     * @param string $should_be_order_string
3621
-     * @return string either ASC, asc, DESC or desc
3622
-     * @throws EE_Error
3623
-     */
3624
-    private function _extract_order($should_be_order_string)
3625
-    {
3626
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
-            return $should_be_order_string;
3628
-        }
3629
-        throw new EE_Error(
3630
-            sprintf(
3631
-                esc_html__(
3632
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
-                    "event_espresso"
3634
-                ),
3635
-                get_class($this),
3636
-                $should_be_order_string
3637
-            )
3638
-        );
3639
-    }
3640
-
3641
-
3642
-
3643
-    /**
3644
-     * Looks at all the models which are included in this query, and asks each
3645
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
-     * so they can be merged
3647
-     *
3648
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
-     *                                                                  'none' means NO default where conditions will
3651
-     *                                                                  be used AT ALL during this query.
3652
-     *                                                                  'other_models_only' means default where
3653
-     *                                                                  conditions from other models will be used, but
3654
-     *                                                                  not for this primary model. 'all', the default,
3655
-     *                                                                  means default where conditions will apply as
3656
-     *                                                                  normal
3657
-     * @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
3658
-     * @throws EE_Error
3659
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
-     */
3661
-    private function _get_default_where_conditions_for_models_in_query(
3662
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3663
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
-        $where_query_params = array()
3665
-    ) {
3666
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
-            throw new EE_Error(sprintf(
3669
-                esc_html__(
3670
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
-                    "event_espresso"
3672
-                ),
3673
-                $use_default_where_conditions,
3674
-                implode(", ", $allowed_used_default_where_conditions_values)
3675
-            ));
3676
-        }
3677
-        $universal_query_params = array();
3678
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
-            $universal_query_params = $this->_get_default_where_conditions();
3680
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_minimum_where_conditions();
3682
-        }
3683
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
-            $related_model = $this->get_related_model_obj($model_name);
3685
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
-            } else {
3690
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3691
-                continue;
3692
-            }
3693
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3694
-                $related_model_universal_where_params,
3695
-                $where_query_params,
3696
-                $related_model,
3697
-                $model_relation_path
3698
-            );
3699
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
-                $universal_query_params,
3701
-                $overrides
3702
-            );
3703
-        }
3704
-        return $universal_query_params;
3705
-    }
3706
-
3707
-
3708
-
3709
-    /**
3710
-     * Determines whether or not we should use default where conditions for the model in question
3711
-     * (this model, or other related models).
3712
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
-     * We should use default where conditions on related models when they requested to use default where conditions
3715
-     * on all models, or specifically just on other related models
3716
-     * @param      $default_where_conditions_value
3717
-     * @param bool $for_this_model false means this is for OTHER related models
3718
-     * @return bool
3719
-     */
3720
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
-    {
3722
-        return (
3723
-                   $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_all,
3728
-                           EEM_Base::default_where_conditions_this_only,
3729
-                           EEM_Base::default_where_conditions_minimum_others,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               )
3734
-               || (
3735
-                   ! $for_this_model
3736
-                   && in_array(
3737
-                       $default_where_conditions_value,
3738
-                       array(
3739
-                           EEM_Base::default_where_conditions_all,
3740
-                           EEM_Base::default_where_conditions_others_only,
3741
-                       ),
3742
-                       true
3743
-                   )
3744
-               );
3745
-    }
3746
-
3747
-    /**
3748
-     * Determines whether or not we should use default minimum conditions for the model in question
3749
-     * (this model, or other related models).
3750
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
-     * where conditions.
3752
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
-     * on this model or others
3754
-     * @param      $default_where_conditions_value
3755
-     * @param bool $for_this_model false means this is for OTHER related models
3756
-     * @return bool
3757
-     */
3758
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
-    {
3760
-        return (
3761
-                   $for_this_model
3762
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
-               )
3764
-               || (
3765
-                   ! $for_this_model
3766
-                   && in_array(
3767
-                       $default_where_conditions_value,
3768
-                       array(
3769
-                           EEM_Base::default_where_conditions_minimum_others,
3770
-                           EEM_Base::default_where_conditions_minimum_all,
3771
-                       ),
3772
-                       true
3773
-                   )
3774
-               );
3775
-    }
3776
-
3777
-
3778
-    /**
3779
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
-     * then we also add a special where condition which allows for that model's primary key
3781
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
-     *
3784
-     * @param array    $default_where_conditions
3785
-     * @param array    $provided_where_conditions
3786
-     * @param EEM_Base $model
3787
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3788
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
-     * @throws EE_Error
3790
-     */
3791
-    private function _override_defaults_or_make_null_friendly(
3792
-        $default_where_conditions,
3793
-        $provided_where_conditions,
3794
-        $model,
3795
-        $model_relation_path
3796
-    ) {
3797
-        $null_friendly_where_conditions = array();
3798
-        $none_overridden = true;
3799
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
-        foreach ($default_where_conditions as $key => $val) {
3801
-            if (isset($provided_where_conditions[ $key ])) {
3802
-                $none_overridden = false;
3803
-            } else {
3804
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
-            }
3806
-        }
3807
-        if ($none_overridden && $default_where_conditions) {
3808
-            if ($model->has_primary_key_field()) {
3809
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
-                                                                                . "."
3811
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3812
-            }/*else{
39
+	/**
40
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
43
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
+	 *
45
+	 * @var boolean
46
+	 */
47
+	private $_values_already_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we assume
51
+	 * the data is just like form input that needs to have the model fields'
52
+	 * prepare_for_set and prepare_for_use_in_db called on it
53
+	 */
54
+	const not_prepared_by_model_object = 0;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we
58
+	 * assume this value is coming from a model object and doesn't need to have
59
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
60
+	 */
61
+	const prepared_by_model_object = 1;
62
+
63
+	/**
64
+	 * when $_values_already_prepared_by_model_object equals this, we assume
65
+	 * the values are already to be used in the database (ie no processing is done
66
+	 * on them by the model's fields)
67
+	 */
68
+	const prepared_for_use_in_db = 2;
69
+
70
+
71
+	protected $singular_item = 'Item';
72
+
73
+	protected $plural_item   = 'Items';
74
+
75
+	/**
76
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
+	 */
78
+	protected $_tables;
79
+
80
+	/**
81
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
+	 *
85
+	 * @var \EE_Model_Field_Base[][] $_fields
86
+	 */
87
+	protected $_fields;
88
+
89
+	/**
90
+	 * array of different kinds of relations
91
+	 *
92
+	 * @var \EE_Model_Relation_Base[] $_model_relations
93
+	 */
94
+	protected $_model_relations;
95
+
96
+	/**
97
+	 * @var \EE_Index[] $_indexes
98
+	 */
99
+	protected $_indexes = array();
100
+
101
+	/**
102
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
103
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
+	 * by setting the same columns as used in these queries in the query yourself.
105
+	 *
106
+	 * @var EE_Default_Where_Conditions
107
+	 */
108
+	protected $_default_where_conditions_strategy;
109
+
110
+	/**
111
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
+	 * This is particularly useful when you want something between 'none' and 'default'
113
+	 *
114
+	 * @var EE_Default_Where_Conditions
115
+	 */
116
+	protected $_minimum_where_conditions_strategy;
117
+
118
+	/**
119
+	 * String describing how to find the "owner" of this model's objects.
120
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
+	 * But when there isn't, this indicates which related model, or transiently-related model,
122
+	 * has the foreign key to the wp_users table.
123
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
+	 * related to events, and events have a foreign key to wp_users.
125
+	 * On EEM_Transaction, this would be 'Transaction.Event'
126
+	 *
127
+	 * @var string
128
+	 */
129
+	protected $_model_chain_to_wp_user = '';
130
+
131
+	/**
132
+	 * String describing how to find the model with a password controlling access to this model. This property has the
133
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
+	 * This value is the path of models to follow to arrive at the model with the password field.
135
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
+	 * model with a password that should affect reading this on the front-end.
137
+	 * Eg this is an empty string for the Event model because it has a password.
138
+	 * This is null for the Registration model, because its event's password has no bearing on whether
139
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
+	 * should hide tickets for datetimes for events that have a password set.
142
+	 * @var string |null
143
+	 */
144
+	protected $model_chain_to_password = null;
145
+
146
+	/**
147
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
+	 * don't need it (particularly CPT models)
149
+	 *
150
+	 * @var bool
151
+	 */
152
+	protected $_ignore_where_strategy = false;
153
+
154
+	/**
155
+	 * String used in caps relating to this model. Eg, if the caps relating to this
156
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
+	 *
158
+	 * @var string. If null it hasn't been initialized yet. If false then we
159
+	 * have indicated capabilities don't apply to this
160
+	 */
161
+	protected $_caps_slug = null;
162
+
163
+	/**
164
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
+	 * and next-level keys are capability names, and each's value is a
166
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
168
+	 * and then each capability in the corresponding sub-array that they're missing
169
+	 * adds the where conditions onto the query.
170
+	 *
171
+	 * @var array
172
+	 */
173
+	protected $_cap_restrictions = array(
174
+		self::caps_read       => array(),
175
+		self::caps_read_admin => array(),
176
+		self::caps_edit       => array(),
177
+		self::caps_delete     => array(),
178
+	);
179
+
180
+	/**
181
+	 * Array defining which cap restriction generators to use to create default
182
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
183
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
+	 * automatically set this to false (not just null).
186
+	 *
187
+	 * @var EE_Restriction_Generator_Base[]
188
+	 */
189
+	protected $_cap_restriction_generators = array();
190
+
191
+	/**
192
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
+	 */
194
+	const caps_read       = 'read';
195
+
196
+	const caps_read_admin = 'read_admin';
197
+
198
+	const caps_edit       = 'edit';
199
+
200
+	const caps_delete     = 'delete';
201
+
202
+	/**
203
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
+	 * maps to 'read' because when looking for relevant permissions we're going to use
206
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
207
+	 *
208
+	 * @var array
209
+	 */
210
+	protected $_cap_contexts_to_cap_action_map = array(
211
+		self::caps_read       => 'read',
212
+		self::caps_read_admin => 'read',
213
+		self::caps_edit       => 'edit',
214
+		self::caps_delete     => 'delete',
215
+	);
216
+
217
+	/**
218
+	 * Timezone
219
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
+	 * EE_Datetime_Field data type will have access to it.
223
+	 *
224
+	 * @var string
225
+	 */
226
+	protected $_timezone;
227
+
228
+
229
+	/**
230
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
+	 * multisite.
232
+	 *
233
+	 * @var int
234
+	 */
235
+	protected static $_model_query_blog_id;
236
+
237
+	/**
238
+	 * A copy of _fields, except the array keys are the model names pointed to by
239
+	 * the field
240
+	 *
241
+	 * @var EE_Model_Field_Base[]
242
+	 */
243
+	private $_cache_foreign_key_to_fields = array();
244
+
245
+	/**
246
+	 * Cached list of all the fields on the model, indexed by their name
247
+	 *
248
+	 * @var EE_Model_Field_Base[]
249
+	 */
250
+	private $_cached_fields = null;
251
+
252
+	/**
253
+	 * Cached list of all the fields on the model, except those that are
254
+	 * marked as only pertinent to the database
255
+	 *
256
+	 * @var EE_Model_Field_Base[]
257
+	 */
258
+	private $_cached_fields_non_db_only = null;
259
+
260
+	/**
261
+	 * A cached reference to the primary key for quick lookup
262
+	 *
263
+	 * @var EE_Model_Field_Base
264
+	 */
265
+	private $_primary_key_field = null;
266
+
267
+	/**
268
+	 * Flag indicating whether this model has a primary key or not
269
+	 *
270
+	 * @var boolean
271
+	 */
272
+	protected $_has_primary_key_field = null;
273
+
274
+	/**
275
+	 * array in the format:  [ FK alias => full PK ]
276
+	 * where keys are local column name aliases for foreign keys
277
+	 * and values are the fully qualified column name for the primary key they represent
278
+	 *  ex:
279
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
+	 *
281
+	 * @var array $foreign_key_aliases
282
+	 */
283
+	protected $foreign_key_aliases = [];
284
+
285
+	/**
286
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
287
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
+	 * This should be true for models that deal with data that should exist independent of EE.
289
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
291
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
293
+	 * @var boolean
294
+	 */
295
+	protected $_wp_core_model = false;
296
+
297
+	/**
298
+	 * @var bool stores whether this model has a password field or not.
299
+	 * null until initialized by hasPasswordField()
300
+	 */
301
+	protected $has_password_field;
302
+
303
+	/**
304
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
+	 */
306
+	protected $password_field;
307
+
308
+	/**
309
+	 *    List of valid operators that can be used for querying.
310
+	 * The keys are all operators we'll accept, the values are the real SQL
311
+	 * operators used
312
+	 *
313
+	 * @var array
314
+	 */
315
+	protected $_valid_operators = array(
316
+		'='           => '=',
317
+		'<='          => '<=',
318
+		'<'           => '<',
319
+		'>='          => '>=',
320
+		'>'           => '>',
321
+		'!='          => '!=',
322
+		'LIKE'        => 'LIKE',
323
+		'like'        => 'LIKE',
324
+		'NOT_LIKE'    => 'NOT LIKE',
325
+		'not_like'    => 'NOT LIKE',
326
+		'NOT LIKE'    => 'NOT LIKE',
327
+		'not like'    => 'NOT LIKE',
328
+		'IN'          => 'IN',
329
+		'in'          => 'IN',
330
+		'NOT_IN'      => 'NOT IN',
331
+		'not_in'      => 'NOT IN',
332
+		'NOT IN'      => 'NOT IN',
333
+		'not in'      => 'NOT IN',
334
+		'between'     => 'BETWEEN',
335
+		'BETWEEN'     => 'BETWEEN',
336
+		'IS_NOT_NULL' => 'IS NOT NULL',
337
+		'is_not_null' => 'IS NOT NULL',
338
+		'IS NOT NULL' => 'IS NOT NULL',
339
+		'is not null' => 'IS NOT NULL',
340
+		'IS_NULL'     => 'IS NULL',
341
+		'is_null'     => 'IS NULL',
342
+		'IS NULL'     => 'IS NULL',
343
+		'is null'     => 'IS NULL',
344
+		'REGEXP'      => 'REGEXP',
345
+		'regexp'      => 'REGEXP',
346
+		'NOT_REGEXP'  => 'NOT REGEXP',
347
+		'not_regexp'  => 'NOT REGEXP',
348
+		'NOT REGEXP'  => 'NOT REGEXP',
349
+		'not regexp'  => 'NOT REGEXP',
350
+	);
351
+
352
+	/**
353
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
+	 *
355
+	 * @var array
356
+	 */
357
+	protected $_in_style_operators = array('IN', 'NOT IN');
358
+
359
+	/**
360
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
+	 * '12-31-2012'"
362
+	 *
363
+	 * @var array
364
+	 */
365
+	protected $_between_style_operators = array('BETWEEN');
366
+
367
+	/**
368
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
+	 * @var array
370
+	 */
371
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
+	/**
373
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
+	 * on a join table.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
+
380
+	/**
381
+	 * Allowed values for $query_params['order'] for ordering in queries
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
+
387
+	/**
388
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
390
+	 *
391
+	 * @var array
392
+	 */
393
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
+
395
+	/**
396
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
398
+	 *
399
+	 * @var array
400
+	 */
401
+	private $_allowed_query_params = array(
402
+		0,
403
+		'limit',
404
+		'order_by',
405
+		'group_by',
406
+		'having',
407
+		'force_join',
408
+		'order',
409
+		'on_join_limit',
410
+		'default_where_conditions',
411
+		'caps',
412
+		'extra_selects',
413
+		'exclude_protected',
414
+	);
415
+
416
+	/**
417
+	 * All the data types that can be used in $wpdb->prepare statements.
418
+	 *
419
+	 * @var array
420
+	 */
421
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
+
423
+	/**
424
+	 * @var EE_Registry $EE
425
+	 */
426
+	protected $EE = null;
427
+
428
+
429
+	/**
430
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
+	 *
432
+	 * @var int
433
+	 */
434
+	protected $_show_next_x_db_queries = 0;
435
+
436
+	/**
437
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
+	 * WHERE, GROUP_BY, etc.
440
+	 *
441
+	 * @var CustomSelects
442
+	 */
443
+	protected $_custom_selections = array();
444
+
445
+	/**
446
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
+	 * caches every model object we've fetched from the DB on this request
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_entity_map;
452
+
453
+	/**
454
+	 * @var LoaderInterface $loader
455
+	 */
456
+	protected static $loader;
457
+
458
+
459
+	/**
460
+	 * constant used to show EEM_Base has not yet verified the db on this http request
461
+	 */
462
+	const db_verified_none = 0;
463
+
464
+	/**
465
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
466
+	 * but not the addons' dbs
467
+	 */
468
+	const db_verified_core = 1;
469
+
470
+	/**
471
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
+	 * the EE core db too)
473
+	 */
474
+	const db_verified_addons = 2;
475
+
476
+	/**
477
+	 * indicates whether an EEM_Base child has already re-verified the DB
478
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
479
+	 * looking like EEM_Base::db_verified_*
480
+	 *
481
+	 * @var int - 0 = none, 1 = core, 2 = addons
482
+	 */
483
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
484
+
485
+	/**
486
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
489
+	 */
490
+	const default_where_conditions_all = 'all';
491
+
492
+	/**
493
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
+	 *        models which share tables with other models, this can return data for the wrong model.
498
+	 */
499
+	const default_where_conditions_this_only = 'this_model_only';
500
+
501
+	/**
502
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
+	 */
506
+	const default_where_conditions_others_only = 'other_models_only';
507
+
508
+	/**
509
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
512
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
+	 *        (regardless of whether those events and venues are trashed)
514
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
+	 *        events.
516
+	 */
517
+	const default_where_conditions_minimum_all = 'minimum';
518
+
519
+	/**
520
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
+	 *        not)
524
+	 */
525
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
+
527
+	/**
528
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
+	 *        it's possible it will return table entries for other models. You should use
531
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
532
+	 */
533
+	const default_where_conditions_none = 'none';
534
+
535
+
536
+
537
+	/**
538
+	 * About all child constructors:
539
+	 * they should define the _tables, _fields and _model_relations arrays.
540
+	 * Should ALWAYS be called after child constructor.
541
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
542
+	 * finalizes constructing all the object's attributes.
543
+	 * Generally, rather than requiring a child to code
544
+	 * $this->_tables = array(
545
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
+	 *        ...);
547
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
+	 * each EE_Table has a function to set the table's alias after the constructor, using
549
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
+	 * do something similar.
551
+	 *
552
+	 * @param null $timezone
553
+	 * @throws EE_Error
554
+	 */
555
+	protected function __construct($timezone = null)
556
+	{
557
+		// check that the model has not been loaded too soon
558
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
+			throw new EE_Error(
560
+				sprintf(
561
+					esc_html__(
562
+						'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.',
563
+						'event_espresso'
564
+					),
565
+					get_class($this)
566
+				)
567
+			);
568
+		}
569
+		/**
570
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
+		 */
572
+		if (empty(EEM_Base::$_model_query_blog_id)) {
573
+			EEM_Base::set_model_query_blog_id();
574
+		}
575
+		/**
576
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
+		 * just use EE_Register_Model_Extension
578
+		 *
579
+		 * @var EE_Table_Base[] $_tables
580
+		 */
581
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
+		foreach ($this->_tables as $table_alias => $table_obj) {
583
+			/** @var $table_obj EE_Table_Base */
584
+			$table_obj->_construct_finalize_with_alias($table_alias);
585
+			if ($table_obj instanceof EE_Secondary_Table) {
586
+				/** @var $table_obj EE_Secondary_Table */
587
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
+			}
589
+		}
590
+		/**
591
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
+		 * EE_Register_Model_Extension
593
+		 *
594
+		 * @param EE_Model_Field_Base[] $_fields
595
+		 */
596
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
+		$this->_invalidate_field_caches();
598
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
599
+			if (! array_key_exists($table_alias, $this->_tables)) {
600
+				throw new EE_Error(sprintf(esc_html__(
601
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
+					'event_espresso'
603
+				), $table_alias, implode(",", $this->_fields)));
604
+			}
605
+			foreach ($fields_for_table as $field_name => $field_obj) {
606
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
+				// primary key field base has a slightly different _construct_finalize
608
+				/** @var $field_obj EE_Model_Field_Base */
609
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
+			}
611
+		}
612
+		// everything is related to Extra_Meta
613
+		if (get_class($this) !== 'EEM_Extra_Meta') {
614
+			// make extra meta related to everything, but don't block deleting things just
615
+			// because they have related extra meta info. For now just orphan those extra meta
616
+			// in the future we should automatically delete them
617
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
+		}
619
+		// and change logs
620
+		if (get_class($this) !== 'EEM_Change_Log') {
621
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
+		}
623
+		/**
624
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
+		 * EE_Register_Model_Extension
626
+		 *
627
+		 * @param EE_Model_Relation_Base[] $_model_relations
628
+		 */
629
+		$this->_model_relations = (array) apply_filters(
630
+			'FHEE__' . get_class($this) . '__construct__model_relations',
631
+			$this->_model_relations
632
+		);
633
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
634
+			/** @var $relation_obj EE_Model_Relation_Base */
635
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
+		}
637
+		foreach ($this->_indexes as $index_name => $index_obj) {
638
+			/** @var $index_obj EE_Index */
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 ($this->_cap_restriction_generators !== false) {
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 ($this->_cap_restriction_generators !== false) {
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
+							esc_html__(
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
+				EEM_Base::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
+				EEM_Base::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
+	private static function getLoader()
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
+							esc_html__(
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
+					esc_html__('$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(esc_html__(
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(esc_html__('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
+					esc_html__('$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(esc_html__(
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
+					esc_html__('$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
+					esc_html__(
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
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
+			}
2181
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
+			$ways_to_identify_a_row = array();
2184
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
+				$values_for_each_combined_primary_key_for_a_row = array();
2186
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
+				}
2189
+				$ways_to_identify_a_row[] = '('
2190
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
+											. ')';
2192
+			}
2193
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2194
+		}
2195
+		return $query_part;
2196
+	}
2197
+
2198
+
2199
+
2200
+	/**
2201
+	 * Gets the model field by the fully qualified name
2202
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
+	 * @return EE_Model_Field_Base
2204
+	 */
2205
+	public function get_field_by_column($qualified_column_name)
2206
+	{
2207
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
+				return $field_obj;
2210
+			}
2211
+		}
2212
+		throw new EE_Error(
2213
+			sprintf(
2214
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
+				$this->get_this_model_name(),
2216
+				$qualified_column_name
2217
+			)
2218
+		);
2219
+	}
2220
+
2221
+
2222
+
2223
+	/**
2224
+	 * Count all the rows that match criteria the model query params.
2225
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
+	 * column
2227
+	 *
2228
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
+	 * @param string $field_to_count field on model to count by (not column name)
2230
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
+	 *                               that by the setting $distinct to TRUE;
2232
+	 * @return int
2233
+	 * @throws EE_Error
2234
+	 */
2235
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
+	{
2237
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
+		if ($field_to_count) {
2239
+			$field_obj = $this->field_settings_for($field_to_count);
2240
+			$column_to_count = $field_obj->get_qualified_column();
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$pk_field_obj = $this->get_primary_key_field();
2243
+			$column_to_count = $pk_field_obj->get_qualified_column();
2244
+		} else {
2245
+			// there's no primary key
2246
+			// if we're counting distinct items, and there's no primary key,
2247
+			// we need to list out the columns for distinction;
2248
+			// otherwise we can just use star
2249
+			if ($distinct) {
2250
+				$columns_to_use = array();
2251
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
+					$columns_to_use[] = $field_obj->get_qualified_column();
2253
+				}
2254
+				$column_to_count = implode(',', $columns_to_use);
2255
+			} else {
2256
+				$column_to_count = '*';
2257
+			}
2258
+		}
2259
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
+	}
2263
+
2264
+
2265
+
2266
+	/**
2267
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
+	 *
2269
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2271
+	 * @return float
2272
+	 * @throws EE_Error
2273
+	 */
2274
+	public function sum($query_params, $field_to_sum = null)
2275
+	{
2276
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
+		if ($field_to_sum) {
2278
+			$field_obj = $this->field_settings_for($field_to_sum);
2279
+		} else {
2280
+			$field_obj = $this->get_primary_key_field();
2281
+		}
2282
+		$column_to_count = $field_obj->get_qualified_column();
2283
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
+		$data_type = $field_obj->get_wpdb_data_type();
2286
+		if ($data_type === '%d' || $data_type === '%s') {
2287
+			return (float) $return_value;
2288
+		}
2289
+		// must be %f
2290
+		return (float) $return_value;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Just calls the specified method on $wpdb with the given arguments
2297
+	 * Consolidates a little extra error handling code
2298
+	 *
2299
+	 * @param string $wpdb_method
2300
+	 * @param array  $arguments_to_provide
2301
+	 * @throws EE_Error
2302
+	 * @global wpdb  $wpdb
2303
+	 * @return mixed
2304
+	 */
2305
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
+	{
2307
+		// if we're in maintenance mode level 2, DON'T run any queries
2308
+		// because level 2 indicates the database needs updating and
2309
+		// is probably out of sync with the code
2310
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
+			throw new EE_Error(sprintf(esc_html__(
2312
+				"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.",
2313
+				"event_espresso"
2314
+			)));
2315
+		}
2316
+		/** @type WPDB $wpdb */
2317
+		global $wpdb;
2318
+		if (! method_exists($wpdb, $wpdb_method)) {
2319
+			throw new EE_Error(sprintf(esc_html__(
2320
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2321
+				'event_espresso'
2322
+			), $wpdb_method));
2323
+		}
2324
+		if (WP_DEBUG) {
2325
+			$old_show_errors_value = $wpdb->show_errors;
2326
+			$wpdb->show_errors(false);
2327
+		}
2328
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2330
+		if (WP_DEBUG) {
2331
+			$wpdb->show_errors($old_show_errors_value);
2332
+			if (! empty($wpdb->last_error)) {
2333
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
+			}
2335
+			if ($result === false) {
2336
+				throw new EE_Error(sprintf(esc_html__(
2337
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
+					'event_espresso'
2339
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2340
+			}
2341
+		} elseif ($result === false) {
2342
+			EE_Error::add_error(
2343
+				sprintf(
2344
+					esc_html__(
2345
+						'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"',
2346
+						'event_espresso'
2347
+					),
2348
+					$wpdb_method,
2349
+					var_export($arguments_to_provide, true),
2350
+					$wpdb->last_error
2351
+				),
2352
+				__FILE__,
2353
+				__FUNCTION__,
2354
+				__LINE__
2355
+			);
2356
+		}
2357
+		return $result;
2358
+	}
2359
+
2360
+
2361
+
2362
+	/**
2363
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2364
+	 * and if there's an error tries to verify the DB is correct. Uses
2365
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2366
+	 * we should try to fix the EE core db, the addons, or just give up
2367
+	 *
2368
+	 * @param string $wpdb_method
2369
+	 * @param array  $arguments_to_provide
2370
+	 * @return mixed
2371
+	 */
2372
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		/** @type WPDB $wpdb */
2375
+		global $wpdb;
2376
+		$wpdb->last_error = null;
2377
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
+		// was there an error running the query? but we don't care on new activations
2379
+		// (we're going to setup the DB anyway on new activations)
2380
+		if (
2381
+			($result === false || ! empty($wpdb->last_error))
2382
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
+		) {
2384
+			switch (EEM_Base::$_db_verification_level) {
2385
+				case EEM_Base::db_verified_none:
2386
+					// let's double-check core's DB
2387
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
+					break;
2389
+				case EEM_Base::db_verified_core:
2390
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
+					break;
2393
+				case EEM_Base::db_verified_addons:
2394
+					// ummmm... you in trouble
2395
+					return $result;
2396
+					break;
2397
+			}
2398
+			if (! empty($error_message)) {
2399
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
+				trigger_error($error_message);
2401
+			}
2402
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
+		}
2404
+		return $result;
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2411
+	 * EEM_Base::$_db_verification_level
2412
+	 *
2413
+	 * @param string $wpdb_method
2414
+	 * @param array  $arguments_to_provide
2415
+	 * @return string
2416
+	 */
2417
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
+	{
2419
+		/** @type WPDB $wpdb */
2420
+		global $wpdb;
2421
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2422
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
+		$error_message = sprintf(
2424
+			esc_html__(
2425
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
+				'event_espresso'
2427
+			),
2428
+			$wpdb->last_error,
2429
+			$wpdb_method,
2430
+			wp_json_encode($arguments_to_provide)
2431
+		);
2432
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
+		return $error_message;
2434
+	}
2435
+
2436
+
2437
+
2438
+	/**
2439
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
+	 * EEM_Base::$_db_verification_level
2441
+	 *
2442
+	 * @param $wpdb_method
2443
+	 * @param $arguments_to_provide
2444
+	 * @return string
2445
+	 */
2446
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
+	{
2448
+		/** @type WPDB $wpdb */
2449
+		global $wpdb;
2450
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
+		$error_message = sprintf(
2453
+			esc_html__(
2454
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
+				'event_espresso'
2456
+			),
2457
+			$wpdb->last_error,
2458
+			$wpdb_method,
2459
+			wp_json_encode($arguments_to_provide)
2460
+		);
2461
+		EE_System::instance()->initialize_addons();
2462
+		return $error_message;
2463
+	}
2464
+
2465
+
2466
+
2467
+	/**
2468
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
+	 * ..."
2472
+	 *
2473
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2474
+	 * @return string
2475
+	 */
2476
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
+	{
2478
+		return " FROM " . $model_query_info->get_full_join_sql() .
2479
+			   $model_query_info->get_where_sql() .
2480
+			   $model_query_info->get_group_by_sql() .
2481
+			   $model_query_info->get_having_sql() .
2482
+			   $model_query_info->get_order_by_sql() .
2483
+			   $model_query_info->get_limit_sql();
2484
+	}
2485
+
2486
+
2487
+
2488
+	/**
2489
+	 * Set to easily debug the next X queries ran from this model.
2490
+	 *
2491
+	 * @param int $count
2492
+	 */
2493
+	public function show_next_x_db_queries($count = 1)
2494
+	{
2495
+		$this->_show_next_x_db_queries = $count;
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * @param $sql_query
2502
+	 */
2503
+	public function show_db_query_if_previously_requested($sql_query)
2504
+	{
2505
+		if ($this->_show_next_x_db_queries > 0) {
2506
+			echo esc_html($sql_query);
2507
+			$this->_show_next_x_db_queries--;
2508
+		}
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
+	 * There are the 3 cases:
2516
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
+	 * $otherModelObject has no ID, it is first saved.
2518
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
+	 * has no ID, it is first saved.
2520
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
+	 * join table
2523
+	 *
2524
+	 * @param        EE_Base_Class                     /int $thisModelObject
2525
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
+	 * @param string $relationName                     , key in EEM_Base::_relations
2527
+	 *                                                 an attendee to a group, you also want to specify which role they
2528
+	 *                                                 will have in that group. So you would use this parameter to
2529
+	 *                                                 specify array('role-column-name'=>'role-id')
2530
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
+	 *                                                 to for relation to methods that allow you to further specify
2532
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
+	 *                                                 because these will be inserted in any new rows created as well.
2535
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
+	 * @throws EE_Error
2537
+	 */
2538
+	public function add_relationship_to(
2539
+		$id_or_obj,
2540
+		$other_model_id_or_obj,
2541
+		$relationName,
2542
+		$extra_join_model_fields_n_values = array()
2543
+	) {
2544
+		$relation_obj = $this->related_settings_for($relationName);
2545
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
+	}
2547
+
2548
+
2549
+
2550
+	/**
2551
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
+	 * There are the 3 cases:
2553
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
+	 * error
2555
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
+	 * an error
2557
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
+	 *
2559
+	 * @param        EE_Base_Class /int $id_or_obj
2560
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
+	 * @param string $relationName key in EEM_Base::_relations
2562
+	 * @return boolean of success
2563
+	 * @throws EE_Error
2564
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
+	 *                             because these will be inserted in any new rows created as well.
2568
+	 */
2569
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
+	{
2571
+		$relation_obj = $this->related_settings_for($relationName);
2572
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
+	}
2574
+
2575
+
2576
+
2577
+	/**
2578
+	 * @param mixed           $id_or_obj
2579
+	 * @param string          $relationName
2580
+	 * @param array           $where_query_params
2581
+	 * @param EE_Base_Class[] objects to which relations were removed
2582
+	 * @return \EE_Base_Class[]
2583
+	 * @throws EE_Error
2584
+	 */
2585
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
+	{
2587
+		$relation_obj = $this->related_settings_for($relationName);
2588
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
+	}
2590
+
2591
+
2592
+
2593
+	/**
2594
+	 * Gets all the related items of the specified $model_name, using $query_params.
2595
+	 * Note: by default, we remove the "default query params"
2596
+	 * because we want to get even deleted items etc.
2597
+	 *
2598
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
+	 * @return EE_Base_Class[]
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
+	{
2606
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2607
+		$relation_settings = $this->related_settings_for($model_name);
2608
+		return $relation_settings->get_all_related($model_obj, $query_params);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Deletes all the model objects across the relation indicated by $model_name
2615
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2617
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
+	 *
2619
+	 * @param EE_Base_Class|int|string $id_or_obj
2620
+	 * @param string                   $model_name
2621
+	 * @param array                    $query_params
2622
+	 * @return int how many deleted
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
+	{
2627
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2628
+		$relation_settings = $this->related_settings_for($model_name);
2629
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2630
+	}
2631
+
2632
+
2633
+
2634
+	/**
2635
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2636
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
+	 * the model objects can't be hard deleted because of blocking related model objects,
2638
+	 * just does a soft-delete on them instead.
2639
+	 *
2640
+	 * @param EE_Base_Class|int|string $id_or_obj
2641
+	 * @param string                   $model_name
2642
+	 * @param array                    $query_params
2643
+	 * @return int how many deleted
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
+	{
2648
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2649
+		$relation_settings = $this->related_settings_for($model_name);
2650
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
+	}
2652
+
2653
+
2654
+
2655
+	/**
2656
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
+	 * unless otherwise specified in the $query_params
2658
+	 *
2659
+	 * @param        int             /EE_Base_Class $id_or_obj
2660
+	 * @param string $model_name     like 'Event', or 'Registration'
2661
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2663
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
+	 *                               that by the setting $distinct to TRUE;
2665
+	 * @return int
2666
+	 * @throws EE_Error
2667
+	 */
2668
+	public function count_related(
2669
+		$id_or_obj,
2670
+		$model_name,
2671
+		$query_params = array(),
2672
+		$field_to_count = null,
2673
+		$distinct = false
2674
+	) {
2675
+		$related_model = $this->get_related_model_obj($model_name);
2676
+		// we're just going to use the query params on the related model's normal get_all query,
2677
+		// except add a condition to say to match the current mod
2678
+		if (! isset($query_params['default_where_conditions'])) {
2679
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
+		}
2681
+		$this_model_name = $this->get_this_model_name();
2682
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
+		return $related_model->count($query_params, $field_to_count, $distinct);
2685
+	}
2686
+
2687
+
2688
+
2689
+	/**
2690
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
+	 *
2693
+	 * @param        int           /EE_Base_Class $id_or_obj
2694
+	 * @param string $model_name   like 'Event', or 'Registration'
2695
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
+	 * @return float
2698
+	 * @throws EE_Error
2699
+	 */
2700
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
+	{
2702
+		$related_model = $this->get_related_model_obj($model_name);
2703
+		if (! is_array($query_params)) {
2704
+			EE_Error::doing_it_wrong(
2705
+				'EEM_Base::sum_related',
2706
+				sprintf(
2707
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
+					gettype($query_params)
2709
+				),
2710
+				'4.6.0'
2711
+			);
2712
+			$query_params = array();
2713
+		}
2714
+		// we're just going to use the query params on the related model's normal get_all query,
2715
+		// except add a condition to say to match the current mod
2716
+		if (! isset($query_params['default_where_conditions'])) {
2717
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
+		}
2719
+		$this_model_name = $this->get_this_model_name();
2720
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
+		return $related_model->sum($query_params, $field_to_sum);
2723
+	}
2724
+
2725
+
2726
+
2727
+	/**
2728
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
+	 * $modelObject
2730
+	 *
2731
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
+	 * @return EE_Base_Class
2735
+	 * @throws EE_Error
2736
+	 */
2737
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
+	{
2739
+		$query_params['limit'] = 1;
2740
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
+		if ($results) {
2742
+			return array_shift($results);
2743
+		}
2744
+		return null;
2745
+	}
2746
+
2747
+
2748
+
2749
+	/**
2750
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
+	 *
2752
+	 * @return string
2753
+	 */
2754
+	public function get_this_model_name()
2755
+	{
2756
+		return str_replace("EEM_", "", get_class($this));
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
+	 *
2764
+	 * @return EE_Any_Foreign_Model_Name_Field
2765
+	 * @throws EE_Error
2766
+	 */
2767
+	public function get_field_containing_related_model_name()
2768
+	{
2769
+		foreach ($this->field_settings(true) as $field) {
2770
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
+				$field_with_model_name = $field;
2772
+			}
2773
+		}
2774
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
+			throw new EE_Error(sprintf(
2776
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
+				$this->get_this_model_name()
2778
+			));
2779
+		}
2780
+		return $field_with_model_name;
2781
+	}
2782
+
2783
+
2784
+
2785
+	/**
2786
+	 * Inserts a new entry into the database, for each table.
2787
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
+	 *
2794
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
+	 *                              of EEM_Base)
2798
+	 * @return int|string new primary key on main table that got inserted
2799
+	 * @throws EE_Error
2800
+	 */
2801
+	public function insert($field_n_values)
2802
+	{
2803
+		/**
2804
+		 * Filters the fields and their values before inserting an item using the models
2805
+		 *
2806
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2807
+		 * @param EEM_Base $model           the model used
2808
+		 */
2809
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
+			$main_table = $this->_get_main_table();
2812
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
+			if ($new_id !== false) {
2814
+				foreach ($this->_get_other_tables() as $other_table) {
2815
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
+				}
2817
+			}
2818
+			/**
2819
+			 * Done just after attempting to insert a new model object
2820
+			 *
2821
+			 * @param EEM_Base   $model           used
2822
+			 * @param array      $fields_n_values fields and their values
2823
+			 * @param int|string the              ID of the newly-inserted model object
2824
+			 */
2825
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
+			return $new_id;
2827
+		}
2828
+		return false;
2829
+	}
2830
+
2831
+
2832
+
2833
+	/**
2834
+	 * Checks that the result would satisfy the unique indexes on this model
2835
+	 *
2836
+	 * @param array  $field_n_values
2837
+	 * @param string $action
2838
+	 * @return boolean
2839
+	 * @throws EE_Error
2840
+	 */
2841
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
+	{
2843
+		foreach ($this->unique_indexes() as $index_name => $index) {
2844
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
+			if ($this->exists(array($uniqueness_where_params))) {
2846
+				EE_Error::add_error(
2847
+					sprintf(
2848
+						esc_html__(
2849
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
+							"event_espresso"
2851
+						),
2852
+						$action,
2853
+						$this->_get_class_name(),
2854
+						$index_name,
2855
+						implode(",", $index->field_names()),
2856
+						http_build_query($uniqueness_where_params)
2857
+					),
2858
+					__FILE__,
2859
+					__FUNCTION__,
2860
+					__LINE__
2861
+				);
2862
+				return false;
2863
+			}
2864
+		}
2865
+		return true;
2866
+	}
2867
+
2868
+
2869
+
2870
+	/**
2871
+	 * Checks the database for an item that conflicts (ie, if this item were
2872
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2873
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
+	 * can be either an EE_Base_Class or an array of fields n values
2875
+	 *
2876
+	 * @param EE_Base_Class|array $obj_or_fields_array
2877
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2878
+	 *                                                 when looking for conflicts
2879
+	 *                                                 (ie, if false, we ignore the model object's primary key
2880
+	 *                                                 when finding "conflicts". If true, it's also considered).
2881
+	 *                                                 Only works for INT primary key,
2882
+	 *                                                 STRING primary keys cannot be ignored
2883
+	 * @throws EE_Error
2884
+	 * @return EE_Base_Class|array
2885
+	 */
2886
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
+	{
2888
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2890
+		} elseif (is_array($obj_or_fields_array)) {
2891
+			$fields_n_values = $obj_or_fields_array;
2892
+		} else {
2893
+			throw new EE_Error(
2894
+				sprintf(
2895
+					esc_html__(
2896
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
+						"event_espresso"
2898
+					),
2899
+					get_class($this),
2900
+					$obj_or_fields_array
2901
+				)
2902
+			);
2903
+		}
2904
+		$query_params = array();
2905
+		if (
2906
+			$this->has_primary_key_field()
2907
+			&& ($include_primary_key
2908
+				|| $this->get_primary_key_field()
2909
+				   instanceof
2910
+				   EE_Primary_Key_String_Field)
2911
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2912
+		) {
2913
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
+		}
2915
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
+		}
2919
+		// if there is nothing to base this search on, then we shouldn't find anything
2920
+		if (empty($query_params)) {
2921
+			return array();
2922
+		}
2923
+		return $this->get_one($query_params);
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Like count, but is optimized and returns a boolean instead of an int
2930
+	 *
2931
+	 * @param array $query_params
2932
+	 * @return boolean
2933
+	 * @throws EE_Error
2934
+	 */
2935
+	public function exists($query_params)
2936
+	{
2937
+		$query_params['limit'] = 1;
2938
+		return $this->count($query_params) > 0;
2939
+	}
2940
+
2941
+
2942
+
2943
+	/**
2944
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
+	 *
2946
+	 * @param int|string $id
2947
+	 * @return boolean
2948
+	 * @throws EE_Error
2949
+	 */
2950
+	public function exists_by_ID($id)
2951
+	{
2952
+		return $this->exists(
2953
+			array(
2954
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
+				array(
2956
+					$this->primary_key_name() => $id,
2957
+				),
2958
+			)
2959
+		);
2960
+	}
2961
+
2962
+
2963
+
2964
+	/**
2965
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
+	 * on the main table)
2969
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
+	 * cases where we want to call it directly rather than via insert().
2971
+	 *
2972
+	 * @access   protected
2973
+	 * @param EE_Table_Base $table
2974
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
+	 *                                       float
2976
+	 * @param int           $new_id          for now we assume only int keys
2977
+	 * @throws EE_Error
2978
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
+	 * @return int ID of new row inserted, or FALSE on failure
2980
+	 */
2981
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
+	{
2983
+		global $wpdb;
2984
+		$insertion_col_n_values = array();
2985
+		$format_for_insertion = array();
2986
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
+		foreach ($fields_on_table as $field_name => $field_obj) {
2988
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
+			if ($field_obj->is_auto_increment()) {
2990
+				continue;
2991
+			}
2992
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
+			if ($prepared_value !== null) {
2995
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
+			}
2998
+		}
2999
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3000
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3001
+			// so add the fk to the main table as a column
3002
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+		}
3005
+		// insert the new entry
3006
+		$result = $this->_do_wpdb_query(
3007
+			'insert',
3008
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
+		);
3010
+		if ($result === false) {
3011
+			return false;
3012
+		}
3013
+		// ok, now what do we return for the ID of the newly-inserted thing?
3014
+		if ($this->has_primary_key_field()) {
3015
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3016
+				return $wpdb->insert_id;
3017
+			}
3018
+			// it's not an auto-increment primary key, so
3019
+			// it must have been supplied
3020
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
+		}
3022
+		// we can't return a  primary key because there is none. instead return
3023
+		// a unique string indicating this model
3024
+		return $this->get_index_primary_key_string($fields_n_values);
3025
+	}
3026
+
3027
+
3028
+
3029
+	/**
3030
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
+	 * and there is no default, we pass it along. WPDB will take care of it)
3033
+	 *
3034
+	 * @param EE_Model_Field_Base $field_obj
3035
+	 * @param array               $fields_n_values
3036
+	 * @return mixed string|int|float depending on what the table column will be expecting
3037
+	 * @throws EE_Error
3038
+	 */
3039
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
+	{
3041
+		// if this field doesn't allow nullable, don't allow it
3042
+		if (
3043
+			! $field_obj->is_nullable()
3044
+			&& (
3045
+				! isset($fields_n_values[ $field_obj->get_name() ])
3046
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3047
+			)
3048
+		) {
3049
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
+		}
3051
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
+			? $fields_n_values[ $field_obj->get_name() ]
3053
+			: null;
3054
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
+	 * the field's prepare_for_set() method.
3063
+	 *
3064
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
+	 *                                   top of file)
3067
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
+	 *                                   $value is a custom selection
3069
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
+	 */
3071
+	private function _prepare_value_for_use_in_db($value, $field)
3072
+	{
3073
+		if ($field && $field instanceof EE_Model_Field_Base) {
3074
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
+			switch ($this->_values_already_prepared_by_model_object) {
3076
+				/** @noinspection PhpMissingBreakStatementInspection */
3077
+				case self::not_prepared_by_model_object:
3078
+					$value = $field->prepare_for_set($value);
3079
+				// purposefully left out "return"
3080
+				case self::prepared_by_model_object:
3081
+					/** @noinspection SuspiciousAssignmentsInspection */
3082
+					$value = $field->prepare_for_use_in_db($value);
3083
+				case self::prepared_for_use_in_db:
3084
+					// leave the value alone
3085
+			}
3086
+			return $value;
3087
+			// phpcs:enable
3088
+		}
3089
+		return $value;
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Returns the main table on this model
3096
+	 *
3097
+	 * @return EE_Primary_Table
3098
+	 * @throws EE_Error
3099
+	 */
3100
+	protected function _get_main_table()
3101
+	{
3102
+		foreach ($this->_tables as $table) {
3103
+			if ($table instanceof EE_Primary_Table) {
3104
+				return $table;
3105
+			}
3106
+		}
3107
+		throw new EE_Error(sprintf(esc_html__(
3108
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
+			'event_espresso'
3110
+		), get_class($this)));
3111
+	}
3112
+
3113
+
3114
+
3115
+	/**
3116
+	 * table
3117
+	 * returns EE_Primary_Table table name
3118
+	 *
3119
+	 * @return string
3120
+	 * @throws EE_Error
3121
+	 */
3122
+	public function table()
3123
+	{
3124
+		return $this->_get_main_table()->get_table_name();
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * table
3131
+	 * returns first EE_Secondary_Table table name
3132
+	 *
3133
+	 * @return string
3134
+	 */
3135
+	public function second_table()
3136
+	{
3137
+		// grab second table from tables array
3138
+		$second_table = end($this->_tables);
3139
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
+	}
3141
+
3142
+
3143
+
3144
+	/**
3145
+	 * get_table_obj_by_alias
3146
+	 * returns table name given it's alias
3147
+	 *
3148
+	 * @param string $table_alias
3149
+	 * @return EE_Primary_Table | EE_Secondary_Table
3150
+	 */
3151
+	public function get_table_obj_by_alias($table_alias = '')
3152
+	{
3153
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
+	 *
3161
+	 * @return EE_Secondary_Table[]
3162
+	 */
3163
+	protected function _get_other_tables()
3164
+	{
3165
+		$other_tables = array();
3166
+		foreach ($this->_tables as $table_alias => $table) {
3167
+			if ($table instanceof EE_Secondary_Table) {
3168
+				$other_tables[ $table_alias ] = $table;
3169
+			}
3170
+		}
3171
+		return $other_tables;
3172
+	}
3173
+
3174
+
3175
+
3176
+	/**
3177
+	 * Finds all the fields that correspond to the given table
3178
+	 *
3179
+	 * @param string $table_alias , array key in EEM_Base::_tables
3180
+	 * @return EE_Model_Field_Base[]
3181
+	 */
3182
+	public function _get_fields_for_table($table_alias)
3183
+	{
3184
+		return $this->_fields[ $table_alias ];
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3191
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
+	 * related Registration, Transaction, and Payment models.
3195
+	 *
3196
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
+	 * @return EE_Model_Query_Info_Carrier
3198
+	 * @throws EE_Error
3199
+	 */
3200
+	public function _extract_related_models_from_query($query_params)
3201
+	{
3202
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
+		if (array_key_exists(0, $query_params)) {
3204
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
+		}
3206
+		if (array_key_exists('group_by', $query_params)) {
3207
+			if (is_array($query_params['group_by'])) {
3208
+				$this->_extract_related_models_from_sub_params_array_values(
3209
+					$query_params['group_by'],
3210
+					$query_info_carrier,
3211
+					'group_by'
3212
+				);
3213
+			} elseif (! empty($query_params['group_by'])) {
3214
+				$this->_extract_related_model_info_from_query_param(
3215
+					$query_params['group_by'],
3216
+					$query_info_carrier,
3217
+					'group_by'
3218
+				);
3219
+			}
3220
+		}
3221
+		if (array_key_exists('having', $query_params)) {
3222
+			$this->_extract_related_models_from_sub_params_array_keys(
3223
+				$query_params[0],
3224
+				$query_info_carrier,
3225
+				'having'
3226
+			);
3227
+		}
3228
+		if (array_key_exists('order_by', $query_params)) {
3229
+			if (is_array($query_params['order_by'])) {
3230
+				$this->_extract_related_models_from_sub_params_array_keys(
3231
+					$query_params['order_by'],
3232
+					$query_info_carrier,
3233
+					'order_by'
3234
+				);
3235
+			} elseif (! empty($query_params['order_by'])) {
3236
+				$this->_extract_related_model_info_from_query_param(
3237
+					$query_params['order_by'],
3238
+					$query_info_carrier,
3239
+					'order_by'
3240
+				);
3241
+			}
3242
+		}
3243
+		if (array_key_exists('force_join', $query_params)) {
3244
+			$this->_extract_related_models_from_sub_params_array_values(
3245
+				$query_params['force_join'],
3246
+				$query_info_carrier,
3247
+				'force_join'
3248
+			);
3249
+		}
3250
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
+		return $query_info_carrier;
3252
+	}
3253
+
3254
+
3255
+
3256
+	/**
3257
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
+	 *
3259
+	 * @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
3260
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3262
+	 * @throws EE_Error
3263
+	 * @return \EE_Model_Query_Info_Carrier
3264
+	 */
3265
+	private function _extract_related_models_from_sub_params_array_keys(
3266
+		$sub_query_params,
3267
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
+		$query_param_type
3269
+	) {
3270
+		if (! empty($sub_query_params)) {
3271
+			$sub_query_params = (array) $sub_query_params;
3272
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
+				$this->_extract_related_model_info_from_query_param(
3275
+					$param,
3276
+					$model_query_info_carrier,
3277
+					$query_param_type
3278
+				);
3279
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
+				// of array('Registration.TXN_ID'=>23)
3283
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
+					if (! is_array($possibly_array_of_params)) {
3286
+						throw new EE_Error(sprintf(
3287
+							esc_html__(
3288
+								"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'))",
3289
+								"event_espresso"
3290
+							),
3291
+							$param,
3292
+							$possibly_array_of_params
3293
+						));
3294
+					}
3295
+					$this->_extract_related_models_from_sub_params_array_keys(
3296
+						$possibly_array_of_params,
3297
+						$model_query_info_carrier,
3298
+						$query_param_type
3299
+					);
3300
+				} elseif (
3301
+					$query_param_type === 0 // ie WHERE
3302
+						  && is_array($possibly_array_of_params)
3303
+						  && isset($possibly_array_of_params[2])
3304
+						  && $possibly_array_of_params[2] == true
3305
+				) {
3306
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
+					// indicating that $possible_array_of_params[1] is actually a field name,
3308
+					// from which we should extract query parameters!
3309
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
+						throw new EE_Error(sprintf(esc_html__(
3311
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
+							"event_espresso"
3313
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3314
+					}
3315
+					$this->_extract_related_model_info_from_query_param(
3316
+						$possibly_array_of_params[1],
3317
+						$model_query_info_carrier,
3318
+						$query_param_type
3319
+					);
3320
+				}
3321
+			}
3322
+		}
3323
+		return $model_query_info_carrier;
3324
+	}
3325
+
3326
+
3327
+
3328
+	/**
3329
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3330
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
+	 *
3332
+	 * @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
3333
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3335
+	 * @throws EE_Error
3336
+	 * @return \EE_Model_Query_Info_Carrier
3337
+	 */
3338
+	private function _extract_related_models_from_sub_params_array_values(
3339
+		$sub_query_params,
3340
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
+		$query_param_type
3342
+	) {
3343
+		if (! empty($sub_query_params)) {
3344
+			if (! is_array($sub_query_params)) {
3345
+				throw new EE_Error(sprintf(
3346
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
+					$sub_query_params
3348
+				));
3349
+			}
3350
+			foreach ($sub_query_params as $param) {
3351
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
+				$this->_extract_related_model_info_from_query_param(
3353
+					$param,
3354
+					$model_query_info_carrier,
3355
+					$query_param_type
3356
+				);
3357
+			}
3358
+		}
3359
+		return $model_query_info_carrier;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Extract all the query parts from  model query params
3365
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
+	 * but use them in a different order. Eg, we need to know what models we are querying
3368
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
+	 * other models before we can finalize the where clause SQL.
3370
+	 *
3371
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
+	 * @throws EE_Error
3373
+	 * @return EE_Model_Query_Info_Carrier
3374
+	 * @throws ModelConfigurationException
3375
+	 */
3376
+	public function _create_model_query_info_carrier($query_params)
3377
+	{
3378
+		if (! is_array($query_params)) {
3379
+			EE_Error::doing_it_wrong(
3380
+				'EEM_Base::_create_model_query_info_carrier',
3381
+				sprintf(
3382
+					esc_html__(
3383
+						'$query_params should be an array, you passed a variable of type %s',
3384
+						'event_espresso'
3385
+					),
3386
+					gettype($query_params)
3387
+				),
3388
+				'4.6.0'
3389
+			);
3390
+			$query_params = array();
3391
+		}
3392
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
+		// first check if we should alter the query to account for caps or not
3394
+		// because the caps might require us to do extra joins
3395
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
+			$query_params[0] = array_replace_recursive(
3397
+				$query_params[0],
3398
+				$this->caps_where_conditions(
3399
+					$query_params['caps']
3400
+				)
3401
+			);
3402
+		}
3403
+
3404
+		// check if we should alter the query to remove data related to protected
3405
+		// custom post types
3406
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
+			$where_param_key_for_password = $this->modelChainAndPassword();
3408
+			// only include if related to a cpt where no password has been set
3409
+			$query_params[0]['OR*nopassword'] = array(
3410
+				$where_param_key_for_password => '',
3411
+				$where_param_key_for_password . '*' => array('IS_NULL')
3412
+			);
3413
+		}
3414
+		$query_object = $this->_extract_related_models_from_query($query_params);
3415
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
+		foreach ($query_params[0] as $key => $value) {
3417
+			if (is_int($key)) {
3418
+				throw new EE_Error(
3419
+					sprintf(
3420
+						esc_html__(
3421
+							"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.",
3422
+							"event_espresso"
3423
+						),
3424
+						$key,
3425
+						var_export($value, true),
3426
+						var_export($query_params, true),
3427
+						get_class($this)
3428
+					)
3429
+				);
3430
+			}
3431
+		}
3432
+		if (
3433
+			array_key_exists('default_where_conditions', $query_params)
3434
+			&& ! empty($query_params['default_where_conditions'])
3435
+		) {
3436
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3437
+		} else {
3438
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
+		}
3440
+		$query_params[0] = array_merge(
3441
+			$this->_get_default_where_conditions_for_models_in_query(
3442
+				$query_object,
3443
+				$use_default_where_conditions,
3444
+				$query_params[0]
3445
+			),
3446
+			$query_params[0]
3447
+		);
3448
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
+		// So we need to setup a subquery and use that for the main join.
3451
+		// Note for now this only works on the primary table for the model.
3452
+		// So for instance, you could set the limit array like this:
3453
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
+			$query_object->set_main_model_join_sql(
3456
+				$this->_construct_limit_join_select(
3457
+					$query_params['on_join_limit'][0],
3458
+					$query_params['on_join_limit'][1]
3459
+				)
3460
+			);
3461
+		}
3462
+		// set limit
3463
+		if (array_key_exists('limit', $query_params)) {
3464
+			if (is_array($query_params['limit'])) {
3465
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
+					$e = sprintf(
3467
+						esc_html__(
3468
+							"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)",
3469
+							"event_espresso"
3470
+						),
3471
+						http_build_query($query_params['limit'])
3472
+					);
3473
+					throw new EE_Error($e . "|" . $e);
3474
+				}
3475
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
+			} elseif (! empty($query_params['limit'])) {
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
+			}
3480
+		}
3481
+		// set order by
3482
+		if (array_key_exists('order_by', $query_params)) {
3483
+			if (is_array($query_params['order_by'])) {
3484
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
+				if (array_key_exists('order', $query_params)) {
3488
+					throw new EE_Error(
3489
+						sprintf(
3490
+							esc_html__(
3491
+								"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 ",
3492
+								"event_espresso"
3493
+							),
3494
+							get_class($this),
3495
+							implode(", ", array_keys($query_params['order_by'])),
3496
+							implode(", ", $query_params['order_by']),
3497
+							$query_params['order']
3498
+						)
3499
+					);
3500
+				}
3501
+				$this->_extract_related_models_from_sub_params_array_keys(
3502
+					$query_params['order_by'],
3503
+					$query_object,
3504
+					'order_by'
3505
+				);
3506
+				// assume it's an array of fields to order by
3507
+				$order_array = array();
3508
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
+					$order = $this->_extract_order($order);
3510
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
+				}
3512
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
+			} elseif (! empty($query_params['order_by'])) {
3514
+				$this->_extract_related_model_info_from_query_param(
3515
+					$query_params['order_by'],
3516
+					$query_object,
3517
+					'order',
3518
+					$query_params['order_by']
3519
+				);
3520
+				$order = isset($query_params['order'])
3521
+					? $this->_extract_order($query_params['order'])
3522
+					: 'DESC';
3523
+				$query_object->set_order_by_sql(
3524
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
+				);
3526
+			}
3527
+		}
3528
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
+		if (
3530
+			! array_key_exists('order_by', $query_params)
3531
+			&& array_key_exists('order', $query_params)
3532
+			&& ! empty($query_params['order'])
3533
+		) {
3534
+			$pk_field = $this->get_primary_key_field();
3535
+			$order = $this->_extract_order($query_params['order']);
3536
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
+		}
3538
+		// set group by
3539
+		if (array_key_exists('group_by', $query_params)) {
3540
+			if (is_array($query_params['group_by'])) {
3541
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3542
+				$group_by_array = array();
3543
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
+				}
3546
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
+			} elseif (! empty($query_params['group_by'])) {
3548
+				$query_object->set_group_by_sql(
3549
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
+				);
3551
+			}
3552
+		}
3553
+		// set having
3554
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
+		}
3557
+		// now, just verify they didn't pass anything wack
3558
+		foreach ($query_params as $query_key => $query_value) {
3559
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
+				throw new EE_Error(
3561
+					sprintf(
3562
+						esc_html__(
3563
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
+							'event_espresso'
3565
+						),
3566
+						$query_key,
3567
+						get_class($this),
3568
+						//                      print_r( $this->_allowed_query_params, TRUE )
3569
+						implode(',', $this->_allowed_query_params)
3570
+					)
3571
+				);
3572
+			}
3573
+		}
3574
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3575
+		if (empty($main_model_join_sql)) {
3576
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
+		}
3578
+		return $query_object;
3579
+	}
3580
+
3581
+
3582
+
3583
+	/**
3584
+	 * Gets the where conditions that should be imposed on the query based on the
3585
+	 * context (eg reading frontend, backend, edit or delete).
3586
+	 *
3587
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3588
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
+	 * @throws EE_Error
3590
+	 */
3591
+	public function caps_where_conditions($context = self::caps_read)
3592
+	{
3593
+		EEM_Base::verify_is_valid_cap_context($context);
3594
+		$cap_where_conditions = array();
3595
+		$cap_restrictions = $this->caps_missing($context);
3596
+		/**
3597
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
+		 */
3599
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
+			$cap_where_conditions = array_replace_recursive(
3601
+				$cap_where_conditions,
3602
+				$restriction_if_no_cap->get_default_where_conditions()
3603
+			);
3604
+		}
3605
+		return apply_filters(
3606
+			'FHEE__EEM_Base__caps_where_conditions__return',
3607
+			$cap_where_conditions,
3608
+			$this,
3609
+			$context,
3610
+			$cap_restrictions
3611
+		);
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
+	 * otherwise throws an exception
3619
+	 *
3620
+	 * @param string $should_be_order_string
3621
+	 * @return string either ASC, asc, DESC or desc
3622
+	 * @throws EE_Error
3623
+	 */
3624
+	private function _extract_order($should_be_order_string)
3625
+	{
3626
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
+			return $should_be_order_string;
3628
+		}
3629
+		throw new EE_Error(
3630
+			sprintf(
3631
+				esc_html__(
3632
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
+					"event_espresso"
3634
+				),
3635
+				get_class($this),
3636
+				$should_be_order_string
3637
+			)
3638
+		);
3639
+	}
3640
+
3641
+
3642
+
3643
+	/**
3644
+	 * Looks at all the models which are included in this query, and asks each
3645
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
+	 * so they can be merged
3647
+	 *
3648
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
+	 *                                                                  'none' means NO default where conditions will
3651
+	 *                                                                  be used AT ALL during this query.
3652
+	 *                                                                  'other_models_only' means default where
3653
+	 *                                                                  conditions from other models will be used, but
3654
+	 *                                                                  not for this primary model. 'all', the default,
3655
+	 *                                                                  means default where conditions will apply as
3656
+	 *                                                                  normal
3657
+	 * @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
3658
+	 * @throws EE_Error
3659
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
+	 */
3661
+	private function _get_default_where_conditions_for_models_in_query(
3662
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3663
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
+		$where_query_params = array()
3665
+	) {
3666
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
+			throw new EE_Error(sprintf(
3669
+				esc_html__(
3670
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
+					"event_espresso"
3672
+				),
3673
+				$use_default_where_conditions,
3674
+				implode(", ", $allowed_used_default_where_conditions_values)
3675
+			));
3676
+		}
3677
+		$universal_query_params = array();
3678
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
+			$universal_query_params = $this->_get_default_where_conditions();
3680
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_minimum_where_conditions();
3682
+		}
3683
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
+			$related_model = $this->get_related_model_obj($model_name);
3685
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
+			} else {
3690
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3691
+				continue;
3692
+			}
3693
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3694
+				$related_model_universal_where_params,
3695
+				$where_query_params,
3696
+				$related_model,
3697
+				$model_relation_path
3698
+			);
3699
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
+				$universal_query_params,
3701
+				$overrides
3702
+			);
3703
+		}
3704
+		return $universal_query_params;
3705
+	}
3706
+
3707
+
3708
+
3709
+	/**
3710
+	 * Determines whether or not we should use default where conditions for the model in question
3711
+	 * (this model, or other related models).
3712
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
+	 * We should use default where conditions on related models when they requested to use default where conditions
3715
+	 * on all models, or specifically just on other related models
3716
+	 * @param      $default_where_conditions_value
3717
+	 * @param bool $for_this_model false means this is for OTHER related models
3718
+	 * @return bool
3719
+	 */
3720
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
+	{
3722
+		return (
3723
+				   $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_all,
3728
+						   EEM_Base::default_where_conditions_this_only,
3729
+						   EEM_Base::default_where_conditions_minimum_others,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   )
3734
+			   || (
3735
+				   ! $for_this_model
3736
+				   && in_array(
3737
+					   $default_where_conditions_value,
3738
+					   array(
3739
+						   EEM_Base::default_where_conditions_all,
3740
+						   EEM_Base::default_where_conditions_others_only,
3741
+					   ),
3742
+					   true
3743
+				   )
3744
+			   );
3745
+	}
3746
+
3747
+	/**
3748
+	 * Determines whether or not we should use default minimum conditions for the model in question
3749
+	 * (this model, or other related models).
3750
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
+	 * where conditions.
3752
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
+	 * on this model or others
3754
+	 * @param      $default_where_conditions_value
3755
+	 * @param bool $for_this_model false means this is for OTHER related models
3756
+	 * @return bool
3757
+	 */
3758
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
+	{
3760
+		return (
3761
+				   $for_this_model
3762
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
+			   )
3764
+			   || (
3765
+				   ! $for_this_model
3766
+				   && in_array(
3767
+					   $default_where_conditions_value,
3768
+					   array(
3769
+						   EEM_Base::default_where_conditions_minimum_others,
3770
+						   EEM_Base::default_where_conditions_minimum_all,
3771
+					   ),
3772
+					   true
3773
+				   )
3774
+			   );
3775
+	}
3776
+
3777
+
3778
+	/**
3779
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
+	 * then we also add a special where condition which allows for that model's primary key
3781
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
+	 *
3784
+	 * @param array    $default_where_conditions
3785
+	 * @param array    $provided_where_conditions
3786
+	 * @param EEM_Base $model
3787
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3788
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
+	 * @throws EE_Error
3790
+	 */
3791
+	private function _override_defaults_or_make_null_friendly(
3792
+		$default_where_conditions,
3793
+		$provided_where_conditions,
3794
+		$model,
3795
+		$model_relation_path
3796
+	) {
3797
+		$null_friendly_where_conditions = array();
3798
+		$none_overridden = true;
3799
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
+		foreach ($default_where_conditions as $key => $val) {
3801
+			if (isset($provided_where_conditions[ $key ])) {
3802
+				$none_overridden = false;
3803
+			} else {
3804
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
+			}
3806
+		}
3807
+		if ($none_overridden && $default_where_conditions) {
3808
+			if ($model->has_primary_key_field()) {
3809
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
+																				. "."
3811
+																				. $model->primary_key_name() ] = array('IS NULL');
3812
+			}/*else{
3813 3813
                 //@todo NO PK, use other defaults
3814 3814
             }*/
3815
-        }
3816
-        return $null_friendly_where_conditions;
3817
-    }
3818
-
3819
-
3820
-
3821
-    /**
3822
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3823
-     * default where conditions on all get_all, update, and delete queries done by this model.
3824
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3826
-     *
3827
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
-     */
3830
-    private function _get_default_where_conditions($model_relation_path = null)
3831
-    {
3832
-        if ($this->_ignore_where_strategy) {
3833
-            return array();
3834
-        }
3835
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
-    }
3837
-
3838
-
3839
-
3840
-    /**
3841
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3845
-     * Similar to _get_default_where_conditions
3846
-     *
3847
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
-     */
3850
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3851
-    {
3852
-        if ($this->_ignore_where_strategy) {
3853
-            return array();
3854
-        }
3855
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
-    }
3857
-
3858
-
3859
-
3860
-    /**
3861
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
-     *
3864
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3865
-     * @return string
3866
-     * @throws EE_Error
3867
-     */
3868
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
-    {
3870
-        $selects = $this->_get_columns_to_select_for_this_model();
3871
-        foreach (
3872
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
-        ) {
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
-                    esc_html__(
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
-                    esc_html__(
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(esc_html__(
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
-                esc_html__(
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
-                        esc_html__(
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
-                        esc_html__(
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
-                        esc_html__(
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
-                    esc_html__(
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
-                    esc_html__(
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
-                esc_html__(
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
-     * Takes an array or a comma-separated list of $values and cleans them
4497
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4498
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
-     *
4502
-     * @param mixed                      $values    array or comma-separated string
4503
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
-     * @throws EE_Error
4506
-     */
4507
-    public function _construct_in_value($values, $field_obj)
4508
-    {
4509
-        $prepped = [];
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
-        // make sure we only have one of each value in the list
4516
-        $values = array_unique($values);
4517
-        foreach ($values as $value) {
4518
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
-        }
4520
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
-        if (empty($prepped)) {
4524
-            $all_fields = $this->field_settings();
4525
-            $first_field    = reset($all_fields);
4526
-            $main_table = $this->_get_main_table();
4527
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
-        }
4529
-        return '(' . implode(',', $prepped) . ')';
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * @param mixed                      $value
4536
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
-     * @throws EE_Error
4538
-     * @return false|null|string
4539
-     */
4540
-    private function _wpdb_prepare_using_field($value, $field_obj)
4541
-    {
4542
-        /** @type WPDB $wpdb */
4543
-        global $wpdb;
4544
-        if ($field_obj instanceof EE_Model_Field_Base) {
4545
-            return $wpdb->prepare(
4546
-                $field_obj->get_wpdb_data_type(),
4547
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4548
-            );
4549
-        } //$field_obj should really just be a data type
4550
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
-            throw new EE_Error(
4552
-                sprintf(
4553
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
-                    $field_obj,
4555
-                    implode(",", $this->_valid_wpdb_data_types)
4556
-                )
4557
-            );
4558
-        }
4559
-        return $wpdb->prepare($field_obj, $value);
4560
-    }
4561
-
4562
-
4563
-
4564
-    /**
4565
-     * Takes the input parameter and finds the model field that it indicates.
4566
-     *
4567
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
-     * @throws EE_Error
4569
-     * @return EE_Model_Field_Base
4570
-     */
4571
-    protected function _deduce_field_from_query_param($query_param_name)
4572
-    {
4573
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
-        // which will help us find the database table and column
4575
-        $query_param_parts = explode(".", $query_param_name);
4576
-        if (empty($query_param_parts)) {
4577
-            throw new EE_Error(sprintf(esc_html__(
4578
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4579
-                'event_espresso'
4580
-            ), $query_param_name));
4581
-        }
4582
-        $number_of_parts = count($query_param_parts);
4583
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
-        if ($number_of_parts === 1) {
4585
-            $field_name = $last_query_param_part;
4586
-            $model_obj = $this;
4587
-        } else {// $number_of_parts >= 2
4588
-            // the last part is the column name, and there are only 2parts. therefore...
4589
-            $field_name = $last_query_param_part;
4590
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
-        }
4592
-        try {
4593
-            return $model_obj->field_settings_for($field_name);
4594
-        } catch (EE_Error $e) {
4595
-            return null;
4596
-        }
4597
-    }
4598
-
4599
-
4600
-
4601
-    /**
4602
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
-     * alias and column which corresponds to it
4604
-     *
4605
-     * @param string $field_name
4606
-     * @throws EE_Error
4607
-     * @return string
4608
-     */
4609
-    public function _get_qualified_column_for_field($field_name)
4610
-    {
4611
-        $all_fields = $this->field_settings();
4612
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
-        if ($field) {
4614
-            return $field->get_qualified_column();
4615
-        }
4616
-        throw new EE_Error(
4617
-            sprintf(
4618
-                esc_html__(
4619
-                    "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.",
4620
-                    'event_espresso'
4621
-                ),
4622
-                $field_name,
4623
-                get_class($this)
4624
-            )
4625
-        );
4626
-    }
4627
-
4628
-
4629
-
4630
-    /**
4631
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
-     * Example usage:
4633
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4634
-     *      array(),
4635
-     *      ARRAY_A,
4636
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
-     *  );
4638
-     * is equivalent to
4639
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
-     * and
4641
-     *  EEM_Event::instance()->get_all_wpdb_results(
4642
-     *      array(
4643
-     *          array(
4644
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
-     *          ),
4646
-     *          ARRAY_A,
4647
-     *          implode(
4648
-     *              ', ',
4649
-     *              array_merge(
4650
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
-     *              )
4653
-     *          )
4654
-     *      )
4655
-     *  );
4656
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
-     *
4658
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
-     *                                            and the one whose fields you are selecting for example: when querying
4660
-     *                                            tickets model and selecting fields from the tickets model you would
4661
-     *                                            leave this parameter empty, because no models are needed to join
4662
-     *                                            between the queried model and the selected one. Likewise when
4663
-     *                                            querying the datetime model and selecting fields from the tickets
4664
-     *                                            model, it would also be left empty, because there is a direct
4665
-     *                                            relation from datetimes to tickets, so no model is needed to join
4666
-     *                                            them together. However, when querying from the event model and
4667
-     *                                            selecting fields from the ticket model, you should provide the string
4668
-     *                                            'Datetime', indicating that the event model must first join to the
4669
-     *                                            datetime model in order to find its relation to ticket model.
4670
-     *                                            Also, when querying from the venue model and selecting fields from
4671
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
-     *                                            indicating you need to join the venue model to the event model,
4673
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4674
-     *                                            This string is used to deduce the prefix that gets added onto the
4675
-     *                                            models' tables qualified columns
4676
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4678
-     *                                            qualified column names
4679
-     * @return array|string
4680
-     */
4681
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
-    {
4683
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
-        $qualified_columns = array();
4685
-        foreach ($this->field_settings() as $field_name => $field) {
4686
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
-        }
4688
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
-    }
4690
-
4691
-
4692
-
4693
-    /**
4694
-     * constructs the select use on special limit joins
4695
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
-     * (as that is typically where the limits would be set).
4698
-     *
4699
-     * @param  string       $table_alias The table the select is being built for
4700
-     * @param  mixed|string $limit       The limit for this select
4701
-     * @return string                The final select join element for the query.
4702
-     */
4703
-    public function _construct_limit_join_select($table_alias, $limit)
4704
-    {
4705
-        $SQL = '';
4706
-        foreach ($this->_tables as $table_obj) {
4707
-            if ($table_obj instanceof EE_Primary_Table) {
4708
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4709
-                    ? $table_obj->get_select_join_limit($limit)
4710
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4712
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4713
-                    ? $table_obj->get_select_join_limit_join($limit)
4714
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4715
-            }
4716
-        }
4717
-        return $SQL;
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
-     *
4726
-     * @return string SQL
4727
-     * @throws EE_Error
4728
-     */
4729
-    public function _construct_internal_join()
4730
-    {
4731
-        $SQL = $this->_get_main_table()->get_table_sql();
4732
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
-        return $SQL;
4734
-    }
4735
-
4736
-
4737
-
4738
-    /**
4739
-     * Constructs the SQL for joining all the tables on this model.
4740
-     * Normally $alias should be the primary table's alias, but in cases where
4741
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
-     * alias, this will construct SQL like:
4744
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
-     * With $alias being a secondary table's alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     *
4748
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
-     * @return string
4750
-     */
4751
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
-    {
4753
-        $SQL = '';
4754
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
-        foreach ($this->_tables as $table_obj) {
4756
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
-                    // so we're joining to this table, meaning the table is already in
4759
-                    // the FROM statement, BUT the primary table isn't. So we want
4760
-                    // to add the inverse join sql
4761
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
-                } else {
4763
-                    // just add a regular JOIN to this table from the primary table
4764
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
-                }
4766
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
-        }
4768
-        return $SQL;
4769
-    }
4770
-
4771
-
4772
-
4773
-    /**
4774
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
-     * their data type (eg, '%s', '%d', etc)
4777
-     *
4778
-     * @return array
4779
-     */
4780
-    public function _get_data_types()
4781
-    {
4782
-        $data_types = array();
4783
-        foreach ($this->field_settings() as $field_obj) {
4784
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
-            /** @var $field_obj EE_Model_Field_Base */
4786
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
-        }
4788
-        return $data_types;
4789
-    }
4790
-
4791
-
4792
-
4793
-    /**
4794
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
-     *
4796
-     * @param string $model_name
4797
-     * @throws EE_Error
4798
-     * @return EEM_Base
4799
-     */
4800
-    public function get_related_model_obj($model_name)
4801
-    {
4802
-        $model_classname = "EEM_" . $model_name;
4803
-        if (! class_exists($model_classname)) {
4804
-            throw new EE_Error(sprintf(esc_html__(
4805
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
-                'event_espresso'
4807
-            ), $model_name, $model_classname));
4808
-        }
4809
-        return call_user_func($model_classname . "::instance");
4810
-    }
4811
-
4812
-
4813
-
4814
-    /**
4815
-     * Returns the array of EE_ModelRelations for this model.
4816
-     *
4817
-     * @return EE_Model_Relation_Base[]
4818
-     */
4819
-    public function relation_settings()
4820
-    {
4821
-        return $this->_model_relations;
4822
-    }
4823
-
4824
-
4825
-
4826
-    /**
4827
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
-     * because without THOSE models, this model probably doesn't have much purpose.
4829
-     * (Eg, without an event, datetimes have little purpose.)
4830
-     *
4831
-     * @return EE_Belongs_To_Relation[]
4832
-     */
4833
-    public function belongs_to_relations()
4834
-    {
4835
-        $belongs_to_relations = array();
4836
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4839
-            }
4840
-        }
4841
-        return $belongs_to_relations;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Returns the specified EE_Model_Relation, or throws an exception
4848
-     *
4849
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4850
-     * @throws EE_Error
4851
-     * @return EE_Model_Relation_Base
4852
-     */
4853
-    public function related_settings_for($relation_name)
4854
-    {
4855
-        $relatedModels = $this->relation_settings();
4856
-        if (! array_key_exists($relation_name, $relatedModels)) {
4857
-            throw new EE_Error(
4858
-                sprintf(
4859
-                    esc_html__(
4860
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
-                        'event_espresso'
4862
-                    ),
4863
-                    $relation_name,
4864
-                    $this->_get_class_name(),
4865
-                    implode(', ', array_keys($relatedModels))
4866
-                )
4867
-            );
4868
-        }
4869
-        return $relatedModels[ $relation_name ];
4870
-    }
4871
-
4872
-
4873
-
4874
-    /**
4875
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
-     * fields
4877
-     *
4878
-     * @param string $fieldName
4879
-     * @param boolean $include_db_only_fields
4880
-     * @throws EE_Error
4881
-     * @return EE_Model_Field_Base
4882
-     */
4883
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
-    {
4885
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4886
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4887
-            throw new EE_Error(sprintf(
4888
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
-                $fieldName,
4890
-                get_class($this)
4891
-            ));
4892
-        }
4893
-        return $fieldSettings[ $fieldName ];
4894
-    }
4895
-
4896
-
4897
-
4898
-    /**
4899
-     * Checks if this field exists on this model
4900
-     *
4901
-     * @param string $fieldName a key in the model's _field_settings array
4902
-     * @return boolean
4903
-     */
4904
-    public function has_field($fieldName)
4905
-    {
4906
-        $fieldSettings = $this->field_settings(true);
4907
-        if (isset($fieldSettings[ $fieldName ])) {
4908
-            return true;
4909
-        }
4910
-        return false;
4911
-    }
4912
-
4913
-
4914
-
4915
-    /**
4916
-     * Returns whether or not this model has a relation to the specified model
4917
-     *
4918
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4919
-     * @return boolean
4920
-     */
4921
-    public function has_relation($relation_name)
4922
-    {
4923
-        $relations = $this->relation_settings();
4924
-        if (isset($relations[ $relation_name ])) {
4925
-            return true;
4926
-        }
4927
-        return false;
4928
-    }
4929
-
4930
-
4931
-
4932
-    /**
4933
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
-     * Eg, on EE_Answer that would be ANS_ID field object
4935
-     *
4936
-     * @param $field_obj
4937
-     * @return boolean
4938
-     */
4939
-    public function is_primary_key_field($field_obj)
4940
-    {
4941
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
-    }
4943
-
4944
-
4945
-
4946
-    /**
4947
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
-     * Eg, on EE_Answer that would be ANS_ID field object
4949
-     *
4950
-     * @return EE_Model_Field_Base
4951
-     * @throws EE_Error
4952
-     */
4953
-    public function get_primary_key_field()
4954
-    {
4955
-        if ($this->_primary_key_field === null) {
4956
-            foreach ($this->field_settings(true) as $field_obj) {
4957
-                if ($this->is_primary_key_field($field_obj)) {
4958
-                    $this->_primary_key_field = $field_obj;
4959
-                    break;
4960
-                }
4961
-            }
4962
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
-                throw new EE_Error(sprintf(
4964
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
-                    get_class($this)
4966
-                ));
4967
-            }
4968
-        }
4969
-        return $this->_primary_key_field;
4970
-    }
4971
-
4972
-
4973
-
4974
-    /**
4975
-     * Returns whether or not not there is a primary key on this model.
4976
-     * Internally does some caching.
4977
-     *
4978
-     * @return boolean
4979
-     */
4980
-    public function has_primary_key_field()
4981
-    {
4982
-        if ($this->_has_primary_key_field === null) {
4983
-            try {
4984
-                $this->get_primary_key_field();
4985
-                $this->_has_primary_key_field = true;
4986
-            } catch (EE_Error $e) {
4987
-                $this->_has_primary_key_field = false;
4988
-            }
4989
-        }
4990
-        return $this->_has_primary_key_field;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * Finds the first field of type $field_class_name.
4997
-     *
4998
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
-     *                                 EE_Foreign_Key_Field, etc
5000
-     * @return EE_Model_Field_Base or null if none is found
5001
-     */
5002
-    public function get_a_field_of_type($field_class_name)
5003
-    {
5004
-        foreach ($this->field_settings() as $field) {
5005
-            if ($field instanceof $field_class_name) {
5006
-                return $field;
5007
-            }
5008
-        }
5009
-        return null;
5010
-    }
5011
-
5012
-
5013
-
5014
-    /**
5015
-     * Gets a foreign key field pointing to model.
5016
-     *
5017
-     * @param string $model_name eg Event, Registration, not EEM_Event
5018
-     * @return EE_Foreign_Key_Field_Base
5019
-     * @throws EE_Error
5020
-     */
5021
-    public function get_foreign_key_to($model_name)
5022
-    {
5023
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
-            foreach ($this->field_settings() as $field) {
5025
-                if (
5026
-                    $field instanceof EE_Foreign_Key_Field_Base
5027
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5028
-                ) {
5029
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
-                    break;
5031
-                }
5032
-            }
5033
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
-                throw new EE_Error(sprintf(esc_html__(
5035
-                    "There is no foreign key field pointing to model %s on model %s",
5036
-                    'event_espresso'
5037
-                ), $model_name, get_class($this)));
5038
-            }
5039
-        }
5040
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
-    }
5042
-
5043
-
5044
-
5045
-    /**
5046
-     * Gets the table name (including $wpdb->prefix) for the table alias
5047
-     *
5048
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
-     *                            Either one works
5051
-     * @return string
5052
-     */
5053
-    public function get_table_for_alias($table_alias)
5054
-    {
5055
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
-    }
5058
-
5059
-
5060
-
5061
-    /**
5062
-     * Returns a flat array of all field son this model, instead of organizing them
5063
-     * by table_alias as they are in the constructor.
5064
-     *
5065
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5067
-     */
5068
-    public function field_settings($include_db_only_fields = false)
5069
-    {
5070
-        if ($include_db_only_fields) {
5071
-            if ($this->_cached_fields === null) {
5072
-                $this->_cached_fields = array();
5073
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5074
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5076
-                    }
5077
-                }
5078
-            }
5079
-            return $this->_cached_fields;
5080
-        }
5081
-        if ($this->_cached_fields_non_db_only === null) {
5082
-            $this->_cached_fields_non_db_only = array();
5083
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5084
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
-                    /** @var $field_obj EE_Model_Field_Base */
5086
-                    if (! $field_obj->is_db_only_field()) {
5087
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
-                    }
5089
-                }
5090
-            }
5091
-        }
5092
-        return $this->_cached_fields_non_db_only;
5093
-    }
5094
-
5095
-
5096
-
5097
-    /**
5098
-     *        cycle though array of attendees and create objects out of each item
5099
-     *
5100
-     * @access        private
5101
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
-     *                           numerically indexed)
5104
-     * @throws EE_Error
5105
-     */
5106
-    protected function _create_objects($rows = array())
5107
-    {
5108
-        $array_of_objects = array();
5109
-        if (empty($rows)) {
5110
-            return array();
5111
-        }
5112
-        $count_if_model_has_no_primary_key = 0;
5113
-        $has_primary_key = $this->has_primary_key_field();
5114
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
-        foreach ((array) $rows as $row) {
5116
-            if (empty($row)) {
5117
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
-                return array();
5119
-            }
5120
-            // check if we've already set this object in the results array,
5121
-            // in which case there's no need to process it further (again)
5122
-            if ($has_primary_key) {
5123
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
-                    $row,
5125
-                    $primary_key_field->get_qualified_column(),
5126
-                    $primary_key_field->get_table_column()
5127
-                );
5128
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
-                    continue;
5130
-                }
5131
-            }
5132
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5133
-            if (! $classInstance) {
5134
-                throw new EE_Error(
5135
-                    sprintf(
5136
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
-                        $this->get_this_model_name(),
5138
-                        http_build_query($row)
5139
-                    )
5140
-                );
5141
-            }
5142
-            // set the timezone on the instantiated objects
5143
-            $classInstance->set_timezone($this->_timezone);
5144
-            // make sure if there is any timezone setting present that we set the timezone for the object
5145
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
-            $array_of_objects[ $key ] = $classInstance;
5147
-            // also, for all the relations of type BelongsTo, see if we can cache
5148
-            // those related models
5149
-            // (we could do this for other relations too, but if there are conditions
5150
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5151
-            // so it requires a little more thought than just caching them immediately...)
5152
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
-                    // check if this model's INFO is present. If so, cache it on the model
5155
-                    $other_model = $relation_obj->get_other_model();
5156
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
-                    // if we managed to make a model object from the results, cache it on the main model object
5158
-                    if ($other_model_obj_maybe) {
5159
-                        // set timezone on these other model objects if they are present
5160
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5161
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5162
-                    }
5163
-                }
5164
-            }
5165
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
-            // the field in the CustomSelects object
5168
-            if ($this->_custom_selections instanceof CustomSelects) {
5169
-                $classInstance->setCustomSelectsValues(
5170
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5171
-                );
5172
-            }
5173
-        }
5174
-        return $array_of_objects;
5175
-    }
5176
-
5177
-
5178
-    /**
5179
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
-     *
5182
-     * @param array $db_results_row
5183
-     * @return array
5184
-     */
5185
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
-    {
5187
-        $results = array();
5188
-        if ($this->_custom_selections instanceof CustomSelects) {
5189
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
-                if (isset($db_results_row[ $alias ])) {
5191
-                    $results[ $alias ] = $this->convertValueToDataType(
5192
-                        $db_results_row[ $alias ],
5193
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5194
-                    );
5195
-                }
5196
-            }
5197
-        }
5198
-        return $results;
5199
-    }
5200
-
5201
-
5202
-    /**
5203
-     * This will set the value for the given alias
5204
-     * @param string $value
5205
-     * @param string $datatype (one of %d, %s, %f)
5206
-     * @return int|string|float (int for %d, string for %s, float for %f)
5207
-     */
5208
-    protected function convertValueToDataType($value, $datatype)
5209
-    {
5210
-        switch ($datatype) {
5211
-            case '%f':
5212
-                return (float) $value;
5213
-            case '%d':
5214
-                return (int) $value;
5215
-            default:
5216
-                return (string) $value;
5217
-        }
5218
-    }
5219
-
5220
-
5221
-    /**
5222
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
-     * object (as set in the model_field!).
5226
-     *
5227
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
-     */
5229
-    public function create_default_object()
5230
-    {
5231
-        $this_model_fields_and_values = array();
5232
-        // setup the row using default values;
5233
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5234
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
-        }
5236
-        $className = $this->_get_class_name();
5237
-        $classInstance = EE_Registry::instance()
5238
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5239
-        return $classInstance;
5240
-    }
5241
-
5242
-
5243
-
5244
-    /**
5245
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
-     *                             or an stdClass where each property is the name of a column,
5247
-     * @return EE_Base_Class
5248
-     * @throws EE_Error
5249
-     */
5250
-    public function instantiate_class_from_array_or_object($cols_n_values)
5251
-    {
5252
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
-            $cols_n_values = get_object_vars($cols_n_values);
5254
-        }
5255
-        $primary_key = null;
5256
-        // make sure the array only has keys that are fields/columns on this model
5257
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
-        }
5261
-        $className = $this->_get_class_name();
5262
-        // check we actually found results that we can use to build our model object
5263
-        // if not, return null
5264
-        if ($this->has_primary_key_field()) {
5265
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
-                return null;
5267
-            }
5268
-        } elseif ($this->unique_indexes()) {
5269
-            $first_column = reset($this_model_fields_n_values);
5270
-            if (empty($first_column)) {
5271
-                return null;
5272
-            }
5273
-        }
5274
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
-        if ($primary_key) {
5276
-            $classInstance = $this->get_from_entity_map($primary_key);
5277
-            if (! $classInstance) {
5278
-                $classInstance = EE_Registry::instance()
5279
-                                            ->load_class(
5280
-                                                $className,
5281
-                                                array($this_model_fields_n_values, $this->_timezone),
5282
-                                                true,
5283
-                                                false
5284
-                                            );
5285
-                // add this new object to the entity map
5286
-                $classInstance = $this->add_to_entity_map($classInstance);
5287
-            }
5288
-        } else {
5289
-            $classInstance = EE_Registry::instance()
5290
-                                        ->load_class(
5291
-                                            $className,
5292
-                                            array($this_model_fields_n_values, $this->_timezone),
5293
-                                            true,
5294
-                                            false
5295
-                                        );
5296
-        }
5297
-        return $classInstance;
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Gets the model object from the  entity map if it exists
5304
-     *
5305
-     * @param int|string $id the ID of the model object
5306
-     * @return EE_Base_Class
5307
-     */
5308
-    public function get_from_entity_map($id)
5309
-    {
5310
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
-    }
5313
-
5314
-
5315
-
5316
-    /**
5317
-     * add_to_entity_map
5318
-     * Adds the object to the model's entity mappings
5319
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
-     *        then this method should be called immediately after the update query
5324
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5326
-     *
5327
-     * @param    EE_Base_Class $object
5328
-     * @throws EE_Error
5329
-     * @return \EE_Base_Class
5330
-     */
5331
-    public function add_to_entity_map(EE_Base_Class $object)
5332
-    {
5333
-        $className = $this->_get_class_name();
5334
-        if (! $object instanceof $className) {
5335
-            throw new EE_Error(sprintf(
5336
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
-                is_object($object) ? get_class($object) : $object,
5338
-                $className
5339
-            ));
5340
-        }
5341
-        /** @var $object EE_Base_Class */
5342
-        if (! $object->ID()) {
5343
-            throw new EE_Error(sprintf(esc_html__(
5344
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5345
-                "event_espresso"
5346
-            ), get_class($this)));
5347
-        }
5348
-        // double check it's not already there
5349
-        $classInstance = $this->get_from_entity_map($object->ID());
5350
-        if ($classInstance) {
5351
-            return $classInstance;
5352
-        }
5353
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
-        return $object;
5355
-    }
5356
-
5357
-
5358
-
5359
-    /**
5360
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5361
-     * if no identifier is provided, then the entire entity map is emptied
5362
-     *
5363
-     * @param int|string $id the ID of the model object
5364
-     * @return boolean
5365
-     */
5366
-    public function clear_entity_map($id = null)
5367
-    {
5368
-        if (empty($id)) {
5369
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
-            return true;
5371
-        }
5372
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
-            return true;
5375
-        }
5376
-        return false;
5377
-    }
5378
-
5379
-
5380
-
5381
-    /**
5382
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
-     * Given an array where keys are column (or column alias) names and values,
5384
-     * returns an array of their corresponding field names and database values
5385
-     *
5386
-     * @param array $cols_n_values
5387
-     * @return array
5388
-     */
5389
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
-    {
5391
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
-    }
5393
-
5394
-
5395
-
5396
-    /**
5397
-     * _deduce_fields_n_values_from_cols_n_values
5398
-     * Given an array where keys are column (or column alias) names and values,
5399
-     * returns an array of their corresponding field names and database values
5400
-     *
5401
-     * @param string $cols_n_values
5402
-     * @return array
5403
-     */
5404
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
-    {
5406
-        $this_model_fields_n_values = array();
5407
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
-                $cols_n_values,
5410
-                $table_obj->get_fully_qualified_pk_column(),
5411
-                $table_obj->get_pk_column()
5412
-            );
5413
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5414
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
-                    if (! $field_obj->is_db_only_field()) {
5417
-                        // prepare field as if its coming from db
5418
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
-                    }
5421
-                }
5422
-            } else {
5423
-                // the table's rows existed. Use their values
5424
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
-                    if (! $field_obj->is_db_only_field()) {
5426
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
-                            $cols_n_values,
5428
-                            $field_obj->get_qualified_column(),
5429
-                            $field_obj->get_table_column()
5430
-                        );
5431
-                    }
5432
-                }
5433
-            }
5434
-        }
5435
-        return $this_model_fields_n_values;
5436
-    }
5437
-
5438
-
5439
-    /**
5440
-     * @param $cols_n_values
5441
-     * @param $qualified_column
5442
-     * @param $regular_column
5443
-     * @return null
5444
-     * @throws EE_Error
5445
-     * @throws ReflectionException
5446
-     */
5447
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
-    {
5449
-        $value = null;
5450
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
-        // does the field on the model relate to this column retrieved from the db?
5452
-        // or is it a db-only field? (not relating to the model)
5453
-        if (isset($cols_n_values[ $qualified_column ])) {
5454
-            $value = $cols_n_values[ $qualified_column ];
5455
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5456
-            $value = $cols_n_values[ $regular_column ];
5457
-        } elseif (! empty($this->foreign_key_aliases)) {
5458
-            // no PK?  ok check if there is a foreign key alias set for this table
5459
-            // then check if that alias exists in the incoming data
5460
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
-                    $value = $cols_n_values[ $FK_alias ];
5464
-                    list($pk_class) = explode('.', $PK_column);
5465
-                    $pk_model_name = "EEM_{$pk_class}";
5466
-                    /** @var EEM_Base $pk_model */
5467
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
-                    if ($pk_model instanceof EEM_Base) {
5469
-                        // make sure object is pulled from db and added to entity map
5470
-                        $pk_model->get_one_by_ID($value);
5471
-                    }
5472
-                    break;
5473
-                }
5474
-            }
5475
-        }
5476
-        return $value;
5477
-    }
5478
-
5479
-
5480
-
5481
-    /**
5482
-     * refresh_entity_map_from_db
5483
-     * Makes sure the model object in the entity map at $id assumes the values
5484
-     * of the database (opposite of EE_base_Class::save())
5485
-     *
5486
-     * @param int|string $id
5487
-     * @return EE_Base_Class
5488
-     * @throws EE_Error
5489
-     */
5490
-    public function refresh_entity_map_from_db($id)
5491
-    {
5492
-        $obj_in_map = $this->get_from_entity_map($id);
5493
-        if ($obj_in_map) {
5494
-            $wpdb_results = $this->_get_all_wpdb_results(
5495
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
-            );
5497
-            if ($wpdb_results && is_array($wpdb_results)) {
5498
-                $one_row = reset($wpdb_results);
5499
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
-                    $obj_in_map->set_from_db($field_name, $db_value);
5501
-                }
5502
-                // clear the cache of related model objects
5503
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
-                    $obj_in_map->clear_cache($relation_name, null, true);
5505
-                }
5506
-            }
5507
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
-            return $obj_in_map;
5509
-        }
5510
-        return $this->get_one_by_ID($id);
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * refresh_entity_map_with
5517
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5518
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
-     *
5522
-     * @param int|string    $id
5523
-     * @param EE_Base_Class $replacing_model_obj
5524
-     * @return \EE_Base_Class
5525
-     * @throws EE_Error
5526
-     */
5527
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5528
-    {
5529
-        $obj_in_map = $this->get_from_entity_map($id);
5530
-        if ($obj_in_map) {
5531
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5532
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
-                    $obj_in_map->set($field_name, $value);
5534
-                }
5535
-                // make the model object in the entity map's cache match the $replacing_model_obj
5536
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
-                    $obj_in_map->clear_cache($relation_name, null, true);
5538
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
-                    }
5541
-                }
5542
-            }
5543
-            return $obj_in_map;
5544
-        }
5545
-        $this->add_to_entity_map($replacing_model_obj);
5546
-        return $replacing_model_obj;
5547
-    }
5548
-
5549
-
5550
-
5551
-    /**
5552
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
-     * require_once($this->_getClassName().".class.php");
5555
-     *
5556
-     * @return string
5557
-     */
5558
-    private function _get_class_name()
5559
-    {
5560
-        return "EE_" . $this->get_this_model_name();
5561
-    }
5562
-
5563
-
5564
-
5565
-    /**
5566
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5567
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
-     * it would be 'Events'.
5569
-     *
5570
-     * @param int $quantity
5571
-     * @return string
5572
-     */
5573
-    public function item_name($quantity = 1)
5574
-    {
5575
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5589
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5590
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5591
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5592
-     *        return $previousReturnValue.$returnString;
5593
-     * }
5594
-     * require('EEM_Answer.model.php');
5595
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5596
-     * // will output "you called my_callback! and passed args:monkeys,100"
5597
-     *
5598
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5599
-     * @param array  $args       array of original arguments passed to the function
5600
-     * @throws EE_Error
5601
-     * @return mixed whatever the plugin which calls add_filter decides
5602
-     */
5603
-    public function __call($methodName, $args)
5604
-    {
5605
-        $className = get_class($this);
5606
-        $tagName = "FHEE__{$className}__{$methodName}";
5607
-        if (! has_filter($tagName)) {
5608
-            throw new EE_Error(
5609
-                sprintf(
5610
-                    esc_html__(
5611
-                        '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 );',
5612
-                        'event_espresso'
5613
-                    ),
5614
-                    $methodName,
5615
-                    $className,
5616
-                    $tagName,
5617
-                    '<br />'
5618
-                )
5619
-            );
5620
-        }
5621
-        return apply_filters($tagName, null, $this, $args);
5622
-    }
5623
-
5624
-
5625
-
5626
-    /**
5627
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5628
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5629
-     *
5630
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5631
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5632
-     *                                                       the object's class name
5633
-     *                                                       or object's ID
5634
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5635
-     *                                                       exists in the database. If it does not, we add it
5636
-     * @throws EE_Error
5637
-     * @return EE_Base_Class
5638
-     */
5639
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5640
-    {
5641
-        $className = $this->_get_class_name();
5642
-        if ($base_class_obj_or_id instanceof $className) {
5643
-            $model_object = $base_class_obj_or_id;
5644
-        } else {
5645
-            $primary_key_field = $this->get_primary_key_field();
5646
-            if (
5647
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5648
-                && (
5649
-                    is_int($base_class_obj_or_id)
5650
-                    || is_string($base_class_obj_or_id)
5651
-                )
5652
-            ) {
5653
-                // assume it's an ID.
5654
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5655
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5656
-            } elseif (
5657
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5658
-                && is_string($base_class_obj_or_id)
5659
-            ) {
5660
-                // assume its a string representation of the object
5661
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5662
-            } else {
5663
-                throw new EE_Error(
5664
-                    sprintf(
5665
-                        esc_html__(
5666
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5667
-                            'event_espresso'
5668
-                        ),
5669
-                        $base_class_obj_or_id,
5670
-                        $this->_get_class_name(),
5671
-                        print_r($base_class_obj_or_id, true)
5672
-                    )
5673
-                );
5674
-            }
5675
-        }
5676
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5677
-            $model_object->save();
5678
-        }
5679
-        return $model_object;
5680
-    }
5681
-
5682
-
5683
-
5684
-    /**
5685
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5686
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5687
-     * returns it ID.
5688
-     *
5689
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5690
-     * @return int|string depending on the type of this model object's ID
5691
-     * @throws EE_Error
5692
-     */
5693
-    public function ensure_is_ID($base_class_obj_or_id)
5694
-    {
5695
-        $className = $this->_get_class_name();
5696
-        if ($base_class_obj_or_id instanceof $className) {
5697
-            /** @var $base_class_obj_or_id EE_Base_Class */
5698
-            $id = $base_class_obj_or_id->ID();
5699
-        } elseif (is_int($base_class_obj_or_id)) {
5700
-            // assume it's an ID
5701
-            $id = $base_class_obj_or_id;
5702
-        } elseif (is_string($base_class_obj_or_id)) {
5703
-            // assume its a string representation of the object
5704
-            $id = $base_class_obj_or_id;
5705
-        } else {
5706
-            throw new EE_Error(sprintf(
5707
-                esc_html__(
5708
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5709
-                    'event_espresso'
5710
-                ),
5711
-                $base_class_obj_or_id,
5712
-                $this->_get_class_name(),
5713
-                print_r($base_class_obj_or_id, true)
5714
-            ));
5715
-        }
5716
-        return $id;
5717
-    }
5718
-
5719
-
5720
-
5721
-    /**
5722
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5723
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5724
-     * been sanitized and converted into the appropriate domain.
5725
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5726
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5727
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5728
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5729
-     * $EVT = EEM_Event::instance(); $old_setting =
5730
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5731
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5732
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5733
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5734
-     *
5735
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5736
-     * @return void
5737
-     */
5738
-    public function assume_values_already_prepared_by_model_object(
5739
-        $values_already_prepared = self::not_prepared_by_model_object
5740
-    ) {
5741
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5742
-    }
5743
-
5744
-
5745
-
5746
-    /**
5747
-     * Read comments for assume_values_already_prepared_by_model_object()
5748
-     *
5749
-     * @return int
5750
-     */
5751
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5752
-    {
5753
-        return $this->_values_already_prepared_by_model_object;
5754
-    }
5755
-
5756
-
5757
-
5758
-    /**
5759
-     * Gets all the indexes on this model
5760
-     *
5761
-     * @return EE_Index[]
5762
-     */
5763
-    public function indexes()
5764
-    {
5765
-        return $this->_indexes;
5766
-    }
5767
-
5768
-
5769
-
5770
-    /**
5771
-     * Gets all the Unique Indexes on this model
5772
-     *
5773
-     * @return EE_Unique_Index[]
5774
-     */
5775
-    public function unique_indexes()
5776
-    {
5777
-        $unique_indexes = array();
5778
-        foreach ($this->_indexes as $name => $index) {
5779
-            if ($index instanceof EE_Unique_Index) {
5780
-                $unique_indexes [ $name ] = $index;
5781
-            }
5782
-        }
5783
-        return $unique_indexes;
5784
-    }
5785
-
5786
-
5787
-
5788
-    /**
5789
-     * Gets all the fields which, when combined, make the primary key.
5790
-     * This is usually just an array with 1 element (the primary key), but in cases
5791
-     * where there is no primary key, it's a combination of fields as defined
5792
-     * on a primary index
5793
-     *
5794
-     * @return EE_Model_Field_Base[] indexed by the field's name
5795
-     * @throws EE_Error
5796
-     */
5797
-    public function get_combined_primary_key_fields()
5798
-    {
5799
-        foreach ($this->indexes() as $index) {
5800
-            if ($index instanceof EE_Primary_Key_Index) {
5801
-                return $index->fields();
5802
-            }
5803
-        }
5804
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5805
-    }
5806
-
5807
-
5808
-
5809
-    /**
5810
-     * Used to build a primary key string (when the model has no primary key),
5811
-     * which can be used a unique string to identify this model object.
5812
-     *
5813
-     * @param array $fields_n_values keys are field names, values are their values.
5814
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5815
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5816
-     *                               before passing it to this function (that will convert it from columns-n-values
5817
-     *                               to field-names-n-values).
5818
-     * @return string
5819
-     * @throws EE_Error
5820
-     */
5821
-    public function get_index_primary_key_string($fields_n_values)
5822
-    {
5823
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5824
-            $fields_n_values,
5825
-            $this->get_combined_primary_key_fields()
5826
-        );
5827
-        return http_build_query($cols_n_values_for_primary_key_index);
5828
-    }
5829
-
5830
-
5831
-
5832
-    /**
5833
-     * Gets the field values from the primary key string
5834
-     *
5835
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5836
-     * @param string $index_primary_key_string
5837
-     * @return null|array
5838
-     * @throws EE_Error
5839
-     */
5840
-    public function parse_index_primary_key_string($index_primary_key_string)
5841
-    {
5842
-        $key_fields = $this->get_combined_primary_key_fields();
5843
-        // check all of them are in the $id
5844
-        $key_vals_in_combined_pk = array();
5845
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5846
-        foreach ($key_fields as $key_field_name => $field_obj) {
5847
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
-                return null;
5849
-            }
5850
-        }
5851
-        return $key_vals_in_combined_pk;
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * verifies that an array of key-value pairs for model fields has a key
5858
-     * for each field comprising the primary key index
5859
-     *
5860
-     * @param array $key_vals
5861
-     * @return boolean
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function has_all_combined_primary_key_fields($key_vals)
5865
-    {
5866
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5867
-        foreach ($keys_it_should_have as $key) {
5868
-            if (! isset($key_vals[ $key ])) {
5869
-                return false;
5870
-            }
5871
-        }
5872
-        return true;
5873
-    }
5874
-
5875
-
5876
-
5877
-    /**
5878
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5879
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5880
-     *
5881
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5882
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5883
-     * @throws EE_Error
5884
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5885
-     *                                                              indexed)
5886
-     */
5887
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5888
-    {
5889
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5890
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5891
-        } elseif (is_array($model_object_or_attributes_array)) {
5892
-            $attributes_array = $model_object_or_attributes_array;
5893
-        } else {
5894
-            throw new EE_Error(sprintf(esc_html__(
5895
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5896
-                "event_espresso"
5897
-            ), $model_object_or_attributes_array));
5898
-        }
5899
-        // even copies obviously won't have the same ID, so remove the primary key
5900
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5901
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5902
-            unset($attributes_array[ $this->primary_key_name() ]);
5903
-        }
5904
-        if (isset($query_params[0])) {
5905
-            $query_params[0] = array_merge($attributes_array, $query_params);
5906
-        } else {
5907
-            $query_params[0] = $attributes_array;
5908
-        }
5909
-        return $this->get_all($query_params);
5910
-    }
5911
-
5912
-
5913
-
5914
-    /**
5915
-     * Gets the first copy we find. See get_all_copies for more details
5916
-     *
5917
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5918
-     * @param array $query_params
5919
-     * @return EE_Base_Class
5920
-     * @throws EE_Error
5921
-     */
5922
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5923
-    {
5924
-        if (! is_array($query_params)) {
5925
-            EE_Error::doing_it_wrong(
5926
-                'EEM_Base::get_one_copy',
5927
-                sprintf(
5928
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5929
-                    gettype($query_params)
5930
-                ),
5931
-                '4.6.0'
5932
-            );
5933
-            $query_params = array();
5934
-        }
5935
-        $query_params['limit'] = 1;
5936
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5937
-        if (is_array($copies)) {
5938
-            return array_shift($copies);
5939
-        }
5940
-        return null;
5941
-    }
5942
-
5943
-
5944
-
5945
-    /**
5946
-     * Updates the item with the specified id. Ignores default query parameters because
5947
-     * we have specified the ID, and its assumed we KNOW what we're doing
5948
-     *
5949
-     * @param array      $fields_n_values keys are field names, values are their new values
5950
-     * @param int|string $id              the value of the primary key to update
5951
-     * @return int number of rows updated
5952
-     * @throws EE_Error
5953
-     */
5954
-    public function update_by_ID($fields_n_values, $id)
5955
-    {
5956
-        $query_params = array(
5957
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5958
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5959
-        );
5960
-        return $this->update($fields_n_values, $query_params);
5961
-    }
5962
-
5963
-
5964
-
5965
-    /**
5966
-     * Changes an operator which was supplied to the models into one usable in SQL
5967
-     *
5968
-     * @param string $operator_supplied
5969
-     * @return string an operator which can be used in SQL
5970
-     * @throws EE_Error
5971
-     */
5972
-    private function _prepare_operator_for_sql($operator_supplied)
5973
-    {
5974
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
-            : null;
5976
-        if ($sql_operator) {
5977
-            return $sql_operator;
5978
-        }
5979
-        throw new EE_Error(
5980
-            sprintf(
5981
-                esc_html__(
5982
-                    "The operator '%s' is not in the list of valid operators: %s",
5983
-                    "event_espresso"
5984
-                ),
5985
-                $operator_supplied,
5986
-                implode(",", array_keys($this->_valid_operators))
5987
-            )
5988
-        );
5989
-    }
5990
-
5991
-
5992
-
5993
-    /**
5994
-     * Gets the valid operators
5995
-     * @return array keys are accepted strings, values are the SQL they are converted to
5996
-     */
5997
-    public function valid_operators()
5998
-    {
5999
-        return $this->_valid_operators;
6000
-    }
6001
-
6002
-
6003
-
6004
-    /**
6005
-     * Gets the between-style operators (take 2 arguments).
6006
-     * @return array keys are accepted strings, values are the SQL they are converted to
6007
-     */
6008
-    public function valid_between_style_operators()
6009
-    {
6010
-        return array_intersect(
6011
-            $this->valid_operators(),
6012
-            $this->_between_style_operators
6013
-        );
6014
-    }
6015
-
6016
-    /**
6017
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6018
-     * @return array keys are accepted strings, values are the SQL they are converted to
6019
-     */
6020
-    public function valid_like_style_operators()
6021
-    {
6022
-        return array_intersect(
6023
-            $this->valid_operators(),
6024
-            $this->_like_style_operators
6025
-        );
6026
-    }
6027
-
6028
-    /**
6029
-     * Gets the "in"-style operators
6030
-     * @return array keys are accepted strings, values are the SQL they are converted to
6031
-     */
6032
-    public function valid_in_style_operators()
6033
-    {
6034
-        return array_intersect(
6035
-            $this->valid_operators(),
6036
-            $this->_in_style_operators
6037
-        );
6038
-    }
6039
-
6040
-    /**
6041
-     * Gets the "null"-style operators (accept no arguments)
6042
-     * @return array keys are accepted strings, values are the SQL they are converted to
6043
-     */
6044
-    public function valid_null_style_operators()
6045
-    {
6046
-        return array_intersect(
6047
-            $this->valid_operators(),
6048
-            $this->_null_style_operators
6049
-        );
6050
-    }
6051
-
6052
-    /**
6053
-     * Gets an array where keys are the primary keys and values are their 'names'
6054
-     * (as determined by the model object's name() function, which is often overridden)
6055
-     *
6056
-     * @param array $query_params like get_all's
6057
-     * @return string[]
6058
-     * @throws EE_Error
6059
-     */
6060
-    public function get_all_names($query_params = array())
6061
-    {
6062
-        $objs = $this->get_all($query_params);
6063
-        $names = array();
6064
-        foreach ($objs as $obj) {
6065
-            $names[ $obj->ID() ] = $obj->name();
6066
-        }
6067
-        return $names;
6068
-    }
6069
-
6070
-
6071
-
6072
-    /**
6073
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6074
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6075
-     * this is duplicated effort and reduces efficiency) you would be better to use
6076
-     * array_keys() on $model_objects.
6077
-     *
6078
-     * @param \EE_Base_Class[] $model_objects
6079
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6080
-     *                                               in the returned array
6081
-     * @return array
6082
-     * @throws EE_Error
6083
-     */
6084
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6085
-    {
6086
-        if (! $this->has_primary_key_field()) {
6087
-            if (WP_DEBUG) {
6088
-                EE_Error::add_error(
6089
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6090
-                    __FILE__,
6091
-                    __FUNCTION__,
6092
-                    __LINE__
6093
-                );
6094
-            }
6095
-        }
6096
-        $IDs = array();
6097
-        foreach ($model_objects as $model_object) {
6098
-            $id = $model_object->ID();
6099
-            if (! $id) {
6100
-                if ($filter_out_empty_ids) {
6101
-                    continue;
6102
-                }
6103
-                if (WP_DEBUG) {
6104
-                    EE_Error::add_error(
6105
-                        esc_html__(
6106
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6107
-                            'event_espresso'
6108
-                        ),
6109
-                        __FILE__,
6110
-                        __FUNCTION__,
6111
-                        __LINE__
6112
-                    );
6113
-                }
6114
-            }
6115
-            $IDs[] = $id;
6116
-        }
6117
-        return $IDs;
6118
-    }
6119
-
6120
-
6121
-
6122
-    /**
6123
-     * Returns the string used in capabilities relating to this model. If there
6124
-     * are no capabilities that relate to this model returns false
6125
-     *
6126
-     * @return string|false
6127
-     */
6128
-    public function cap_slug()
6129
-    {
6130
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6131
-    }
6132
-
6133
-
6134
-
6135
-    /**
6136
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6137
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6138
-     * only returns the cap restrictions array in that context (ie, the array
6139
-     * at that key)
6140
-     *
6141
-     * @param string $context
6142
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6143
-     * @throws EE_Error
6144
-     */
6145
-    public function cap_restrictions($context = EEM_Base::caps_read)
6146
-    {
6147
-        EEM_Base::verify_is_valid_cap_context($context);
6148
-        // check if we ought to run the restriction generator first
6149
-        if (
6150
-            isset($this->_cap_restriction_generators[ $context ])
6151
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6152
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
-        ) {
6154
-            $this->_cap_restrictions[ $context ] = array_merge(
6155
-                $this->_cap_restrictions[ $context ],
6156
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
-            );
6158
-        }
6159
-        // and make sure we've finalized the construction of each restriction
6160
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6162
-                $where_conditions_obj->_finalize_construct($this);
6163
-            }
6164
-        }
6165
-        return $this->_cap_restrictions[ $context ];
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Indicating whether or not this model thinks its a wp core model
6172
-     *
6173
-     * @return boolean
6174
-     */
6175
-    public function is_wp_core_model()
6176
-    {
6177
-        return $this->_wp_core_model;
6178
-    }
6179
-
6180
-
6181
-
6182
-    /**
6183
-     * Gets all the caps that are missing which impose a restriction on
6184
-     * queries made in this context
6185
-     *
6186
-     * @param string $context one of EEM_Base::caps_ constants
6187
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6188
-     * @throws EE_Error
6189
-     */
6190
-    public function caps_missing($context = EEM_Base::caps_read)
6191
-    {
6192
-        $missing_caps = array();
6193
-        $cap_restrictions = $this->cap_restrictions($context);
6194
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6195
-            if (
6196
-                ! EE_Capabilities::instance()
6197
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
-            ) {
6199
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6200
-            }
6201
-        }
6202
-        return $missing_caps;
6203
-    }
6204
-
6205
-
6206
-
6207
-    /**
6208
-     * Gets the mapping from capability contexts to action strings used in capability names
6209
-     *
6210
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6211
-     * one of 'read', 'edit', or 'delete'
6212
-     */
6213
-    public function cap_contexts_to_cap_action_map()
6214
-    {
6215
-        return apply_filters(
6216
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6217
-            $this->_cap_contexts_to_cap_action_map,
6218
-            $this
6219
-        );
6220
-    }
6221
-
6222
-
6223
-
6224
-    /**
6225
-     * Gets the action string for the specified capability context
6226
-     *
6227
-     * @param string $context
6228
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6229
-     * @throws EE_Error
6230
-     */
6231
-    public function cap_action_for_context($context)
6232
-    {
6233
-        $mapping = $this->cap_contexts_to_cap_action_map();
6234
-        if (isset($mapping[ $context ])) {
6235
-            return $mapping[ $context ];
6236
-        }
6237
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6238
-            return $action;
6239
-        }
6240
-        throw new EE_Error(
6241
-            sprintf(
6242
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6243
-                $context,
6244
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6245
-            )
6246
-        );
6247
-    }
6248
-
6249
-
6250
-
6251
-    /**
6252
-     * Returns all the capability contexts which are valid when querying models
6253
-     *
6254
-     * @return array
6255
-     */
6256
-    public static function valid_cap_contexts()
6257
-    {
6258
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6259
-            self::caps_read,
6260
-            self::caps_read_admin,
6261
-            self::caps_edit,
6262
-            self::caps_delete,
6263
-        ));
6264
-    }
6265
-
6266
-
6267
-
6268
-    /**
6269
-     * Returns all valid options for 'default_where_conditions'
6270
-     *
6271
-     * @return array
6272
-     */
6273
-    public static function valid_default_where_conditions()
6274
-    {
6275
-        return array(
6276
-            EEM_Base::default_where_conditions_all,
6277
-            EEM_Base::default_where_conditions_this_only,
6278
-            EEM_Base::default_where_conditions_others_only,
6279
-            EEM_Base::default_where_conditions_minimum_all,
6280
-            EEM_Base::default_where_conditions_minimum_others,
6281
-            EEM_Base::default_where_conditions_none
6282
-        );
6283
-    }
6284
-
6285
-    // public static function default_where_conditions_full
6286
-    /**
6287
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6288
-     *
6289
-     * @param string $context
6290
-     * @return bool
6291
-     * @throws EE_Error
6292
-     */
6293
-    public static function verify_is_valid_cap_context($context)
6294
-    {
6295
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6296
-        if (in_array($context, $valid_cap_contexts)) {
6297
-            return true;
6298
-        }
6299
-        throw new EE_Error(
6300
-            sprintf(
6301
-                esc_html__(
6302
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6303
-                    'event_espresso'
6304
-                ),
6305
-                $context,
6306
-                'EEM_Base',
6307
-                implode(',', $valid_cap_contexts)
6308
-            )
6309
-        );
6310
-    }
6311
-
6312
-
6313
-
6314
-    /**
6315
-     * Clears all the models field caches. This is only useful when a sub-class
6316
-     * might have added a field or something and these caches might be invalidated
6317
-     */
6318
-    protected function _invalidate_field_caches()
6319
-    {
6320
-        $this->_cache_foreign_key_to_fields = array();
6321
-        $this->_cached_fields = null;
6322
-        $this->_cached_fields_non_db_only = null;
6323
-    }
6324
-
6325
-
6326
-
6327
-    /**
6328
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6329
-     * (eg "and", "or", "not").
6330
-     *
6331
-     * @return array
6332
-     */
6333
-    public function logic_query_param_keys()
6334
-    {
6335
-        return $this->_logic_query_param_keys;
6336
-    }
6337
-
6338
-
6339
-
6340
-    /**
6341
-     * Determines whether or not the where query param array key is for a logic query param.
6342
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6343
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6344
-     *
6345
-     * @param $query_param_key
6346
-     * @return bool
6347
-     */
6348
-    public function is_logic_query_param_key($query_param_key)
6349
-    {
6350
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6351
-            if (
6352
-                $query_param_key === $logic_query_param_key
6353
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
-            ) {
6355
-                return true;
6356
-            }
6357
-        }
6358
-        return false;
6359
-    }
6360
-
6361
-    /**
6362
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6363
-     * @since 4.9.74.p
6364
-     * @return boolean
6365
-     */
6366
-    public function hasPassword()
6367
-    {
6368
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6369
-        if ($this->has_password_field === null) {
6370
-            $password_field = $this->getPasswordField();
6371
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6372
-        }
6373
-        return $this->has_password_field;
6374
-    }
6375
-
6376
-    /**
6377
-     * Returns the password field on this model, if there is one
6378
-     * @since 4.9.74.p
6379
-     * @return EE_Password_Field|null
6380
-     */
6381
-    public function getPasswordField()
6382
-    {
6383
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6384
-        // there's no need to search for it. If we don't know yet, then find out
6385
-        if ($this->has_password_field === null && $this->password_field === null) {
6386
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6387
-        }
6388
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6389
-        return $this->password_field;
6390
-    }
6391
-
6392
-
6393
-    /**
6394
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6395
-     * @since 4.9.74.p
6396
-     * @return EE_Model_Field_Base[]
6397
-     * @throws EE_Error
6398
-     */
6399
-    public function getPasswordProtectedFields()
6400
-    {
6401
-        $password_field = $this->getPasswordField();
6402
-        $fields = array();
6403
-        if ($password_field instanceof EE_Password_Field) {
6404
-            $field_names = $password_field->protectedFields();
6405
-            foreach ($field_names as $field_name) {
6406
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6407
-            }
6408
-        }
6409
-        return $fields;
6410
-    }
6411
-
6412
-
6413
-    /**
6414
-     * Checks if the current user can perform the requested action on this model
6415
-     * @since 4.9.74.p
6416
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6417
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6418
-     * @return bool
6419
-     * @throws EE_Error
6420
-     * @throws InvalidArgumentException
6421
-     * @throws InvalidDataTypeException
6422
-     * @throws InvalidInterfaceException
6423
-     * @throws ReflectionException
6424
-     * @throws UnexpectedEntityException
6425
-     */
6426
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6427
-    {
6428
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6429
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6430
-        }
6431
-        if (!is_array($model_obj_or_fields_n_values)) {
6432
-            throw new UnexpectedEntityException(
6433
-                $model_obj_or_fields_n_values,
6434
-                'EE_Base_Class',
6435
-                sprintf(
6436
-                    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'),
6437
-                    __FUNCTION__
6438
-                )
6439
-            );
6440
-        }
6441
-        return $this->exists(
6442
-            $this->alter_query_params_to_restrict_by_ID(
6443
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6444
-                array(
6445
-                    'default_where_conditions' => 'none',
6446
-                    'caps'                     => $cap_to_check,
6447
-                )
6448
-            )
6449
-        );
6450
-    }
6451
-
6452
-    /**
6453
-     * Returns the query param where conditions key to the password affecting this model.
6454
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6455
-     * @since 4.9.74.p
6456
-     * @return null|string
6457
-     * @throws EE_Error
6458
-     * @throws InvalidArgumentException
6459
-     * @throws InvalidDataTypeException
6460
-     * @throws InvalidInterfaceException
6461
-     * @throws ModelConfigurationException
6462
-     * @throws ReflectionException
6463
-     */
6464
-    public function modelChainAndPassword()
6465
-    {
6466
-        if ($this->model_chain_to_password === null) {
6467
-            throw new ModelConfigurationException(
6468
-                $this,
6469
-                esc_html_x(
6470
-                // @codingStandardsIgnoreStart
6471
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6472
-                    // @codingStandardsIgnoreEnd
6473
-                    '1: model name',
6474
-                    'event_espresso'
6475
-                )
6476
-            );
6477
-        }
6478
-        if ($this->model_chain_to_password === '') {
6479
-            $model_with_password = $this;
6480
-        } else {
6481
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6482
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6483
-            } else {
6484
-                $last_model_in_chain = $this->model_chain_to_password;
6485
-            }
6486
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6487
-        }
6488
-
6489
-        $password_field = $model_with_password->getPasswordField();
6490
-        if ($password_field instanceof EE_Password_Field) {
6491
-            $password_field_name = $password_field->get_name();
6492
-        } else {
6493
-            throw new ModelConfigurationException(
6494
-                $this,
6495
-                sprintf(
6496
-                    esc_html_x(
6497
-                        '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"',
6498
-                        '1: model name, 2: special string',
6499
-                        'event_espresso'
6500
-                    ),
6501
-                    $model_with_password->get_this_model_name(),
6502
-                    $this->model_chain_to_password
6503
-                )
6504
-            );
6505
-        }
6506
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
-    }
6508
-
6509
-    /**
6510
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6511
-     * or if this model itself has a password affecting access to some of its other fields.
6512
-     * @since 4.9.74.p
6513
-     * @return boolean
6514
-     */
6515
-    public function restrictedByRelatedModelPassword()
6516
-    {
6517
-        return $this->model_chain_to_password !== null;
6518
-    }
3815
+		}
3816
+		return $null_friendly_where_conditions;
3817
+	}
3818
+
3819
+
3820
+
3821
+	/**
3822
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3823
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3824
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3826
+	 *
3827
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
+	 */
3830
+	private function _get_default_where_conditions($model_relation_path = null)
3831
+	{
3832
+		if ($this->_ignore_where_strategy) {
3833
+			return array();
3834
+		}
3835
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
+	}
3837
+
3838
+
3839
+
3840
+	/**
3841
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3845
+	 * Similar to _get_default_where_conditions
3846
+	 *
3847
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
+	 */
3850
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3851
+	{
3852
+		if ($this->_ignore_where_strategy) {
3853
+			return array();
3854
+		}
3855
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
+	}
3857
+
3858
+
3859
+
3860
+	/**
3861
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
+	 *
3864
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3865
+	 * @return string
3866
+	 * @throws EE_Error
3867
+	 */
3868
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
+	{
3870
+		$selects = $this->_get_columns_to_select_for_this_model();
3871
+		foreach (
3872
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
+		) {
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
+					esc_html__(
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
+					esc_html__(
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(esc_html__(
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
+				esc_html__(
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
+						esc_html__(
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
+						esc_html__(
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
+						esc_html__(
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
+					esc_html__(
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
+					esc_html__(
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
+				esc_html__(
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
+	 * Takes an array or a comma-separated list of $values and cleans them
4497
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4498
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
+	 *
4502
+	 * @param mixed                      $values    array or comma-separated string
4503
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
+	 * @throws EE_Error
4506
+	 */
4507
+	public function _construct_in_value($values, $field_obj)
4508
+	{
4509
+		$prepped = [];
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
+		// make sure we only have one of each value in the list
4516
+		$values = array_unique($values);
4517
+		foreach ($values as $value) {
4518
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
+		}
4520
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
+		if (empty($prepped)) {
4524
+			$all_fields = $this->field_settings();
4525
+			$first_field    = reset($all_fields);
4526
+			$main_table = $this->_get_main_table();
4527
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
+		}
4529
+		return '(' . implode(',', $prepped) . ')';
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * @param mixed                      $value
4536
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
+	 * @throws EE_Error
4538
+	 * @return false|null|string
4539
+	 */
4540
+	private function _wpdb_prepare_using_field($value, $field_obj)
4541
+	{
4542
+		/** @type WPDB $wpdb */
4543
+		global $wpdb;
4544
+		if ($field_obj instanceof EE_Model_Field_Base) {
4545
+			return $wpdb->prepare(
4546
+				$field_obj->get_wpdb_data_type(),
4547
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4548
+			);
4549
+		} //$field_obj should really just be a data type
4550
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
+			throw new EE_Error(
4552
+				sprintf(
4553
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
+					$field_obj,
4555
+					implode(",", $this->_valid_wpdb_data_types)
4556
+				)
4557
+			);
4558
+		}
4559
+		return $wpdb->prepare($field_obj, $value);
4560
+	}
4561
+
4562
+
4563
+
4564
+	/**
4565
+	 * Takes the input parameter and finds the model field that it indicates.
4566
+	 *
4567
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
+	 * @throws EE_Error
4569
+	 * @return EE_Model_Field_Base
4570
+	 */
4571
+	protected function _deduce_field_from_query_param($query_param_name)
4572
+	{
4573
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
+		// which will help us find the database table and column
4575
+		$query_param_parts = explode(".", $query_param_name);
4576
+		if (empty($query_param_parts)) {
4577
+			throw new EE_Error(sprintf(esc_html__(
4578
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4579
+				'event_espresso'
4580
+			), $query_param_name));
4581
+		}
4582
+		$number_of_parts = count($query_param_parts);
4583
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
+		if ($number_of_parts === 1) {
4585
+			$field_name = $last_query_param_part;
4586
+			$model_obj = $this;
4587
+		} else {// $number_of_parts >= 2
4588
+			// the last part is the column name, and there are only 2parts. therefore...
4589
+			$field_name = $last_query_param_part;
4590
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
+		}
4592
+		try {
4593
+			return $model_obj->field_settings_for($field_name);
4594
+		} catch (EE_Error $e) {
4595
+			return null;
4596
+		}
4597
+	}
4598
+
4599
+
4600
+
4601
+	/**
4602
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
+	 * alias and column which corresponds to it
4604
+	 *
4605
+	 * @param string $field_name
4606
+	 * @throws EE_Error
4607
+	 * @return string
4608
+	 */
4609
+	public function _get_qualified_column_for_field($field_name)
4610
+	{
4611
+		$all_fields = $this->field_settings();
4612
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
+		if ($field) {
4614
+			return $field->get_qualified_column();
4615
+		}
4616
+		throw new EE_Error(
4617
+			sprintf(
4618
+				esc_html__(
4619
+					"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.",
4620
+					'event_espresso'
4621
+				),
4622
+				$field_name,
4623
+				get_class($this)
4624
+			)
4625
+		);
4626
+	}
4627
+
4628
+
4629
+
4630
+	/**
4631
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
+	 * Example usage:
4633
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4634
+	 *      array(),
4635
+	 *      ARRAY_A,
4636
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
+	 *  );
4638
+	 * is equivalent to
4639
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
+	 * and
4641
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4642
+	 *      array(
4643
+	 *          array(
4644
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
+	 *          ),
4646
+	 *          ARRAY_A,
4647
+	 *          implode(
4648
+	 *              ', ',
4649
+	 *              array_merge(
4650
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
+	 *              )
4653
+	 *          )
4654
+	 *      )
4655
+	 *  );
4656
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
+	 *
4658
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
+	 *                                            and the one whose fields you are selecting for example: when querying
4660
+	 *                                            tickets model and selecting fields from the tickets model you would
4661
+	 *                                            leave this parameter empty, because no models are needed to join
4662
+	 *                                            between the queried model and the selected one. Likewise when
4663
+	 *                                            querying the datetime model and selecting fields from the tickets
4664
+	 *                                            model, it would also be left empty, because there is a direct
4665
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4666
+	 *                                            them together. However, when querying from the event model and
4667
+	 *                                            selecting fields from the ticket model, you should provide the string
4668
+	 *                                            'Datetime', indicating that the event model must first join to the
4669
+	 *                                            datetime model in order to find its relation to ticket model.
4670
+	 *                                            Also, when querying from the venue model and selecting fields from
4671
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
+	 *                                            indicating you need to join the venue model to the event model,
4673
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4674
+	 *                                            This string is used to deduce the prefix that gets added onto the
4675
+	 *                                            models' tables qualified columns
4676
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4678
+	 *                                            qualified column names
4679
+	 * @return array|string
4680
+	 */
4681
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
+	{
4683
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
+		$qualified_columns = array();
4685
+		foreach ($this->field_settings() as $field_name => $field) {
4686
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
+		}
4688
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
+	}
4690
+
4691
+
4692
+
4693
+	/**
4694
+	 * constructs the select use on special limit joins
4695
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
+	 * (as that is typically where the limits would be set).
4698
+	 *
4699
+	 * @param  string       $table_alias The table the select is being built for
4700
+	 * @param  mixed|string $limit       The limit for this select
4701
+	 * @return string                The final select join element for the query.
4702
+	 */
4703
+	public function _construct_limit_join_select($table_alias, $limit)
4704
+	{
4705
+		$SQL = '';
4706
+		foreach ($this->_tables as $table_obj) {
4707
+			if ($table_obj instanceof EE_Primary_Table) {
4708
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4709
+					? $table_obj->get_select_join_limit($limit)
4710
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4712
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4713
+					? $table_obj->get_select_join_limit_join($limit)
4714
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4715
+			}
4716
+		}
4717
+		return $SQL;
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
+	 *
4726
+	 * @return string SQL
4727
+	 * @throws EE_Error
4728
+	 */
4729
+	public function _construct_internal_join()
4730
+	{
4731
+		$SQL = $this->_get_main_table()->get_table_sql();
4732
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
+		return $SQL;
4734
+	}
4735
+
4736
+
4737
+
4738
+	/**
4739
+	 * Constructs the SQL for joining all the tables on this model.
4740
+	 * Normally $alias should be the primary table's alias, but in cases where
4741
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
+	 * alias, this will construct SQL like:
4744
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 *
4748
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
+	 * @return string
4750
+	 */
4751
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
+	{
4753
+		$SQL = '';
4754
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
+		foreach ($this->_tables as $table_obj) {
4756
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
+					// so we're joining to this table, meaning the table is already in
4759
+					// the FROM statement, BUT the primary table isn't. So we want
4760
+					// to add the inverse join sql
4761
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
+				} else {
4763
+					// just add a regular JOIN to this table from the primary table
4764
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
+				}
4766
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
+		}
4768
+		return $SQL;
4769
+	}
4770
+
4771
+
4772
+
4773
+	/**
4774
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
+	 * their data type (eg, '%s', '%d', etc)
4777
+	 *
4778
+	 * @return array
4779
+	 */
4780
+	public function _get_data_types()
4781
+	{
4782
+		$data_types = array();
4783
+		foreach ($this->field_settings() as $field_obj) {
4784
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
+			/** @var $field_obj EE_Model_Field_Base */
4786
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
+		}
4788
+		return $data_types;
4789
+	}
4790
+
4791
+
4792
+
4793
+	/**
4794
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
+	 *
4796
+	 * @param string $model_name
4797
+	 * @throws EE_Error
4798
+	 * @return EEM_Base
4799
+	 */
4800
+	public function get_related_model_obj($model_name)
4801
+	{
4802
+		$model_classname = "EEM_" . $model_name;
4803
+		if (! class_exists($model_classname)) {
4804
+			throw new EE_Error(sprintf(esc_html__(
4805
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
+				'event_espresso'
4807
+			), $model_name, $model_classname));
4808
+		}
4809
+		return call_user_func($model_classname . "::instance");
4810
+	}
4811
+
4812
+
4813
+
4814
+	/**
4815
+	 * Returns the array of EE_ModelRelations for this model.
4816
+	 *
4817
+	 * @return EE_Model_Relation_Base[]
4818
+	 */
4819
+	public function relation_settings()
4820
+	{
4821
+		return $this->_model_relations;
4822
+	}
4823
+
4824
+
4825
+
4826
+	/**
4827
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
+	 * because without THOSE models, this model probably doesn't have much purpose.
4829
+	 * (Eg, without an event, datetimes have little purpose.)
4830
+	 *
4831
+	 * @return EE_Belongs_To_Relation[]
4832
+	 */
4833
+	public function belongs_to_relations()
4834
+	{
4835
+		$belongs_to_relations = array();
4836
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4839
+			}
4840
+		}
4841
+		return $belongs_to_relations;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Returns the specified EE_Model_Relation, or throws an exception
4848
+	 *
4849
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4850
+	 * @throws EE_Error
4851
+	 * @return EE_Model_Relation_Base
4852
+	 */
4853
+	public function related_settings_for($relation_name)
4854
+	{
4855
+		$relatedModels = $this->relation_settings();
4856
+		if (! array_key_exists($relation_name, $relatedModels)) {
4857
+			throw new EE_Error(
4858
+				sprintf(
4859
+					esc_html__(
4860
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
+						'event_espresso'
4862
+					),
4863
+					$relation_name,
4864
+					$this->_get_class_name(),
4865
+					implode(', ', array_keys($relatedModels))
4866
+				)
4867
+			);
4868
+		}
4869
+		return $relatedModels[ $relation_name ];
4870
+	}
4871
+
4872
+
4873
+
4874
+	/**
4875
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
+	 * fields
4877
+	 *
4878
+	 * @param string $fieldName
4879
+	 * @param boolean $include_db_only_fields
4880
+	 * @throws EE_Error
4881
+	 * @return EE_Model_Field_Base
4882
+	 */
4883
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
+	{
4885
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4886
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4887
+			throw new EE_Error(sprintf(
4888
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
+				$fieldName,
4890
+				get_class($this)
4891
+			));
4892
+		}
4893
+		return $fieldSettings[ $fieldName ];
4894
+	}
4895
+
4896
+
4897
+
4898
+	/**
4899
+	 * Checks if this field exists on this model
4900
+	 *
4901
+	 * @param string $fieldName a key in the model's _field_settings array
4902
+	 * @return boolean
4903
+	 */
4904
+	public function has_field($fieldName)
4905
+	{
4906
+		$fieldSettings = $this->field_settings(true);
4907
+		if (isset($fieldSettings[ $fieldName ])) {
4908
+			return true;
4909
+		}
4910
+		return false;
4911
+	}
4912
+
4913
+
4914
+
4915
+	/**
4916
+	 * Returns whether or not this model has a relation to the specified model
4917
+	 *
4918
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4919
+	 * @return boolean
4920
+	 */
4921
+	public function has_relation($relation_name)
4922
+	{
4923
+		$relations = $this->relation_settings();
4924
+		if (isset($relations[ $relation_name ])) {
4925
+			return true;
4926
+		}
4927
+		return false;
4928
+	}
4929
+
4930
+
4931
+
4932
+	/**
4933
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
+	 * Eg, on EE_Answer that would be ANS_ID field object
4935
+	 *
4936
+	 * @param $field_obj
4937
+	 * @return boolean
4938
+	 */
4939
+	public function is_primary_key_field($field_obj)
4940
+	{
4941
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
+	}
4943
+
4944
+
4945
+
4946
+	/**
4947
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
+	 * Eg, on EE_Answer that would be ANS_ID field object
4949
+	 *
4950
+	 * @return EE_Model_Field_Base
4951
+	 * @throws EE_Error
4952
+	 */
4953
+	public function get_primary_key_field()
4954
+	{
4955
+		if ($this->_primary_key_field === null) {
4956
+			foreach ($this->field_settings(true) as $field_obj) {
4957
+				if ($this->is_primary_key_field($field_obj)) {
4958
+					$this->_primary_key_field = $field_obj;
4959
+					break;
4960
+				}
4961
+			}
4962
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
+				throw new EE_Error(sprintf(
4964
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
+					get_class($this)
4966
+				));
4967
+			}
4968
+		}
4969
+		return $this->_primary_key_field;
4970
+	}
4971
+
4972
+
4973
+
4974
+	/**
4975
+	 * Returns whether or not not there is a primary key on this model.
4976
+	 * Internally does some caching.
4977
+	 *
4978
+	 * @return boolean
4979
+	 */
4980
+	public function has_primary_key_field()
4981
+	{
4982
+		if ($this->_has_primary_key_field === null) {
4983
+			try {
4984
+				$this->get_primary_key_field();
4985
+				$this->_has_primary_key_field = true;
4986
+			} catch (EE_Error $e) {
4987
+				$this->_has_primary_key_field = false;
4988
+			}
4989
+		}
4990
+		return $this->_has_primary_key_field;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * Finds the first field of type $field_class_name.
4997
+	 *
4998
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
+	 *                                 EE_Foreign_Key_Field, etc
5000
+	 * @return EE_Model_Field_Base or null if none is found
5001
+	 */
5002
+	public function get_a_field_of_type($field_class_name)
5003
+	{
5004
+		foreach ($this->field_settings() as $field) {
5005
+			if ($field instanceof $field_class_name) {
5006
+				return $field;
5007
+			}
5008
+		}
5009
+		return null;
5010
+	}
5011
+
5012
+
5013
+
5014
+	/**
5015
+	 * Gets a foreign key field pointing to model.
5016
+	 *
5017
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5018
+	 * @return EE_Foreign_Key_Field_Base
5019
+	 * @throws EE_Error
5020
+	 */
5021
+	public function get_foreign_key_to($model_name)
5022
+	{
5023
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
+			foreach ($this->field_settings() as $field) {
5025
+				if (
5026
+					$field instanceof EE_Foreign_Key_Field_Base
5027
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5028
+				) {
5029
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
+					break;
5031
+				}
5032
+			}
5033
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
+				throw new EE_Error(sprintf(esc_html__(
5035
+					"There is no foreign key field pointing to model %s on model %s",
5036
+					'event_espresso'
5037
+				), $model_name, get_class($this)));
5038
+			}
5039
+		}
5040
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
+	}
5042
+
5043
+
5044
+
5045
+	/**
5046
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5047
+	 *
5048
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
+	 *                            Either one works
5051
+	 * @return string
5052
+	 */
5053
+	public function get_table_for_alias($table_alias)
5054
+	{
5055
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
+	}
5058
+
5059
+
5060
+
5061
+	/**
5062
+	 * Returns a flat array of all field son this model, instead of organizing them
5063
+	 * by table_alias as they are in the constructor.
5064
+	 *
5065
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5067
+	 */
5068
+	public function field_settings($include_db_only_fields = false)
5069
+	{
5070
+		if ($include_db_only_fields) {
5071
+			if ($this->_cached_fields === null) {
5072
+				$this->_cached_fields = array();
5073
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5074
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
+						$this->_cached_fields[ $field_name ] = $field_obj;
5076
+					}
5077
+				}
5078
+			}
5079
+			return $this->_cached_fields;
5080
+		}
5081
+		if ($this->_cached_fields_non_db_only === null) {
5082
+			$this->_cached_fields_non_db_only = array();
5083
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5084
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
+					/** @var $field_obj EE_Model_Field_Base */
5086
+					if (! $field_obj->is_db_only_field()) {
5087
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+					}
5089
+				}
5090
+			}
5091
+		}
5092
+		return $this->_cached_fields_non_db_only;
5093
+	}
5094
+
5095
+
5096
+
5097
+	/**
5098
+	 *        cycle though array of attendees and create objects out of each item
5099
+	 *
5100
+	 * @access        private
5101
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
+	 *                           numerically indexed)
5104
+	 * @throws EE_Error
5105
+	 */
5106
+	protected function _create_objects($rows = array())
5107
+	{
5108
+		$array_of_objects = array();
5109
+		if (empty($rows)) {
5110
+			return array();
5111
+		}
5112
+		$count_if_model_has_no_primary_key = 0;
5113
+		$has_primary_key = $this->has_primary_key_field();
5114
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
+		foreach ((array) $rows as $row) {
5116
+			if (empty($row)) {
5117
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
+				return array();
5119
+			}
5120
+			// check if we've already set this object in the results array,
5121
+			// in which case there's no need to process it further (again)
5122
+			if ($has_primary_key) {
5123
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
+					$row,
5125
+					$primary_key_field->get_qualified_column(),
5126
+					$primary_key_field->get_table_column()
5127
+				);
5128
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
+					continue;
5130
+				}
5131
+			}
5132
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5133
+			if (! $classInstance) {
5134
+				throw new EE_Error(
5135
+					sprintf(
5136
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
+						$this->get_this_model_name(),
5138
+						http_build_query($row)
5139
+					)
5140
+				);
5141
+			}
5142
+			// set the timezone on the instantiated objects
5143
+			$classInstance->set_timezone($this->_timezone);
5144
+			// make sure if there is any timezone setting present that we set the timezone for the object
5145
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
+			$array_of_objects[ $key ] = $classInstance;
5147
+			// also, for all the relations of type BelongsTo, see if we can cache
5148
+			// those related models
5149
+			// (we could do this for other relations too, but if there are conditions
5150
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5151
+			// so it requires a little more thought than just caching them immediately...)
5152
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
+					// check if this model's INFO is present. If so, cache it on the model
5155
+					$other_model = $relation_obj->get_other_model();
5156
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
+					// if we managed to make a model object from the results, cache it on the main model object
5158
+					if ($other_model_obj_maybe) {
5159
+						// set timezone on these other model objects if they are present
5160
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5161
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5162
+					}
5163
+				}
5164
+			}
5165
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
+			// the field in the CustomSelects object
5168
+			if ($this->_custom_selections instanceof CustomSelects) {
5169
+				$classInstance->setCustomSelectsValues(
5170
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5171
+				);
5172
+			}
5173
+		}
5174
+		return $array_of_objects;
5175
+	}
5176
+
5177
+
5178
+	/**
5179
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
+	 *
5182
+	 * @param array $db_results_row
5183
+	 * @return array
5184
+	 */
5185
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
+	{
5187
+		$results = array();
5188
+		if ($this->_custom_selections instanceof CustomSelects) {
5189
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
+				if (isset($db_results_row[ $alias ])) {
5191
+					$results[ $alias ] = $this->convertValueToDataType(
5192
+						$db_results_row[ $alias ],
5193
+						$this->_custom_selections->getDataTypeForAlias($alias)
5194
+					);
5195
+				}
5196
+			}
5197
+		}
5198
+		return $results;
5199
+	}
5200
+
5201
+
5202
+	/**
5203
+	 * This will set the value for the given alias
5204
+	 * @param string $value
5205
+	 * @param string $datatype (one of %d, %s, %f)
5206
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5207
+	 */
5208
+	protected function convertValueToDataType($value, $datatype)
5209
+	{
5210
+		switch ($datatype) {
5211
+			case '%f':
5212
+				return (float) $value;
5213
+			case '%d':
5214
+				return (int) $value;
5215
+			default:
5216
+				return (string) $value;
5217
+		}
5218
+	}
5219
+
5220
+
5221
+	/**
5222
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
+	 * object (as set in the model_field!).
5226
+	 *
5227
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
+	 */
5229
+	public function create_default_object()
5230
+	{
5231
+		$this_model_fields_and_values = array();
5232
+		// setup the row using default values;
5233
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5234
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
+		}
5236
+		$className = $this->_get_class_name();
5237
+		$classInstance = EE_Registry::instance()
5238
+									->load_class($className, array($this_model_fields_and_values), false, false);
5239
+		return $classInstance;
5240
+	}
5241
+
5242
+
5243
+
5244
+	/**
5245
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
+	 *                             or an stdClass where each property is the name of a column,
5247
+	 * @return EE_Base_Class
5248
+	 * @throws EE_Error
5249
+	 */
5250
+	public function instantiate_class_from_array_or_object($cols_n_values)
5251
+	{
5252
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
+			$cols_n_values = get_object_vars($cols_n_values);
5254
+		}
5255
+		$primary_key = null;
5256
+		// make sure the array only has keys that are fields/columns on this model
5257
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+		}
5261
+		$className = $this->_get_class_name();
5262
+		// check we actually found results that we can use to build our model object
5263
+		// if not, return null
5264
+		if ($this->has_primary_key_field()) {
5265
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
+				return null;
5267
+			}
5268
+		} elseif ($this->unique_indexes()) {
5269
+			$first_column = reset($this_model_fields_n_values);
5270
+			if (empty($first_column)) {
5271
+				return null;
5272
+			}
5273
+		}
5274
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
+		if ($primary_key) {
5276
+			$classInstance = $this->get_from_entity_map($primary_key);
5277
+			if (! $classInstance) {
5278
+				$classInstance = EE_Registry::instance()
5279
+											->load_class(
5280
+												$className,
5281
+												array($this_model_fields_n_values, $this->_timezone),
5282
+												true,
5283
+												false
5284
+											);
5285
+				// add this new object to the entity map
5286
+				$classInstance = $this->add_to_entity_map($classInstance);
5287
+			}
5288
+		} else {
5289
+			$classInstance = EE_Registry::instance()
5290
+										->load_class(
5291
+											$className,
5292
+											array($this_model_fields_n_values, $this->_timezone),
5293
+											true,
5294
+											false
5295
+										);
5296
+		}
5297
+		return $classInstance;
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Gets the model object from the  entity map if it exists
5304
+	 *
5305
+	 * @param int|string $id the ID of the model object
5306
+	 * @return EE_Base_Class
5307
+	 */
5308
+	public function get_from_entity_map($id)
5309
+	{
5310
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+	}
5313
+
5314
+
5315
+
5316
+	/**
5317
+	 * add_to_entity_map
5318
+	 * Adds the object to the model's entity mappings
5319
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
+	 *        then this method should be called immediately after the update query
5324
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5326
+	 *
5327
+	 * @param    EE_Base_Class $object
5328
+	 * @throws EE_Error
5329
+	 * @return \EE_Base_Class
5330
+	 */
5331
+	public function add_to_entity_map(EE_Base_Class $object)
5332
+	{
5333
+		$className = $this->_get_class_name();
5334
+		if (! $object instanceof $className) {
5335
+			throw new EE_Error(sprintf(
5336
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
+				is_object($object) ? get_class($object) : $object,
5338
+				$className
5339
+			));
5340
+		}
5341
+		/** @var $object EE_Base_Class */
5342
+		if (! $object->ID()) {
5343
+			throw new EE_Error(sprintf(esc_html__(
5344
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5345
+				"event_espresso"
5346
+			), get_class($this)));
5347
+		}
5348
+		// double check it's not already there
5349
+		$classInstance = $this->get_from_entity_map($object->ID());
5350
+		if ($classInstance) {
5351
+			return $classInstance;
5352
+		}
5353
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
+		return $object;
5355
+	}
5356
+
5357
+
5358
+
5359
+	/**
5360
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5361
+	 * if no identifier is provided, then the entire entity map is emptied
5362
+	 *
5363
+	 * @param int|string $id the ID of the model object
5364
+	 * @return boolean
5365
+	 */
5366
+	public function clear_entity_map($id = null)
5367
+	{
5368
+		if (empty($id)) {
5369
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
+			return true;
5371
+		}
5372
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+			return true;
5375
+		}
5376
+		return false;
5377
+	}
5378
+
5379
+
5380
+
5381
+	/**
5382
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
+	 * Given an array where keys are column (or column alias) names and values,
5384
+	 * returns an array of their corresponding field names and database values
5385
+	 *
5386
+	 * @param array $cols_n_values
5387
+	 * @return array
5388
+	 */
5389
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
+	{
5391
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
+	}
5393
+
5394
+
5395
+
5396
+	/**
5397
+	 * _deduce_fields_n_values_from_cols_n_values
5398
+	 * Given an array where keys are column (or column alias) names and values,
5399
+	 * returns an array of their corresponding field names and database values
5400
+	 *
5401
+	 * @param string $cols_n_values
5402
+	 * @return array
5403
+	 */
5404
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
+	{
5406
+		$this_model_fields_n_values = array();
5407
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
+				$cols_n_values,
5410
+				$table_obj->get_fully_qualified_pk_column(),
5411
+				$table_obj->get_pk_column()
5412
+			);
5413
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5414
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
+					if (! $field_obj->is_db_only_field()) {
5417
+						// prepare field as if its coming from db
5418
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
+					}
5421
+				}
5422
+			} else {
5423
+				// the table's rows existed. Use their values
5424
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
+					if (! $field_obj->is_db_only_field()) {
5426
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+							$cols_n_values,
5428
+							$field_obj->get_qualified_column(),
5429
+							$field_obj->get_table_column()
5430
+						);
5431
+					}
5432
+				}
5433
+			}
5434
+		}
5435
+		return $this_model_fields_n_values;
5436
+	}
5437
+
5438
+
5439
+	/**
5440
+	 * @param $cols_n_values
5441
+	 * @param $qualified_column
5442
+	 * @param $regular_column
5443
+	 * @return null
5444
+	 * @throws EE_Error
5445
+	 * @throws ReflectionException
5446
+	 */
5447
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
+	{
5449
+		$value = null;
5450
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
+		// does the field on the model relate to this column retrieved from the db?
5452
+		// or is it a db-only field? (not relating to the model)
5453
+		if (isset($cols_n_values[ $qualified_column ])) {
5454
+			$value = $cols_n_values[ $qualified_column ];
5455
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5456
+			$value = $cols_n_values[ $regular_column ];
5457
+		} elseif (! empty($this->foreign_key_aliases)) {
5458
+			// no PK?  ok check if there is a foreign key alias set for this table
5459
+			// then check if that alias exists in the incoming data
5460
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
+					$value = $cols_n_values[ $FK_alias ];
5464
+					list($pk_class) = explode('.', $PK_column);
5465
+					$pk_model_name = "EEM_{$pk_class}";
5466
+					/** @var EEM_Base $pk_model */
5467
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
+					if ($pk_model instanceof EEM_Base) {
5469
+						// make sure object is pulled from db and added to entity map
5470
+						$pk_model->get_one_by_ID($value);
5471
+					}
5472
+					break;
5473
+				}
5474
+			}
5475
+		}
5476
+		return $value;
5477
+	}
5478
+
5479
+
5480
+
5481
+	/**
5482
+	 * refresh_entity_map_from_db
5483
+	 * Makes sure the model object in the entity map at $id assumes the values
5484
+	 * of the database (opposite of EE_base_Class::save())
5485
+	 *
5486
+	 * @param int|string $id
5487
+	 * @return EE_Base_Class
5488
+	 * @throws EE_Error
5489
+	 */
5490
+	public function refresh_entity_map_from_db($id)
5491
+	{
5492
+		$obj_in_map = $this->get_from_entity_map($id);
5493
+		if ($obj_in_map) {
5494
+			$wpdb_results = $this->_get_all_wpdb_results(
5495
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
+			);
5497
+			if ($wpdb_results && is_array($wpdb_results)) {
5498
+				$one_row = reset($wpdb_results);
5499
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
+					$obj_in_map->set_from_db($field_name, $db_value);
5501
+				}
5502
+				// clear the cache of related model objects
5503
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
+					$obj_in_map->clear_cache($relation_name, null, true);
5505
+				}
5506
+			}
5507
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
+			return $obj_in_map;
5509
+		}
5510
+		return $this->get_one_by_ID($id);
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * refresh_entity_map_with
5517
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5518
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
+	 *
5522
+	 * @param int|string    $id
5523
+	 * @param EE_Base_Class $replacing_model_obj
5524
+	 * @return \EE_Base_Class
5525
+	 * @throws EE_Error
5526
+	 */
5527
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5528
+	{
5529
+		$obj_in_map = $this->get_from_entity_map($id);
5530
+		if ($obj_in_map) {
5531
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5532
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
+					$obj_in_map->set($field_name, $value);
5534
+				}
5535
+				// make the model object in the entity map's cache match the $replacing_model_obj
5536
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
+					$obj_in_map->clear_cache($relation_name, null, true);
5538
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
+					}
5541
+				}
5542
+			}
5543
+			return $obj_in_map;
5544
+		}
5545
+		$this->add_to_entity_map($replacing_model_obj);
5546
+		return $replacing_model_obj;
5547
+	}
5548
+
5549
+
5550
+
5551
+	/**
5552
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
+	 * require_once($this->_getClassName().".class.php");
5555
+	 *
5556
+	 * @return string
5557
+	 */
5558
+	private function _get_class_name()
5559
+	{
5560
+		return "EE_" . $this->get_this_model_name();
5561
+	}
5562
+
5563
+
5564
+
5565
+	/**
5566
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5567
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
+	 * it would be 'Events'.
5569
+	 *
5570
+	 * @param int $quantity
5571
+	 * @return string
5572
+	 */
5573
+	public function item_name($quantity = 1)
5574
+	{
5575
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5589
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5590
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5591
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5592
+	 *        return $previousReturnValue.$returnString;
5593
+	 * }
5594
+	 * require('EEM_Answer.model.php');
5595
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5596
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5597
+	 *
5598
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5599
+	 * @param array  $args       array of original arguments passed to the function
5600
+	 * @throws EE_Error
5601
+	 * @return mixed whatever the plugin which calls add_filter decides
5602
+	 */
5603
+	public function __call($methodName, $args)
5604
+	{
5605
+		$className = get_class($this);
5606
+		$tagName = "FHEE__{$className}__{$methodName}";
5607
+		if (! has_filter($tagName)) {
5608
+			throw new EE_Error(
5609
+				sprintf(
5610
+					esc_html__(
5611
+						'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 );',
5612
+						'event_espresso'
5613
+					),
5614
+					$methodName,
5615
+					$className,
5616
+					$tagName,
5617
+					'<br />'
5618
+				)
5619
+			);
5620
+		}
5621
+		return apply_filters($tagName, null, $this, $args);
5622
+	}
5623
+
5624
+
5625
+
5626
+	/**
5627
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5628
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5629
+	 *
5630
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5631
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5632
+	 *                                                       the object's class name
5633
+	 *                                                       or object's ID
5634
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5635
+	 *                                                       exists in the database. If it does not, we add it
5636
+	 * @throws EE_Error
5637
+	 * @return EE_Base_Class
5638
+	 */
5639
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5640
+	{
5641
+		$className = $this->_get_class_name();
5642
+		if ($base_class_obj_or_id instanceof $className) {
5643
+			$model_object = $base_class_obj_or_id;
5644
+		} else {
5645
+			$primary_key_field = $this->get_primary_key_field();
5646
+			if (
5647
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5648
+				&& (
5649
+					is_int($base_class_obj_or_id)
5650
+					|| is_string($base_class_obj_or_id)
5651
+				)
5652
+			) {
5653
+				// assume it's an ID.
5654
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5655
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5656
+			} elseif (
5657
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5658
+				&& is_string($base_class_obj_or_id)
5659
+			) {
5660
+				// assume its a string representation of the object
5661
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5662
+			} else {
5663
+				throw new EE_Error(
5664
+					sprintf(
5665
+						esc_html__(
5666
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5667
+							'event_espresso'
5668
+						),
5669
+						$base_class_obj_or_id,
5670
+						$this->_get_class_name(),
5671
+						print_r($base_class_obj_or_id, true)
5672
+					)
5673
+				);
5674
+			}
5675
+		}
5676
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5677
+			$model_object->save();
5678
+		}
5679
+		return $model_object;
5680
+	}
5681
+
5682
+
5683
+
5684
+	/**
5685
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5686
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5687
+	 * returns it ID.
5688
+	 *
5689
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5690
+	 * @return int|string depending on the type of this model object's ID
5691
+	 * @throws EE_Error
5692
+	 */
5693
+	public function ensure_is_ID($base_class_obj_or_id)
5694
+	{
5695
+		$className = $this->_get_class_name();
5696
+		if ($base_class_obj_or_id instanceof $className) {
5697
+			/** @var $base_class_obj_or_id EE_Base_Class */
5698
+			$id = $base_class_obj_or_id->ID();
5699
+		} elseif (is_int($base_class_obj_or_id)) {
5700
+			// assume it's an ID
5701
+			$id = $base_class_obj_or_id;
5702
+		} elseif (is_string($base_class_obj_or_id)) {
5703
+			// assume its a string representation of the object
5704
+			$id = $base_class_obj_or_id;
5705
+		} else {
5706
+			throw new EE_Error(sprintf(
5707
+				esc_html__(
5708
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5709
+					'event_espresso'
5710
+				),
5711
+				$base_class_obj_or_id,
5712
+				$this->_get_class_name(),
5713
+				print_r($base_class_obj_or_id, true)
5714
+			));
5715
+		}
5716
+		return $id;
5717
+	}
5718
+
5719
+
5720
+
5721
+	/**
5722
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5723
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5724
+	 * been sanitized and converted into the appropriate domain.
5725
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5726
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5727
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5728
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5729
+	 * $EVT = EEM_Event::instance(); $old_setting =
5730
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5731
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5732
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5733
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5734
+	 *
5735
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5736
+	 * @return void
5737
+	 */
5738
+	public function assume_values_already_prepared_by_model_object(
5739
+		$values_already_prepared = self::not_prepared_by_model_object
5740
+	) {
5741
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5742
+	}
5743
+
5744
+
5745
+
5746
+	/**
5747
+	 * Read comments for assume_values_already_prepared_by_model_object()
5748
+	 *
5749
+	 * @return int
5750
+	 */
5751
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5752
+	{
5753
+		return $this->_values_already_prepared_by_model_object;
5754
+	}
5755
+
5756
+
5757
+
5758
+	/**
5759
+	 * Gets all the indexes on this model
5760
+	 *
5761
+	 * @return EE_Index[]
5762
+	 */
5763
+	public function indexes()
5764
+	{
5765
+		return $this->_indexes;
5766
+	}
5767
+
5768
+
5769
+
5770
+	/**
5771
+	 * Gets all the Unique Indexes on this model
5772
+	 *
5773
+	 * @return EE_Unique_Index[]
5774
+	 */
5775
+	public function unique_indexes()
5776
+	{
5777
+		$unique_indexes = array();
5778
+		foreach ($this->_indexes as $name => $index) {
5779
+			if ($index instanceof EE_Unique_Index) {
5780
+				$unique_indexes [ $name ] = $index;
5781
+			}
5782
+		}
5783
+		return $unique_indexes;
5784
+	}
5785
+
5786
+
5787
+
5788
+	/**
5789
+	 * Gets all the fields which, when combined, make the primary key.
5790
+	 * This is usually just an array with 1 element (the primary key), but in cases
5791
+	 * where there is no primary key, it's a combination of fields as defined
5792
+	 * on a primary index
5793
+	 *
5794
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5795
+	 * @throws EE_Error
5796
+	 */
5797
+	public function get_combined_primary_key_fields()
5798
+	{
5799
+		foreach ($this->indexes() as $index) {
5800
+			if ($index instanceof EE_Primary_Key_Index) {
5801
+				return $index->fields();
5802
+			}
5803
+		}
5804
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5805
+	}
5806
+
5807
+
5808
+
5809
+	/**
5810
+	 * Used to build a primary key string (when the model has no primary key),
5811
+	 * which can be used a unique string to identify this model object.
5812
+	 *
5813
+	 * @param array $fields_n_values keys are field names, values are their values.
5814
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5815
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5816
+	 *                               before passing it to this function (that will convert it from columns-n-values
5817
+	 *                               to field-names-n-values).
5818
+	 * @return string
5819
+	 * @throws EE_Error
5820
+	 */
5821
+	public function get_index_primary_key_string($fields_n_values)
5822
+	{
5823
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5824
+			$fields_n_values,
5825
+			$this->get_combined_primary_key_fields()
5826
+		);
5827
+		return http_build_query($cols_n_values_for_primary_key_index);
5828
+	}
5829
+
5830
+
5831
+
5832
+	/**
5833
+	 * Gets the field values from the primary key string
5834
+	 *
5835
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5836
+	 * @param string $index_primary_key_string
5837
+	 * @return null|array
5838
+	 * @throws EE_Error
5839
+	 */
5840
+	public function parse_index_primary_key_string($index_primary_key_string)
5841
+	{
5842
+		$key_fields = $this->get_combined_primary_key_fields();
5843
+		// check all of them are in the $id
5844
+		$key_vals_in_combined_pk = array();
5845
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5846
+		foreach ($key_fields as $key_field_name => $field_obj) {
5847
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
+				return null;
5849
+			}
5850
+		}
5851
+		return $key_vals_in_combined_pk;
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * verifies that an array of key-value pairs for model fields has a key
5858
+	 * for each field comprising the primary key index
5859
+	 *
5860
+	 * @param array $key_vals
5861
+	 * @return boolean
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function has_all_combined_primary_key_fields($key_vals)
5865
+	{
5866
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5867
+		foreach ($keys_it_should_have as $key) {
5868
+			if (! isset($key_vals[ $key ])) {
5869
+				return false;
5870
+			}
5871
+		}
5872
+		return true;
5873
+	}
5874
+
5875
+
5876
+
5877
+	/**
5878
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5879
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5880
+	 *
5881
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5882
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5883
+	 * @throws EE_Error
5884
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5885
+	 *                                                              indexed)
5886
+	 */
5887
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5888
+	{
5889
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5890
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5891
+		} elseif (is_array($model_object_or_attributes_array)) {
5892
+			$attributes_array = $model_object_or_attributes_array;
5893
+		} else {
5894
+			throw new EE_Error(sprintf(esc_html__(
5895
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5896
+				"event_espresso"
5897
+			), $model_object_or_attributes_array));
5898
+		}
5899
+		// even copies obviously won't have the same ID, so remove the primary key
5900
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5901
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5902
+			unset($attributes_array[ $this->primary_key_name() ]);
5903
+		}
5904
+		if (isset($query_params[0])) {
5905
+			$query_params[0] = array_merge($attributes_array, $query_params);
5906
+		} else {
5907
+			$query_params[0] = $attributes_array;
5908
+		}
5909
+		return $this->get_all($query_params);
5910
+	}
5911
+
5912
+
5913
+
5914
+	/**
5915
+	 * Gets the first copy we find. See get_all_copies for more details
5916
+	 *
5917
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5918
+	 * @param array $query_params
5919
+	 * @return EE_Base_Class
5920
+	 * @throws EE_Error
5921
+	 */
5922
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5923
+	{
5924
+		if (! is_array($query_params)) {
5925
+			EE_Error::doing_it_wrong(
5926
+				'EEM_Base::get_one_copy',
5927
+				sprintf(
5928
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5929
+					gettype($query_params)
5930
+				),
5931
+				'4.6.0'
5932
+			);
5933
+			$query_params = array();
5934
+		}
5935
+		$query_params['limit'] = 1;
5936
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5937
+		if (is_array($copies)) {
5938
+			return array_shift($copies);
5939
+		}
5940
+		return null;
5941
+	}
5942
+
5943
+
5944
+
5945
+	/**
5946
+	 * Updates the item with the specified id. Ignores default query parameters because
5947
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5948
+	 *
5949
+	 * @param array      $fields_n_values keys are field names, values are their new values
5950
+	 * @param int|string $id              the value of the primary key to update
5951
+	 * @return int number of rows updated
5952
+	 * @throws EE_Error
5953
+	 */
5954
+	public function update_by_ID($fields_n_values, $id)
5955
+	{
5956
+		$query_params = array(
5957
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5958
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5959
+		);
5960
+		return $this->update($fields_n_values, $query_params);
5961
+	}
5962
+
5963
+
5964
+
5965
+	/**
5966
+	 * Changes an operator which was supplied to the models into one usable in SQL
5967
+	 *
5968
+	 * @param string $operator_supplied
5969
+	 * @return string an operator which can be used in SQL
5970
+	 * @throws EE_Error
5971
+	 */
5972
+	private function _prepare_operator_for_sql($operator_supplied)
5973
+	{
5974
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
+			: null;
5976
+		if ($sql_operator) {
5977
+			return $sql_operator;
5978
+		}
5979
+		throw new EE_Error(
5980
+			sprintf(
5981
+				esc_html__(
5982
+					"The operator '%s' is not in the list of valid operators: %s",
5983
+					"event_espresso"
5984
+				),
5985
+				$operator_supplied,
5986
+				implode(",", array_keys($this->_valid_operators))
5987
+			)
5988
+		);
5989
+	}
5990
+
5991
+
5992
+
5993
+	/**
5994
+	 * Gets the valid operators
5995
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5996
+	 */
5997
+	public function valid_operators()
5998
+	{
5999
+		return $this->_valid_operators;
6000
+	}
6001
+
6002
+
6003
+
6004
+	/**
6005
+	 * Gets the between-style operators (take 2 arguments).
6006
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6007
+	 */
6008
+	public function valid_between_style_operators()
6009
+	{
6010
+		return array_intersect(
6011
+			$this->valid_operators(),
6012
+			$this->_between_style_operators
6013
+		);
6014
+	}
6015
+
6016
+	/**
6017
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6018
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6019
+	 */
6020
+	public function valid_like_style_operators()
6021
+	{
6022
+		return array_intersect(
6023
+			$this->valid_operators(),
6024
+			$this->_like_style_operators
6025
+		);
6026
+	}
6027
+
6028
+	/**
6029
+	 * Gets the "in"-style operators
6030
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6031
+	 */
6032
+	public function valid_in_style_operators()
6033
+	{
6034
+		return array_intersect(
6035
+			$this->valid_operators(),
6036
+			$this->_in_style_operators
6037
+		);
6038
+	}
6039
+
6040
+	/**
6041
+	 * Gets the "null"-style operators (accept no arguments)
6042
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6043
+	 */
6044
+	public function valid_null_style_operators()
6045
+	{
6046
+		return array_intersect(
6047
+			$this->valid_operators(),
6048
+			$this->_null_style_operators
6049
+		);
6050
+	}
6051
+
6052
+	/**
6053
+	 * Gets an array where keys are the primary keys and values are their 'names'
6054
+	 * (as determined by the model object's name() function, which is often overridden)
6055
+	 *
6056
+	 * @param array $query_params like get_all's
6057
+	 * @return string[]
6058
+	 * @throws EE_Error
6059
+	 */
6060
+	public function get_all_names($query_params = array())
6061
+	{
6062
+		$objs = $this->get_all($query_params);
6063
+		$names = array();
6064
+		foreach ($objs as $obj) {
6065
+			$names[ $obj->ID() ] = $obj->name();
6066
+		}
6067
+		return $names;
6068
+	}
6069
+
6070
+
6071
+
6072
+	/**
6073
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6074
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6075
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6076
+	 * array_keys() on $model_objects.
6077
+	 *
6078
+	 * @param \EE_Base_Class[] $model_objects
6079
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6080
+	 *                                               in the returned array
6081
+	 * @return array
6082
+	 * @throws EE_Error
6083
+	 */
6084
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6085
+	{
6086
+		if (! $this->has_primary_key_field()) {
6087
+			if (WP_DEBUG) {
6088
+				EE_Error::add_error(
6089
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6090
+					__FILE__,
6091
+					__FUNCTION__,
6092
+					__LINE__
6093
+				);
6094
+			}
6095
+		}
6096
+		$IDs = array();
6097
+		foreach ($model_objects as $model_object) {
6098
+			$id = $model_object->ID();
6099
+			if (! $id) {
6100
+				if ($filter_out_empty_ids) {
6101
+					continue;
6102
+				}
6103
+				if (WP_DEBUG) {
6104
+					EE_Error::add_error(
6105
+						esc_html__(
6106
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6107
+							'event_espresso'
6108
+						),
6109
+						__FILE__,
6110
+						__FUNCTION__,
6111
+						__LINE__
6112
+					);
6113
+				}
6114
+			}
6115
+			$IDs[] = $id;
6116
+		}
6117
+		return $IDs;
6118
+	}
6119
+
6120
+
6121
+
6122
+	/**
6123
+	 * Returns the string used in capabilities relating to this model. If there
6124
+	 * are no capabilities that relate to this model returns false
6125
+	 *
6126
+	 * @return string|false
6127
+	 */
6128
+	public function cap_slug()
6129
+	{
6130
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6131
+	}
6132
+
6133
+
6134
+
6135
+	/**
6136
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6137
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6138
+	 * only returns the cap restrictions array in that context (ie, the array
6139
+	 * at that key)
6140
+	 *
6141
+	 * @param string $context
6142
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6143
+	 * @throws EE_Error
6144
+	 */
6145
+	public function cap_restrictions($context = EEM_Base::caps_read)
6146
+	{
6147
+		EEM_Base::verify_is_valid_cap_context($context);
6148
+		// check if we ought to run the restriction generator first
6149
+		if (
6150
+			isset($this->_cap_restriction_generators[ $context ])
6151
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6152
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
+		) {
6154
+			$this->_cap_restrictions[ $context ] = array_merge(
6155
+				$this->_cap_restrictions[ $context ],
6156
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
+			);
6158
+		}
6159
+		// and make sure we've finalized the construction of each restriction
6160
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6162
+				$where_conditions_obj->_finalize_construct($this);
6163
+			}
6164
+		}
6165
+		return $this->_cap_restrictions[ $context ];
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Indicating whether or not this model thinks its a wp core model
6172
+	 *
6173
+	 * @return boolean
6174
+	 */
6175
+	public function is_wp_core_model()
6176
+	{
6177
+		return $this->_wp_core_model;
6178
+	}
6179
+
6180
+
6181
+
6182
+	/**
6183
+	 * Gets all the caps that are missing which impose a restriction on
6184
+	 * queries made in this context
6185
+	 *
6186
+	 * @param string $context one of EEM_Base::caps_ constants
6187
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6188
+	 * @throws EE_Error
6189
+	 */
6190
+	public function caps_missing($context = EEM_Base::caps_read)
6191
+	{
6192
+		$missing_caps = array();
6193
+		$cap_restrictions = $this->cap_restrictions($context);
6194
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6195
+			if (
6196
+				! EE_Capabilities::instance()
6197
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
+			) {
6199
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6200
+			}
6201
+		}
6202
+		return $missing_caps;
6203
+	}
6204
+
6205
+
6206
+
6207
+	/**
6208
+	 * Gets the mapping from capability contexts to action strings used in capability names
6209
+	 *
6210
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6211
+	 * one of 'read', 'edit', or 'delete'
6212
+	 */
6213
+	public function cap_contexts_to_cap_action_map()
6214
+	{
6215
+		return apply_filters(
6216
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6217
+			$this->_cap_contexts_to_cap_action_map,
6218
+			$this
6219
+		);
6220
+	}
6221
+
6222
+
6223
+
6224
+	/**
6225
+	 * Gets the action string for the specified capability context
6226
+	 *
6227
+	 * @param string $context
6228
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6229
+	 * @throws EE_Error
6230
+	 */
6231
+	public function cap_action_for_context($context)
6232
+	{
6233
+		$mapping = $this->cap_contexts_to_cap_action_map();
6234
+		if (isset($mapping[ $context ])) {
6235
+			return $mapping[ $context ];
6236
+		}
6237
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6238
+			return $action;
6239
+		}
6240
+		throw new EE_Error(
6241
+			sprintf(
6242
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6243
+				$context,
6244
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6245
+			)
6246
+		);
6247
+	}
6248
+
6249
+
6250
+
6251
+	/**
6252
+	 * Returns all the capability contexts which are valid when querying models
6253
+	 *
6254
+	 * @return array
6255
+	 */
6256
+	public static function valid_cap_contexts()
6257
+	{
6258
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6259
+			self::caps_read,
6260
+			self::caps_read_admin,
6261
+			self::caps_edit,
6262
+			self::caps_delete,
6263
+		));
6264
+	}
6265
+
6266
+
6267
+
6268
+	/**
6269
+	 * Returns all valid options for 'default_where_conditions'
6270
+	 *
6271
+	 * @return array
6272
+	 */
6273
+	public static function valid_default_where_conditions()
6274
+	{
6275
+		return array(
6276
+			EEM_Base::default_where_conditions_all,
6277
+			EEM_Base::default_where_conditions_this_only,
6278
+			EEM_Base::default_where_conditions_others_only,
6279
+			EEM_Base::default_where_conditions_minimum_all,
6280
+			EEM_Base::default_where_conditions_minimum_others,
6281
+			EEM_Base::default_where_conditions_none
6282
+		);
6283
+	}
6284
+
6285
+	// public static function default_where_conditions_full
6286
+	/**
6287
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6288
+	 *
6289
+	 * @param string $context
6290
+	 * @return bool
6291
+	 * @throws EE_Error
6292
+	 */
6293
+	public static function verify_is_valid_cap_context($context)
6294
+	{
6295
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6296
+		if (in_array($context, $valid_cap_contexts)) {
6297
+			return true;
6298
+		}
6299
+		throw new EE_Error(
6300
+			sprintf(
6301
+				esc_html__(
6302
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6303
+					'event_espresso'
6304
+				),
6305
+				$context,
6306
+				'EEM_Base',
6307
+				implode(',', $valid_cap_contexts)
6308
+			)
6309
+		);
6310
+	}
6311
+
6312
+
6313
+
6314
+	/**
6315
+	 * Clears all the models field caches. This is only useful when a sub-class
6316
+	 * might have added a field or something and these caches might be invalidated
6317
+	 */
6318
+	protected function _invalidate_field_caches()
6319
+	{
6320
+		$this->_cache_foreign_key_to_fields = array();
6321
+		$this->_cached_fields = null;
6322
+		$this->_cached_fields_non_db_only = null;
6323
+	}
6324
+
6325
+
6326
+
6327
+	/**
6328
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6329
+	 * (eg "and", "or", "not").
6330
+	 *
6331
+	 * @return array
6332
+	 */
6333
+	public function logic_query_param_keys()
6334
+	{
6335
+		return $this->_logic_query_param_keys;
6336
+	}
6337
+
6338
+
6339
+
6340
+	/**
6341
+	 * Determines whether or not the where query param array key is for a logic query param.
6342
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6343
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6344
+	 *
6345
+	 * @param $query_param_key
6346
+	 * @return bool
6347
+	 */
6348
+	public function is_logic_query_param_key($query_param_key)
6349
+	{
6350
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6351
+			if (
6352
+				$query_param_key === $logic_query_param_key
6353
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
+			) {
6355
+				return true;
6356
+			}
6357
+		}
6358
+		return false;
6359
+	}
6360
+
6361
+	/**
6362
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6363
+	 * @since 4.9.74.p
6364
+	 * @return boolean
6365
+	 */
6366
+	public function hasPassword()
6367
+	{
6368
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6369
+		if ($this->has_password_field === null) {
6370
+			$password_field = $this->getPasswordField();
6371
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6372
+		}
6373
+		return $this->has_password_field;
6374
+	}
6375
+
6376
+	/**
6377
+	 * Returns the password field on this model, if there is one
6378
+	 * @since 4.9.74.p
6379
+	 * @return EE_Password_Field|null
6380
+	 */
6381
+	public function getPasswordField()
6382
+	{
6383
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6384
+		// there's no need to search for it. If we don't know yet, then find out
6385
+		if ($this->has_password_field === null && $this->password_field === null) {
6386
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6387
+		}
6388
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6389
+		return $this->password_field;
6390
+	}
6391
+
6392
+
6393
+	/**
6394
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6395
+	 * @since 4.9.74.p
6396
+	 * @return EE_Model_Field_Base[]
6397
+	 * @throws EE_Error
6398
+	 */
6399
+	public function getPasswordProtectedFields()
6400
+	{
6401
+		$password_field = $this->getPasswordField();
6402
+		$fields = array();
6403
+		if ($password_field instanceof EE_Password_Field) {
6404
+			$field_names = $password_field->protectedFields();
6405
+			foreach ($field_names as $field_name) {
6406
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6407
+			}
6408
+		}
6409
+		return $fields;
6410
+	}
6411
+
6412
+
6413
+	/**
6414
+	 * Checks if the current user can perform the requested action on this model
6415
+	 * @since 4.9.74.p
6416
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6417
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6418
+	 * @return bool
6419
+	 * @throws EE_Error
6420
+	 * @throws InvalidArgumentException
6421
+	 * @throws InvalidDataTypeException
6422
+	 * @throws InvalidInterfaceException
6423
+	 * @throws ReflectionException
6424
+	 * @throws UnexpectedEntityException
6425
+	 */
6426
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6427
+	{
6428
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6429
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6430
+		}
6431
+		if (!is_array($model_obj_or_fields_n_values)) {
6432
+			throw new UnexpectedEntityException(
6433
+				$model_obj_or_fields_n_values,
6434
+				'EE_Base_Class',
6435
+				sprintf(
6436
+					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'),
6437
+					__FUNCTION__
6438
+				)
6439
+			);
6440
+		}
6441
+		return $this->exists(
6442
+			$this->alter_query_params_to_restrict_by_ID(
6443
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6444
+				array(
6445
+					'default_where_conditions' => 'none',
6446
+					'caps'                     => $cap_to_check,
6447
+				)
6448
+			)
6449
+		);
6450
+	}
6451
+
6452
+	/**
6453
+	 * Returns the query param where conditions key to the password affecting this model.
6454
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6455
+	 * @since 4.9.74.p
6456
+	 * @return null|string
6457
+	 * @throws EE_Error
6458
+	 * @throws InvalidArgumentException
6459
+	 * @throws InvalidDataTypeException
6460
+	 * @throws InvalidInterfaceException
6461
+	 * @throws ModelConfigurationException
6462
+	 * @throws ReflectionException
6463
+	 */
6464
+	public function modelChainAndPassword()
6465
+	{
6466
+		if ($this->model_chain_to_password === null) {
6467
+			throw new ModelConfigurationException(
6468
+				$this,
6469
+				esc_html_x(
6470
+				// @codingStandardsIgnoreStart
6471
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6472
+					// @codingStandardsIgnoreEnd
6473
+					'1: model name',
6474
+					'event_espresso'
6475
+				)
6476
+			);
6477
+		}
6478
+		if ($this->model_chain_to_password === '') {
6479
+			$model_with_password = $this;
6480
+		} else {
6481
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6482
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6483
+			} else {
6484
+				$last_model_in_chain = $this->model_chain_to_password;
6485
+			}
6486
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6487
+		}
6488
+
6489
+		$password_field = $model_with_password->getPasswordField();
6490
+		if ($password_field instanceof EE_Password_Field) {
6491
+			$password_field_name = $password_field->get_name();
6492
+		} else {
6493
+			throw new ModelConfigurationException(
6494
+				$this,
6495
+				sprintf(
6496
+					esc_html_x(
6497
+						'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"',
6498
+						'1: model name, 2: special string',
6499
+						'event_espresso'
6500
+					),
6501
+					$model_with_password->get_this_model_name(),
6502
+					$this->model_chain_to_password
6503
+				)
6504
+			);
6505
+		}
6506
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
+	}
6508
+
6509
+	/**
6510
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6511
+	 * or if this model itself has a password affecting access to some of its other fields.
6512
+	 * @since 4.9.74.p
6513
+	 * @return boolean
6514
+	 */
6515
+	public function restrictedByRelatedModelPassword()
6516
+	{
6517
+		return $this->model_chain_to_password !== null;
6518
+	}
6519 6519
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3347 added lines, -3347 removed lines patch added patch discarded remove patch
@@ -14,3363 +14,3363 @@
 block discarded – undo
14 14
 abstract class EE_Base_Class
15 15
 {
16 16
 
17
-    /**
18
-     * This is an array of the original properties and values provided during construction
19
-     * of this model object. (keys are model field names, values are their values).
20
-     * This list is important to remember so that when we are merging data from the db, we know
21
-     * which values to override and which to not override.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $_props_n_values_provided_in_constructor;
26
-
27
-    /**
28
-     * Timezone
29
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
30
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
31
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
32
-     * access to it.
33
-     *
34
-     * @var string
35
-     */
36
-    protected $_timezone;
37
-
38
-    /**
39
-     * date format
40
-     * pattern or format for displaying dates
41
-     *
42
-     * @var string $_dt_frmt
43
-     */
44
-    protected $_dt_frmt;
45
-
46
-    /**
47
-     * time format
48
-     * pattern or format for displaying time
49
-     *
50
-     * @var string $_tm_frmt
51
-     */
52
-    protected $_tm_frmt;
53
-
54
-    /**
55
-     * This property is for holding a cached array of object properties indexed by property name as the key.
56
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
57
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
58
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
59
-     *
60
-     * @var array
61
-     */
62
-    protected $_cached_properties = array();
63
-
64
-    /**
65
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
66
-     * single
67
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
68
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
69
-     * all others have an array)
70
-     *
71
-     * @var array
72
-     */
73
-    protected $_model_relations = array();
74
-
75
-    /**
76
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
77
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
78
-     *
79
-     * @var array
80
-     */
81
-    protected $_fields = array();
82
-
83
-    /**
84
-     * @var boolean indicating whether or not this model object is intended to ever be saved
85
-     * For example, we might create model objects intended to only be used for the duration
86
-     * of this request and to be thrown away, and if they were accidentally saved
87
-     * it would be a bug.
88
-     */
89
-    protected $_allow_persist = true;
90
-
91
-    /**
92
-     * @var boolean indicating whether or not this model object's properties have changed since construction
93
-     */
94
-    protected $_has_changes = false;
95
-
96
-    /**
97
-     * @var EEM_Base
98
-     */
99
-    protected $_model;
100
-
101
-    /**
102
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
103
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
104
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
105
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
106
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
107
-     * array as:
108
-     * array(
109
-     *  'Registration_Count' => 24
110
-     * );
111
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
112
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
113
-     * info)
114
-     *
115
-     * @var array
116
-     */
117
-    protected $custom_selection_results = array();
118
-
119
-
120
-    /**
121
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
-     * play nice
123
-     *
124
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
-     *                                                         TXN_amount, QST_name, etc) and values are their values
127
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
-     *                                                         corresponding db model or not.
129
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
-     *                                                         be in when instantiating a EE_Base_Class object.
131
-     * @param array   $date_formats                            An array of date formats to set on construct where first
132
-     *                                                         value is the date_format and second value is the time
133
-     *                                                         format.
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidInterfaceException
136
-     * @throws InvalidDataTypeException
137
-     * @throws EE_Error
138
-     * @throws ReflectionException
139
-     */
140
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
141
-    {
142
-        $className = get_class($this);
143
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
-        $model = $this->get_model();
145
-        $model_fields = $model->field_settings(false);
146
-        // ensure $fieldValues is an array
147
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
148
-        // verify client code has not passed any invalid field names
149
-        foreach ($fieldValues as $field_name => $field_value) {
150
-            if (! isset($model_fields[ $field_name ])) {
151
-                throw new EE_Error(
152
-                    sprintf(
153
-                        esc_html__(
154
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
-                            'event_espresso'
156
-                        ),
157
-                        $field_name,
158
-                        get_class($this),
159
-                        implode(', ', array_keys($model_fields))
160
-                    )
161
-                );
162
-            }
163
-        }
164
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
165
-        if (! empty($date_formats) && is_array($date_formats)) {
166
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
-        } else {
168
-            // set default formats for date and time
169
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
-        }
172
-        // if db model is instantiating
173
-        if ($bydb) {
174
-            // client code has indicated these field values are from the database
175
-            foreach ($model_fields as $fieldName => $field) {
176
-                $this->set_from_db(
177
-                    $fieldName,
178
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
-                );
180
-            }
181
-        } else {
182
-            // we're constructing a brand
183
-            // new instance of the model object. Generally, this means we'll need to do more field validation
184
-            foreach ($model_fields as $fieldName => $field) {
185
-                $this->set(
186
-                    $fieldName,
187
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
-                    true
189
-                );
190
-            }
191
-        }
192
-        // remember what values were passed to this constructor
193
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
194
-        // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
-            $model->add_to_entity_map($this);
197
-        }
198
-        // setup all the relations
199
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = array();
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
217
-     *
218
-     * @return boolean
219
-     */
220
-    public function allow_persist()
221
-    {
222
-        return $this->_allow_persist;
223
-    }
224
-
225
-
226
-    /**
227
-     * Sets whether or not this model object should be allowed to be saved to the DB.
228
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
-     * you got new information that somehow made you change your mind.
230
-     *
231
-     * @param boolean $allow_persist
232
-     * @return boolean
233
-     */
234
-    public function set_allow_persist($allow_persist)
235
-    {
236
-        return $this->_allow_persist = $allow_persist;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the field's original value when this object was constructed during this request.
242
-     * This can be helpful when determining if a model object has changed or not
243
-     *
244
-     * @param string $field_name
245
-     * @return mixed|null
246
-     * @throws ReflectionException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
257
-        ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
-        }
260
-        return null;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param EE_Base_Class $obj
266
-     * @return string
267
-     */
268
-    public function get_class($obj)
269
-    {
270
-        return get_class($obj);
271
-    }
272
-
273
-
274
-    /**
275
-     * Overrides parent because parent expects old models.
276
-     * This also doesn't do any validation, and won't work for serialized arrays
277
-     *
278
-     * @param    string $field_name
279
-     * @param    mixed  $field_value
280
-     * @param bool      $use_default
281
-     * @throws InvalidArgumentException
282
-     * @throws InvalidInterfaceException
283
-     * @throws InvalidDataTypeException
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     * @throws ReflectionException
288
-     */
289
-    public function set($field_name, $field_value, $use_default = false)
290
-    {
291
-        // if not using default and nothing has changed, and object has already been setup (has ID),
292
-        // then don't do anything
293
-        if (
294
-            ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
296
-            && $this->ID()
297
-        ) {
298
-            return;
299
-        }
300
-        $model = $this->get_model();
301
-        $this->_has_changes = true;
302
-        $field_obj = $model->field_settings_for($field_name);
303
-        if ($field_obj instanceof EE_Model_Field_Base) {
304
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
305
-            if ($field_obj instanceof EE_Datetime_Field) {
306
-                $field_obj->set_timezone($this->_timezone);
307
-                $field_obj->set_date_format($this->_dt_frmt);
308
-                $field_obj->set_time_format($this->_tm_frmt);
309
-            }
310
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
311
-            // should the value be null?
312
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
313
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
314
-                /**
315
-                 * To save having to refactor all the models, if a default value is used for a
316
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
317
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
318
-                 * object.
319
-                 *
320
-                 * @since 4.6.10+
321
-                 */
322
-                if (
323
-                    $field_obj instanceof EE_Datetime_Field
324
-                    && $this->_fields[ $field_name ] !== null
325
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
326
-                ) {
327
-                    empty($this->_fields[ $field_name ])
328
-                        ? $this->set($field_name, time())
329
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
330
-                }
331
-            } else {
332
-                $this->_fields[ $field_name ] = $holder_of_value;
333
-            }
334
-            // if we're not in the constructor...
335
-            // now check if what we set was a primary key
336
-            if (
17
+	/**
18
+	 * This is an array of the original properties and values provided during construction
19
+	 * of this model object. (keys are model field names, values are their values).
20
+	 * This list is important to remember so that when we are merging data from the db, we know
21
+	 * which values to override and which to not override.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $_props_n_values_provided_in_constructor;
26
+
27
+	/**
28
+	 * Timezone
29
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
30
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
31
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
32
+	 * access to it.
33
+	 *
34
+	 * @var string
35
+	 */
36
+	protected $_timezone;
37
+
38
+	/**
39
+	 * date format
40
+	 * pattern or format for displaying dates
41
+	 *
42
+	 * @var string $_dt_frmt
43
+	 */
44
+	protected $_dt_frmt;
45
+
46
+	/**
47
+	 * time format
48
+	 * pattern or format for displaying time
49
+	 *
50
+	 * @var string $_tm_frmt
51
+	 */
52
+	protected $_tm_frmt;
53
+
54
+	/**
55
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
56
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
57
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
58
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
59
+	 *
60
+	 * @var array
61
+	 */
62
+	protected $_cached_properties = array();
63
+
64
+	/**
65
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
66
+	 * single
67
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
68
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
69
+	 * all others have an array)
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected $_model_relations = array();
74
+
75
+	/**
76
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
77
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
78
+	 *
79
+	 * @var array
80
+	 */
81
+	protected $_fields = array();
82
+
83
+	/**
84
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
85
+	 * For example, we might create model objects intended to only be used for the duration
86
+	 * of this request and to be thrown away, and if they were accidentally saved
87
+	 * it would be a bug.
88
+	 */
89
+	protected $_allow_persist = true;
90
+
91
+	/**
92
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
93
+	 */
94
+	protected $_has_changes = false;
95
+
96
+	/**
97
+	 * @var EEM_Base
98
+	 */
99
+	protected $_model;
100
+
101
+	/**
102
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
103
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
104
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
105
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
106
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
107
+	 * array as:
108
+	 * array(
109
+	 *  'Registration_Count' => 24
110
+	 * );
111
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
112
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
113
+	 * info)
114
+	 *
115
+	 * @var array
116
+	 */
117
+	protected $custom_selection_results = array();
118
+
119
+
120
+	/**
121
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
+	 * play nice
123
+	 *
124
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
127
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
+	 *                                                         corresponding db model or not.
129
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
+	 *                                                         be in when instantiating a EE_Base_Class object.
131
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
132
+	 *                                                         value is the date_format and second value is the time
133
+	 *                                                         format.
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidInterfaceException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws EE_Error
138
+	 * @throws ReflectionException
139
+	 */
140
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
141
+	{
142
+		$className = get_class($this);
143
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
+		$model = $this->get_model();
145
+		$model_fields = $model->field_settings(false);
146
+		// ensure $fieldValues is an array
147
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
148
+		// verify client code has not passed any invalid field names
149
+		foreach ($fieldValues as $field_name => $field_value) {
150
+			if (! isset($model_fields[ $field_name ])) {
151
+				throw new EE_Error(
152
+					sprintf(
153
+						esc_html__(
154
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
+							'event_espresso'
156
+						),
157
+						$field_name,
158
+						get_class($this),
159
+						implode(', ', array_keys($model_fields))
160
+					)
161
+				);
162
+			}
163
+		}
164
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
165
+		if (! empty($date_formats) && is_array($date_formats)) {
166
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
+		} else {
168
+			// set default formats for date and time
169
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
+		}
172
+		// if db model is instantiating
173
+		if ($bydb) {
174
+			// client code has indicated these field values are from the database
175
+			foreach ($model_fields as $fieldName => $field) {
176
+				$this->set_from_db(
177
+					$fieldName,
178
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
+				);
180
+			}
181
+		} else {
182
+			// we're constructing a brand
183
+			// new instance of the model object. Generally, this means we'll need to do more field validation
184
+			foreach ($model_fields as $fieldName => $field) {
185
+				$this->set(
186
+					$fieldName,
187
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
+					true
189
+				);
190
+			}
191
+		}
192
+		// remember what values were passed to this constructor
193
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
194
+		// remember in entity mapper
195
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
+			$model->add_to_entity_map($this);
197
+		}
198
+		// setup all the relations
199
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = array();
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
217
+	 *
218
+	 * @return boolean
219
+	 */
220
+	public function allow_persist()
221
+	{
222
+		return $this->_allow_persist;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
228
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
+	 * you got new information that somehow made you change your mind.
230
+	 *
231
+	 * @param boolean $allow_persist
232
+	 * @return boolean
233
+	 */
234
+	public function set_allow_persist($allow_persist)
235
+	{
236
+		return $this->_allow_persist = $allow_persist;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the field's original value when this object was constructed during this request.
242
+	 * This can be helpful when determining if a model object has changed or not
243
+	 *
244
+	 * @param string $field_name
245
+	 * @return mixed|null
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (
255
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
257
+		) {
258
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
+		}
260
+		return null;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param EE_Base_Class $obj
266
+	 * @return string
267
+	 */
268
+	public function get_class($obj)
269
+	{
270
+		return get_class($obj);
271
+	}
272
+
273
+
274
+	/**
275
+	 * Overrides parent because parent expects old models.
276
+	 * This also doesn't do any validation, and won't work for serialized arrays
277
+	 *
278
+	 * @param    string $field_name
279
+	 * @param    mixed  $field_value
280
+	 * @param bool      $use_default
281
+	 * @throws InvalidArgumentException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function set($field_name, $field_value, $use_default = false)
290
+	{
291
+		// if not using default and nothing has changed, and object has already been setup (has ID),
292
+		// then don't do anything
293
+		if (
294
+			! $use_default
295
+			&& $this->_fields[ $field_name ] === $field_value
296
+			&& $this->ID()
297
+		) {
298
+			return;
299
+		}
300
+		$model = $this->get_model();
301
+		$this->_has_changes = true;
302
+		$field_obj = $model->field_settings_for($field_name);
303
+		if ($field_obj instanceof EE_Model_Field_Base) {
304
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
305
+			if ($field_obj instanceof EE_Datetime_Field) {
306
+				$field_obj->set_timezone($this->_timezone);
307
+				$field_obj->set_date_format($this->_dt_frmt);
308
+				$field_obj->set_time_format($this->_tm_frmt);
309
+			}
310
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
311
+			// should the value be null?
312
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
313
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
314
+				/**
315
+				 * To save having to refactor all the models, if a default value is used for a
316
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
317
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
318
+				 * object.
319
+				 *
320
+				 * @since 4.6.10+
321
+				 */
322
+				if (
323
+					$field_obj instanceof EE_Datetime_Field
324
+					&& $this->_fields[ $field_name ] !== null
325
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
326
+				) {
327
+					empty($this->_fields[ $field_name ])
328
+						? $this->set($field_name, time())
329
+						: $this->set($field_name, $this->_fields[ $field_name ]);
330
+				}
331
+			} else {
332
+				$this->_fields[ $field_name ] = $holder_of_value;
333
+			}
334
+			// if we're not in the constructor...
335
+			// now check if what we set was a primary key
336
+			if (
337 337
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
338
-                $this->_props_n_values_provided_in_constructor
339
-                && $field_value
340
-                && $field_name === $model->primary_key_name()
341
-            ) {
342
-                // if so, we want all this object's fields to be filled either with
343
-                // what we've explicitly set on this model
344
-                // or what we have in the db
345
-                // echo "setting primary key!";
346
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
347
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
348
-                foreach ($fields_on_model as $field_obj) {
349
-                    if (
350
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
351
-                        && $field_obj->get_name() !== $field_name
352
-                    ) {
353
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
354
-                    }
355
-                }
356
-                // oh this model object has an ID? well make sure its in the entity mapper
357
-                $model->add_to_entity_map($this);
358
-            }
359
-            // let's unset any cache for this field_name from the $_cached_properties property.
360
-            $this->_clear_cached_property($field_name);
361
-        } else {
362
-            throw new EE_Error(
363
-                sprintf(
364
-                    esc_html__(
365
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
366
-                        'event_espresso'
367
-                    ),
368
-                    $field_name
369
-                )
370
-            );
371
-        }
372
-    }
373
-
374
-
375
-    /**
376
-     * Set custom select values for model.
377
-     *
378
-     * @param array $custom_select_values
379
-     */
380
-    public function setCustomSelectsValues(array $custom_select_values)
381
-    {
382
-        $this->custom_selection_results = $custom_select_values;
383
-    }
384
-
385
-
386
-    /**
387
-     * Returns the custom select value for the provided alias if its set.
388
-     * If not set, returns null.
389
-     *
390
-     * @param string $alias
391
-     * @return string|int|float|null
392
-     */
393
-    public function getCustomSelect($alias)
394
-    {
395
-        return isset($this->custom_selection_results[ $alias ])
396
-            ? $this->custom_selection_results[ $alias ]
397
-            : null;
398
-    }
399
-
400
-
401
-    /**
402
-     * This sets the field value on the db column if it exists for the given $column_name or
403
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
-     *
405
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
406
-     * @param string $field_name  Must be the exact column name.
407
-     * @param mixed  $field_value The value to set.
408
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidInterfaceException
411
-     * @throws InvalidDataTypeException
412
-     * @throws EE_Error
413
-     * @throws ReflectionException
414
-     */
415
-    public function set_field_or_extra_meta($field_name, $field_value)
416
-    {
417
-        if ($this->get_model()->has_field($field_name)) {
418
-            $this->set($field_name, $field_value);
419
-            return true;
420
-        }
421
-        // ensure this object is saved first so that extra meta can be properly related.
422
-        $this->save();
423
-        return $this->update_extra_meta($field_name, $field_value);
424
-    }
425
-
426
-
427
-    /**
428
-     * This retrieves the value of the db column set on this class or if that's not present
429
-     * it will attempt to retrieve from extra_meta if found.
430
-     * Example Usage:
431
-     * Via EE_Message child class:
432
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
435
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
-     * value for those extra fields dynamically via the EE_message object.
437
-     *
438
-     * @param  string $field_name expecting the fully qualified field name.
439
-     * @return mixed|null  value for the field if found.  null if not found.
440
-     * @throws ReflectionException
441
-     * @throws InvalidArgumentException
442
-     * @throws InvalidInterfaceException
443
-     * @throws InvalidDataTypeException
444
-     * @throws EE_Error
445
-     */
446
-    public function get_field_or_extra_meta($field_name)
447
-    {
448
-        if ($this->get_model()->has_field($field_name)) {
449
-            $column_value = $this->get($field_name);
450
-        } else {
451
-            // This isn't a column in the main table, let's see if it is in the extra meta.
452
-            $column_value = $this->get_extra_meta($field_name, true, null);
453
-        }
454
-        return $column_value;
455
-    }
456
-
457
-
458
-    /**
459
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
-     *
464
-     * @access public
465
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
-     * @return void
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidInterfaceException
469
-     * @throws InvalidDataTypeException
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function set_timezone($timezone = '')
474
-    {
475
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
476
-        // make sure we clear all cached properties because they won't be relevant now
477
-        $this->_clear_cached_properties();
478
-        // make sure we update field settings and the date for all EE_Datetime_Fields
479
-        $model_fields = $this->get_model()->field_settings(false);
480
-        foreach ($model_fields as $field_name => $field_obj) {
481
-            if ($field_obj instanceof EE_Datetime_Field) {
482
-                $field_obj->set_timezone($this->_timezone);
483
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
484
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
-                }
486
-            }
487
-        }
488
-    }
489
-
490
-
491
-    /**
492
-     * This just returns whatever is set for the current timezone.
493
-     *
494
-     * @access public
495
-     * @return string timezone string
496
-     */
497
-    public function get_timezone()
498
-    {
499
-        return $this->_timezone;
500
-    }
501
-
502
-
503
-    /**
504
-     * This sets the internal date format to what is sent in to be used as the new default for the class
505
-     * internally instead of wp set date format options
506
-     *
507
-     * @since 4.6
508
-     * @param string $format should be a format recognizable by PHP date() functions.
509
-     */
510
-    public function set_date_format($format)
511
-    {
512
-        $this->_dt_frmt = $format;
513
-        // clear cached_properties because they won't be relevant now.
514
-        $this->_clear_cached_properties();
515
-    }
516
-
517
-
518
-    /**
519
-     * This sets the internal time format string to what is sent in to be used as the new default for the
520
-     * class internally instead of wp set time format options.
521
-     *
522
-     * @since 4.6
523
-     * @param string $format should be a format recognizable by PHP date() functions.
524
-     */
525
-    public function set_time_format($format)
526
-    {
527
-        $this->_tm_frmt = $format;
528
-        // clear cached_properties because they won't be relevant now.
529
-        $this->_clear_cached_properties();
530
-    }
531
-
532
-
533
-    /**
534
-     * This returns the current internal set format for the date and time formats.
535
-     *
536
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
537
-     *                             where the first value is the date format and the second value is the time format.
538
-     * @return mixed string|array
539
-     */
540
-    public function get_format($full = true)
541
-    {
542
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
-    }
544
-
545
-
546
-    /**
547
-     * cache
548
-     * stores the passed model object on the current model object.
549
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
550
-     *
551
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
552
-     *                                       'Registration' associated with this model object
553
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
554
-     *                                       that could be a payment or a registration)
555
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
556
-     *                                       items which will be stored in an array on this object
557
-     * @throws ReflectionException
558
-     * @throws InvalidArgumentException
559
-     * @throws InvalidInterfaceException
560
-     * @throws InvalidDataTypeException
561
-     * @throws EE_Error
562
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
563
-     *                                       related thing, no array)
564
-     */
565
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
566
-    {
567
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
568
-        if (! $object_to_cache instanceof EE_Base_Class) {
569
-            return false;
570
-        }
571
-        // also get "how" the object is related, or throw an error
572
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
-            throw new EE_Error(
574
-                sprintf(
575
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
576
-                    $relationName,
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        // how many things are related ?
582
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
583
-            // if it's a "belongs to" relationship, then there's only one related model object
584
-            // eg, if this is a registration, there's only 1 attendee for it
585
-            // so for these model objects just set it to be cached
586
-            $this->_model_relations[ $relationName ] = $object_to_cache;
587
-            $return = true;
588
-        } else {
589
-            // otherwise, this is the "many" side of a one to many relationship,
590
-            // so we'll add the object to the array of related objects for that type.
591
-            // eg: if this is an event, there are many registrations for that event,
592
-            // so we cache the registrations in an array
593
-            if (! is_array($this->_model_relations[ $relationName ])) {
594
-                // if for some reason, the cached item is a model object,
595
-                // then stick that in the array, otherwise start with an empty array
596
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
-                                                           instanceof
598
-                                                           EE_Base_Class
599
-                    ? array($this->_model_relations[ $relationName ]) : array();
600
-            }
601
-            // first check for a cache_id which is normally empty
602
-            if (! empty($cache_id)) {
603
-                // if the cache_id exists, then it means we are purposely trying to cache this
604
-                // with a known key that can then be used to retrieve the object later on
605
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
-                $return = $cache_id;
607
-            } elseif ($object_to_cache->ID()) {
608
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
609
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
-                $return = $object_to_cache->ID();
611
-            } else {
612
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
613
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
614
-                // move the internal pointer to the end of the array
615
-                end($this->_model_relations[ $relationName ]);
616
-                // and grab the key so that we can return it
617
-                $return = key($this->_model_relations[ $relationName ]);
618
-            }
619
-        }
620
-        return $return;
621
-    }
622
-
623
-
624
-    /**
625
-     * For adding an item to the cached_properties property.
626
-     *
627
-     * @access protected
628
-     * @param string      $fieldname the property item the corresponding value is for.
629
-     * @param mixed       $value     The value we are caching.
630
-     * @param string|null $cache_type
631
-     * @return void
632
-     * @throws ReflectionException
633
-     * @throws InvalidArgumentException
634
-     * @throws InvalidInterfaceException
635
-     * @throws InvalidDataTypeException
636
-     * @throws EE_Error
637
-     */
638
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
639
-    {
640
-        // first make sure this property exists
641
-        $this->get_model()->field_settings_for($fieldname);
642
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
643
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
-    }
645
-
646
-
647
-    /**
648
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
649
-     * This also SETS the cache if we return the actual property!
650
-     *
651
-     * @param string $fieldname        the name of the property we're trying to retrieve
652
-     * @param bool   $pretty
653
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
654
-     *                                 (in cases where the same property may be used for different outputs
655
-     *                                 - i.e. datetime, money etc.)
656
-     *                                 It can also accept certain pre-defined "schema" strings
657
-     *                                 to define how to output the property.
658
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
659
-     * @return mixed                   whatever the value for the property is we're retrieving
660
-     * @throws ReflectionException
661
-     * @throws InvalidArgumentException
662
-     * @throws InvalidInterfaceException
663
-     * @throws InvalidDataTypeException
664
-     * @throws EE_Error
665
-     */
666
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
667
-    {
668
-        // verify the field exists
669
-        $model = $this->get_model();
670
-        $model->field_settings_for($fieldname);
671
-        $cache_type = $pretty ? 'pretty' : 'standard';
672
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
673
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
674
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
-        }
676
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
677
-        $this->_set_cached_property($fieldname, $value, $cache_type);
678
-        return $value;
679
-    }
680
-
681
-
682
-    /**
683
-     * If the cache didn't fetch the needed item, this fetches it.
684
-     *
685
-     * @param string $fieldname
686
-     * @param bool   $pretty
687
-     * @param string $extra_cache_ref
688
-     * @return mixed
689
-     * @throws InvalidArgumentException
690
-     * @throws InvalidInterfaceException
691
-     * @throws InvalidDataTypeException
692
-     * @throws EE_Error
693
-     * @throws ReflectionException
694
-     */
695
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
696
-    {
697
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
698
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
699
-        if ($field_obj instanceof EE_Datetime_Field) {
700
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
701
-        }
702
-        if (! isset($this->_fields[ $fieldname ])) {
703
-            $this->_fields[ $fieldname ] = null;
704
-        }
705
-        $value = $pretty
706
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
707
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
-        return $value;
709
-    }
710
-
711
-
712
-    /**
713
-     * set timezone, formats, and output for EE_Datetime_Field objects
714
-     *
715
-     * @param \EE_Datetime_Field $datetime_field
716
-     * @param bool               $pretty
717
-     * @param null               $date_or_time
718
-     * @return void
719
-     * @throws InvalidArgumentException
720
-     * @throws InvalidInterfaceException
721
-     * @throws InvalidDataTypeException
722
-     * @throws EE_Error
723
-     */
724
-    protected function _prepare_datetime_field(
725
-        EE_Datetime_Field $datetime_field,
726
-        $pretty = false,
727
-        $date_or_time = null
728
-    ) {
729
-        $datetime_field->set_timezone($this->_timezone);
730
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
-        // set the output returned
733
-        switch ($date_or_time) {
734
-            case 'D':
735
-                $datetime_field->set_date_time_output('date');
736
-                break;
737
-            case 'T':
738
-                $datetime_field->set_date_time_output('time');
739
-                break;
740
-            default:
741
-                $datetime_field->set_date_time_output();
742
-        }
743
-    }
744
-
745
-
746
-    /**
747
-     * This just takes care of clearing out the cached_properties
748
-     *
749
-     * @return void
750
-     */
751
-    protected function _clear_cached_properties()
752
-    {
753
-        $this->_cached_properties = array();
754
-    }
755
-
756
-
757
-    /**
758
-     * This just clears out ONE property if it exists in the cache
759
-     *
760
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
761
-     * @return void
762
-     */
763
-    protected function _clear_cached_property($property_name)
764
-    {
765
-        if (isset($this->_cached_properties[ $property_name ])) {
766
-            unset($this->_cached_properties[ $property_name ]);
767
-        }
768
-    }
769
-
770
-
771
-    /**
772
-     * Ensures that this related thing is a model object.
773
-     *
774
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
-     * @param string $model_name   name of the related thing, eg 'Attendee',
776
-     * @return EE_Base_Class
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
-    {
785
-        $other_model_instance = self::_get_model_instance_with_name(
786
-            self::_get_model_classname($model_name),
787
-            $this->_timezone
788
-        );
789
-        return $other_model_instance->ensure_is_obj($object_or_id);
790
-    }
791
-
792
-
793
-    /**
794
-     * Forgets the cached model of the given relation Name. So the next time we request it,
795
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
798
-     *
799
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
800
-     *                                                     Eg 'Registration'
801
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
804
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
-     *                                                     this is HasMany or HABTM.
806
-     * @throws ReflectionException
807
-     * @throws InvalidArgumentException
808
-     * @throws InvalidInterfaceException
809
-     * @throws InvalidDataTypeException
810
-     * @throws EE_Error
811
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
812
-     *                                                     relation from all
813
-     */
814
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
-    {
816
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
817
-        $index_in_cache = '';
818
-        if (! $relationship_to_model) {
819
-            throw new EE_Error(
820
-                sprintf(
821
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
822
-                    $relationName,
823
-                    get_class($this)
824
-                )
825
-            );
826
-        }
827
-        if ($clear_all) {
828
-            $obj_removed = true;
829
-            $this->_model_relations[ $relationName ] = null;
830
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
-            $obj_removed = $this->_model_relations[ $relationName ];
832
-            $this->_model_relations[ $relationName ] = null;
833
-        } else {
834
-            if (
835
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
836
-                && $object_to_remove_or_index_into_array->ID()
837
-            ) {
838
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
839
-                if (
840
-                    is_array($this->_model_relations[ $relationName ])
841
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
842
-                ) {
843
-                    $index_found_at = null;
844
-                    // find this object in the array even though it has a different key
845
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
846
-                        /** @noinspection TypeUnsafeComparisonInspection */
847
-                        if (
848
-                            $obj instanceof EE_Base_Class
849
-                            && (
850
-                                $obj == $object_to_remove_or_index_into_array
851
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
852
-                            )
853
-                        ) {
854
-                            $index_found_at = $index;
855
-                            break;
856
-                        }
857
-                    }
858
-                    if ($index_found_at) {
859
-                        $index_in_cache = $index_found_at;
860
-                    } else {
861
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
862
-                        // if it wasn't in it to begin with. So we're done
863
-                        return $object_to_remove_or_index_into_array;
864
-                    }
865
-                }
866
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
867
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
868
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
869
-                    /** @noinspection TypeUnsafeComparisonInspection */
870
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
871
-                        $index_in_cache = $index;
872
-                    }
873
-                }
874
-            } else {
875
-                $index_in_cache = $object_to_remove_or_index_into_array;
876
-            }
877
-            // supposedly we've found it. But it could just be that the client code
878
-            // provided a bad index/object
879
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
880
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
881
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
882
-            } else {
883
-                // that thing was never cached anyways.
884
-                $obj_removed = null;
885
-            }
886
-        }
887
-        return $obj_removed;
888
-    }
889
-
890
-
891
-    /**
892
-     * update_cache_after_object_save
893
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
894
-     * obtained after being saved to the db
895
-     *
896
-     * @param string        $relationName       - the type of object that is cached
897
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
898
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
899
-     * @return boolean TRUE on success, FALSE on fail
900
-     * @throws ReflectionException
901
-     * @throws InvalidArgumentException
902
-     * @throws InvalidInterfaceException
903
-     * @throws InvalidDataTypeException
904
-     * @throws EE_Error
905
-     */
906
-    public function update_cache_after_object_save(
907
-        $relationName,
908
-        EE_Base_Class $newly_saved_object,
909
-        $current_cache_id = ''
910
-    ) {
911
-        // verify that incoming object is of the correct type
912
-        $obj_class = 'EE_' . $relationName;
913
-        if ($newly_saved_object instanceof $obj_class) {
914
-            /* @type EE_Base_Class $newly_saved_object */
915
-            // now get the type of relation
916
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
917
-            // if this is a 1:1 relationship
918
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919
-                // then just replace the cached object with the newly saved object
920
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
921
-                return true;
922
-                // or if it's some kind of sordid feral polyamorous relationship...
923
-            }
924
-            if (
925
-                is_array($this->_model_relations[ $relationName ])
926
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
927
-            ) {
928
-                // then remove the current cached item
929
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
930
-                // and cache the newly saved object using it's new ID
931
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
-                return true;
933
-            }
934
-        }
935
-        return false;
936
-    }
937
-
938
-
939
-    /**
940
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
941
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
942
-     *
943
-     * @param string $relationName
944
-     * @return EE_Base_Class
945
-     */
946
-    public function get_one_from_cache($relationName)
947
-    {
948
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
949
-            ? $this->_model_relations[ $relationName ]
950
-            : null;
951
-        if (is_array($cached_array_or_object)) {
952
-            return array_shift($cached_array_or_object);
953
-        }
954
-        return $cached_array_or_object;
955
-    }
956
-
957
-
958
-    /**
959
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
960
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
961
-     *
962
-     * @param string $relationName
963
-     * @throws ReflectionException
964
-     * @throws InvalidArgumentException
965
-     * @throws InvalidInterfaceException
966
-     * @throws InvalidDataTypeException
967
-     * @throws EE_Error
968
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
969
-     */
970
-    public function get_all_from_cache($relationName)
971
-    {
972
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
973
-        // if the result is not an array, but exists, make it an array
974
-        $objects = is_array($objects) ? $objects : array($objects);
975
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
976
-        // basically, if this model object was stored in the session, and these cached model objects
977
-        // already have IDs, let's make sure they're in their model's entity mapper
978
-        // otherwise we will have duplicates next time we call
979
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
980
-        $model = EE_Registry::instance()->load_model($relationName);
981
-        foreach ($objects as $model_object) {
982
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
983
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
984
-                if ($model_object->ID()) {
985
-                    $model->add_to_entity_map($model_object);
986
-                }
987
-            } else {
988
-                throw new EE_Error(
989
-                    sprintf(
990
-                        esc_html__(
991
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
992
-                            'event_espresso'
993
-                        ),
994
-                        $relationName,
995
-                        gettype($model_object)
996
-                    )
997
-                );
998
-            }
999
-        }
1000
-        return $objects;
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1006
-     * matching the given query conditions.
1007
-     *
1008
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1009
-     * @param int   $limit              How many objects to return.
1010
-     * @param array $query_params       Any additional conditions on the query.
1011
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1012
-     *                                  you can indicate just the columns you want returned
1013
-     * @return array|EE_Base_Class[]
1014
-     * @throws ReflectionException
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidInterfaceException
1017
-     * @throws InvalidDataTypeException
1018
-     * @throws EE_Error
1019
-     */
1020
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1021
-    {
1022
-        $model = $this->get_model();
1023
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1024
-            ? $model->get_primary_key_field()->get_name()
1025
-            : $field_to_order_by;
1026
-        $current_value = ! empty($field) ? $this->get($field) : null;
1027
-        if (empty($field) || empty($current_value)) {
1028
-            return array();
1029
-        }
1030
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1036
-     * matching the given query conditions.
1037
-     *
1038
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1039
-     * @param int   $limit              How many objects to return.
1040
-     * @param array $query_params       Any additional conditions on the query.
1041
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1042
-     *                                  you can indicate just the columns you want returned
1043
-     * @return array|EE_Base_Class[]
1044
-     * @throws ReflectionException
1045
-     * @throws InvalidArgumentException
1046
-     * @throws InvalidInterfaceException
1047
-     * @throws InvalidDataTypeException
1048
-     * @throws EE_Error
1049
-     */
1050
-    public function previous_x(
1051
-        $field_to_order_by = null,
1052
-        $limit = 1,
1053
-        $query_params = array(),
1054
-        $columns_to_select = null
1055
-    ) {
1056
-        $model = $this->get_model();
1057
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1058
-            ? $model->get_primary_key_field()->get_name()
1059
-            : $field_to_order_by;
1060
-        $current_value = ! empty($field) ? $this->get($field) : null;
1061
-        if (empty($field) || empty($current_value)) {
1062
-            return array();
1063
-        }
1064
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1070
-     * matching the given query conditions.
1071
-     *
1072
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1073
-     * @param array $query_params       Any additional conditions on the query.
1074
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1075
-     *                                  you can indicate just the columns you want returned
1076
-     * @return array|EE_Base_Class
1077
-     * @throws ReflectionException
1078
-     * @throws InvalidArgumentException
1079
-     * @throws InvalidInterfaceException
1080
-     * @throws InvalidDataTypeException
1081
-     * @throws EE_Error
1082
-     */
1083
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1084
-    {
1085
-        $model = $this->get_model();
1086
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1087
-            ? $model->get_primary_key_field()->get_name()
1088
-            : $field_to_order_by;
1089
-        $current_value = ! empty($field) ? $this->get($field) : null;
1090
-        if (empty($field) || empty($current_value)) {
1091
-            return array();
1092
-        }
1093
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1099
-     * matching the given query conditions.
1100
-     *
1101
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1102
-     * @param array $query_params       Any additional conditions on the query.
1103
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1104
-     *                                  you can indicate just the column you want returned
1105
-     * @return array|EE_Base_Class
1106
-     * @throws ReflectionException
1107
-     * @throws InvalidArgumentException
1108
-     * @throws InvalidInterfaceException
1109
-     * @throws InvalidDataTypeException
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1113
-    {
1114
-        $model = $this->get_model();
1115
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1116
-            ? $model->get_primary_key_field()->get_name()
1117
-            : $field_to_order_by;
1118
-        $current_value = ! empty($field) ? $this->get($field) : null;
1119
-        if (empty($field) || empty($current_value)) {
1120
-            return array();
1121
-        }
1122
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Overrides parent because parent expects old models.
1128
-     * This also doesn't do any validation, and won't work for serialized arrays
1129
-     *
1130
-     * @param string $field_name
1131
-     * @param mixed  $field_value_from_db
1132
-     * @throws ReflectionException
1133
-     * @throws InvalidArgumentException
1134
-     * @throws InvalidInterfaceException
1135
-     * @throws InvalidDataTypeException
1136
-     * @throws EE_Error
1137
-     */
1138
-    public function set_from_db($field_name, $field_value_from_db)
1139
-    {
1140
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1141
-        if ($field_obj instanceof EE_Model_Field_Base) {
1142
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1143
-            // eg, a CPT model object could have an entry in the posts table, but no
1144
-            // entry in the meta table. Meaning that all its columns in the meta table
1145
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1146
-            if ($field_value_from_db === null) {
1147
-                if ($field_obj->is_nullable()) {
1148
-                    // if the field allows nulls, then let it be null
1149
-                    $field_value = null;
1150
-                } else {
1151
-                    $field_value = $field_obj->get_default_value();
1152
-                }
1153
-            } else {
1154
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1155
-            }
1156
-            $this->_fields[ $field_name ] = $field_value;
1157
-            $this->_clear_cached_property($field_name);
1158
-        }
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * verifies that the specified field is of the correct type
1164
-     *
1165
-     * @param string $field_name
1166
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
-     *                                (in cases where the same property may be used for different outputs
1168
-     *                                - i.e. datetime, money etc.)
1169
-     * @return mixed
1170
-     * @throws ReflectionException
1171
-     * @throws InvalidArgumentException
1172
-     * @throws InvalidInterfaceException
1173
-     * @throws InvalidDataTypeException
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get($field_name, $extra_cache_ref = null)
1177
-    {
1178
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1179
-    }
1180
-
1181
-
1182
-    /**
1183
-     * This method simply returns the RAW unprocessed value for the given property in this class
1184
-     *
1185
-     * @param  string $field_name A valid fieldname
1186
-     * @return mixed              Whatever the raw value stored on the property is.
1187
-     * @throws ReflectionException
1188
-     * @throws InvalidArgumentException
1189
-     * @throws InvalidInterfaceException
1190
-     * @throws InvalidDataTypeException
1191
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1192
-     */
1193
-    public function get_raw($field_name)
1194
-    {
1195
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1196
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1197
-            ? $this->_fields[ $field_name ]->format('U')
1198
-            : $this->_fields[ $field_name ];
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * This is used to return the internal DateTime object used for a field that is a
1204
-     * EE_Datetime_Field.
1205
-     *
1206
-     * @param string $field_name               The field name retrieving the DateTime object.
1207
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1208
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1209
-     *                                         EE_Datetime_Field and but the field value is null, then
1210
-     *                                         just null is returned (because that indicates that likely
1211
-     *                                         this field is nullable).
1212
-     * @throws InvalidArgumentException
1213
-     * @throws InvalidDataTypeException
1214
-     * @throws InvalidInterfaceException
1215
-     * @throws ReflectionException
1216
-     */
1217
-    public function get_DateTime_object($field_name)
1218
-    {
1219
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1220
-        if (! $field_settings instanceof EE_Datetime_Field) {
1221
-            EE_Error::add_error(
1222
-                sprintf(
1223
-                    esc_html__(
1224
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1225
-                        'event_espresso'
1226
-                    ),
1227
-                    $field_name
1228
-                ),
1229
-                __FILE__,
1230
-                __FUNCTION__,
1231
-                __LINE__
1232
-            );
1233
-            return false;
1234
-        }
1235
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1236
-            ? clone $this->_fields[ $field_name ]
1237
-            : null;
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * To be used in template to immediately echo out the value, and format it for output.
1243
-     * Eg, should call stripslashes and whatnot before echoing
1244
-     *
1245
-     * @param string $field_name      the name of the field as it appears in the DB
1246
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1247
-     *                                (in cases where the same property may be used for different outputs
1248
-     *                                - i.e. datetime, money etc.)
1249
-     * @return void
1250
-     * @throws ReflectionException
1251
-     * @throws InvalidArgumentException
1252
-     * @throws InvalidInterfaceException
1253
-     * @throws InvalidDataTypeException
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function e($field_name, $extra_cache_ref = null)
1257
-    {
1258
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1264
-     * can be easily used as the value of form input.
1265
-     *
1266
-     * @param string $field_name
1267
-     * @return void
1268
-     * @throws ReflectionException
1269
-     * @throws InvalidArgumentException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws InvalidDataTypeException
1272
-     * @throws EE_Error
1273
-     */
1274
-    public function f($field_name)
1275
-    {
1276
-        $this->e($field_name, 'form_input');
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * Same as `f()` but just returns the value instead of echoing it
1282
-     *
1283
-     * @param string $field_name
1284
-     * @return string
1285
-     * @throws ReflectionException
1286
-     * @throws InvalidArgumentException
1287
-     * @throws InvalidInterfaceException
1288
-     * @throws InvalidDataTypeException
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function get_f($field_name)
1292
-    {
1293
-        return (string) $this->get_pretty($field_name, 'form_input');
1294
-    }
1295
-
1296
-
1297
-    /**
1298
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1299
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1300
-     * to see what options are available.
1301
-     *
1302
-     * @param string $field_name
1303
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1304
-     *                                (in cases where the same property may be used for different outputs
1305
-     *                                - i.e. datetime, money etc.)
1306
-     * @return mixed
1307
-     * @throws ReflectionException
1308
-     * @throws InvalidArgumentException
1309
-     * @throws InvalidInterfaceException
1310
-     * @throws InvalidDataTypeException
1311
-     * @throws EE_Error
1312
-     */
1313
-    public function get_pretty($field_name, $extra_cache_ref = null)
1314
-    {
1315
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * This simply returns the datetime for the given field name
1321
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1322
-     * (and the equivalent e_date, e_time, e_datetime).
1323
-     *
1324
-     * @access   protected
1325
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1326
-     * @param string   $dt_frmt      valid datetime format used for date
1327
-     *                               (if '' then we just use the default on the field,
1328
-     *                               if NULL we use the last-used format)
1329
-     * @param string   $tm_frmt      Same as above except this is for time format
1330
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1331
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1332
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1333
-     *                               if field is not a valid dtt field, or void if echoing
1334
-     * @throws ReflectionException
1335
-     * @throws InvalidArgumentException
1336
-     * @throws InvalidInterfaceException
1337
-     * @throws InvalidDataTypeException
1338
-     * @throws EE_Error
1339
-     */
1340
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1341
-    {
1342
-        // clear cached property
1343
-        $this->_clear_cached_property($field_name);
1344
-        // reset format properties because they are used in get()
1345
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1346
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1347
-        if ($echo) {
1348
-            $this->e($field_name, $date_or_time);
1349
-            return '';
1350
-        }
1351
-        return $this->get($field_name, $date_or_time);
1352
-    }
1353
-
1354
-
1355
-    /**
1356
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1357
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1358
-     * other echoes the pretty value for dtt)
1359
-     *
1360
-     * @param  string $field_name name of model object datetime field holding the value
1361
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1362
-     * @return string            datetime value formatted
1363
-     * @throws ReflectionException
1364
-     * @throws InvalidArgumentException
1365
-     * @throws InvalidInterfaceException
1366
-     * @throws InvalidDataTypeException
1367
-     * @throws EE_Error
1368
-     */
1369
-    public function get_date($field_name, $format = '')
1370
-    {
1371
-        return $this->_get_datetime($field_name, $format, null, 'D');
1372
-    }
1373
-
1374
-
1375
-    /**
1376
-     * @param        $field_name
1377
-     * @param string $format
1378
-     * @throws ReflectionException
1379
-     * @throws InvalidArgumentException
1380
-     * @throws InvalidInterfaceException
1381
-     * @throws InvalidDataTypeException
1382
-     * @throws EE_Error
1383
-     */
1384
-    public function e_date($field_name, $format = '')
1385
-    {
1386
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1392
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1393
-     * other echoes the pretty value for dtt)
1394
-     *
1395
-     * @param  string $field_name name of model object datetime field holding the value
1396
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1397
-     * @return string             datetime value formatted
1398
-     * @throws ReflectionException
1399
-     * @throws InvalidArgumentException
1400
-     * @throws InvalidInterfaceException
1401
-     * @throws InvalidDataTypeException
1402
-     * @throws EE_Error
1403
-     */
1404
-    public function get_time($field_name, $format = '')
1405
-    {
1406
-        return $this->_get_datetime($field_name, null, $format, 'T');
1407
-    }
1408
-
1409
-
1410
-    /**
1411
-     * @param        $field_name
1412
-     * @param string $format
1413
-     * @throws ReflectionException
1414
-     * @throws InvalidArgumentException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws InvalidDataTypeException
1417
-     * @throws EE_Error
1418
-     */
1419
-    public function e_time($field_name, $format = '')
1420
-    {
1421
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1427
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1428
-     * other echoes the pretty value for dtt)
1429
-     *
1430
-     * @param  string $field_name name of model object datetime field holding the value
1431
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1432
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1433
-     * @return string             datetime value formatted
1434
-     * @throws ReflectionException
1435
-     * @throws InvalidArgumentException
1436
-     * @throws InvalidInterfaceException
1437
-     * @throws InvalidDataTypeException
1438
-     * @throws EE_Error
1439
-     */
1440
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1441
-    {
1442
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * @param string $field_name
1448
-     * @param string $dt_frmt
1449
-     * @param string $tm_frmt
1450
-     * @throws ReflectionException
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws EE_Error
1455
-     */
1456
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1457
-    {
1458
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1459
-    }
1460
-
1461
-
1462
-    /**
1463
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1464
-     *
1465
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1466
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1467
-     *                           on the object will be used.
1468
-     * @return string Date and time string in set locale or false if no field exists for the given
1469
-     * @throws ReflectionException
1470
-     * @throws InvalidArgumentException
1471
-     * @throws InvalidInterfaceException
1472
-     * @throws InvalidDataTypeException
1473
-     * @throws EE_Error
1474
-     *                           field name.
1475
-     */
1476
-    public function get_i18n_datetime($field_name, $format = '')
1477
-    {
1478
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
-        return date_i18n(
1480
-            $format,
1481
-            EEH_DTT_Helper::get_timestamp_with_offset(
1482
-                $this->get_raw($field_name),
1483
-                $this->_timezone
1484
-            )
1485
-        );
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1491
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1492
-     * thrown.
1493
-     *
1494
-     * @param  string $field_name The field name being checked
1495
-     * @throws ReflectionException
1496
-     * @throws InvalidArgumentException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws InvalidDataTypeException
1499
-     * @throws EE_Error
1500
-     * @return EE_Datetime_Field
1501
-     */
1502
-    protected function _get_dtt_field_settings($field_name)
1503
-    {
1504
-        $field = $this->get_model()->field_settings_for($field_name);
1505
-        // check if field is dtt
1506
-        if ($field instanceof EE_Datetime_Field) {
1507
-            return $field;
1508
-        }
1509
-        throw new EE_Error(
1510
-            sprintf(
1511
-                esc_html__(
1512
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1513
-                    'event_espresso'
1514
-                ),
1515
-                $field_name,
1516
-                self::_get_model_classname(get_class($this))
1517
-            )
1518
-        );
1519
-    }
1520
-
1521
-
1522
-
1523
-
1524
-    /**
1525
-     * NOTE ABOUT BELOW:
1526
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1527
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1528
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1529
-     * method and make sure you send the entire datetime value for setting.
1530
-     */
1531
-    /**
1532
-     * sets the time on a datetime property
1533
-     *
1534
-     * @access protected
1535
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1536
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1537
-     * @throws ReflectionException
1538
-     * @throws InvalidArgumentException
1539
-     * @throws InvalidInterfaceException
1540
-     * @throws InvalidDataTypeException
1541
-     * @throws EE_Error
1542
-     */
1543
-    protected function _set_time_for($time, $fieldname)
1544
-    {
1545
-        $this->_set_date_time('T', $time, $fieldname);
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * sets the date on a datetime property
1551
-     *
1552
-     * @access protected
1553
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1554
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1555
-     * @throws ReflectionException
1556
-     * @throws InvalidArgumentException
1557
-     * @throws InvalidInterfaceException
1558
-     * @throws InvalidDataTypeException
1559
-     * @throws EE_Error
1560
-     */
1561
-    protected function _set_date_for($date, $fieldname)
1562
-    {
1563
-        $this->_set_date_time('D', $date, $fieldname);
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * This takes care of setting a date or time independently on a given model object property. This method also
1569
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1570
-     *
1571
-     * @access protected
1572
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1573
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1574
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1575
-     *                                        EE_Datetime_Field property)
1576
-     * @throws ReflectionException
1577
-     * @throws InvalidArgumentException
1578
-     * @throws InvalidInterfaceException
1579
-     * @throws InvalidDataTypeException
1580
-     * @throws EE_Error
1581
-     */
1582
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1583
-    {
1584
-        $field = $this->_get_dtt_field_settings($fieldname);
1585
-        $field->set_timezone($this->_timezone);
1586
-        $field->set_date_format($this->_dt_frmt);
1587
-        $field->set_time_format($this->_tm_frmt);
1588
-        switch ($what) {
1589
-            case 'T':
1590
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
-                    $datetime_value,
1592
-                    $this->_fields[ $fieldname ]
1593
-                );
1594
-                $this->_has_changes = true;
1595
-                break;
1596
-            case 'D':
1597
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
-                    $datetime_value,
1599
-                    $this->_fields[ $fieldname ]
1600
-                );
1601
-                $this->_has_changes = true;
1602
-                break;
1603
-            case 'B':
1604
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
-                $this->_has_changes = true;
1606
-                break;
1607
-        }
1608
-        $this->_clear_cached_property($fieldname);
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
-     * that could lead to some unexpected results!
1617
-     *
1618
-     * @access public
1619
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
-     *                                         value being returned.
1621
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
-     * @param string $prepend                  You can include something to prepend on the timestamp
1624
-     * @param string $append                   You can include something to append on the timestamp
1625
-     * @throws ReflectionException
1626
-     * @throws InvalidArgumentException
1627
-     * @throws InvalidInterfaceException
1628
-     * @throws InvalidDataTypeException
1629
-     * @throws EE_Error
1630
-     * @return string timestamp
1631
-     */
1632
-    public function display_in_my_timezone(
1633
-        $field_name,
1634
-        $callback = 'get_datetime',
1635
-        $args = null,
1636
-        $prepend = '',
1637
-        $append = ''
1638
-    ) {
1639
-        $timezone = EEH_DTT_Helper::get_timezone();
1640
-        if ($timezone === $this->_timezone) {
1641
-            return '';
1642
-        }
1643
-        $original_timezone = $this->_timezone;
1644
-        $this->set_timezone($timezone);
1645
-        $fn = (array) $field_name;
1646
-        $args = array_merge($fn, (array) $args);
1647
-        if (! method_exists($this, $callback)) {
1648
-            throw new EE_Error(
1649
-                sprintf(
1650
-                    esc_html__(
1651
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
-                        'event_espresso'
1653
-                    ),
1654
-                    $callback
1655
-                )
1656
-            );
1657
-        }
1658
-        $args = (array) $args;
1659
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
-        $this->set_timezone($original_timezone);
1661
-        return $return;
1662
-    }
1663
-
1664
-
1665
-    /**
1666
-     * Deletes this model object.
1667
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
-     * override
1669
-     * `EE_Base_Class::_delete` NOT this class.
1670
-     *
1671
-     * @return boolean | int
1672
-     * @throws ReflectionException
1673
-     * @throws InvalidArgumentException
1674
-     * @throws InvalidInterfaceException
1675
-     * @throws InvalidDataTypeException
1676
-     * @throws EE_Error
1677
-     */
1678
-    public function delete()
1679
-    {
1680
-        /**
1681
-         * Called just before the `EE_Base_Class::_delete` method call.
1682
-         * Note:
1683
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
-         * should be aware that `_delete` may not always result in a permanent delete.
1685
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
-         * soft deletes (trash) the object and does not permanently delete it.
1687
-         *
1688
-         * @param EE_Base_Class $model_object about to be 'deleted'
1689
-         */
1690
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
-        $result = $this->_delete();
1692
-        /**
1693
-         * Called just after the `EE_Base_Class::_delete` method call.
1694
-         * Note:
1695
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
-         * should be aware that `_delete` may not always result in a permanent delete.
1697
-         * For example `EE_Soft_Base_Class::_delete`
1698
-         * soft deletes (trash) the object and does not permanently delete it.
1699
-         *
1700
-         * @param EE_Base_Class $model_object that was just 'deleted'
1701
-         * @param boolean       $result
1702
-         */
1703
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
-        return $result;
1705
-    }
1706
-
1707
-
1708
-    /**
1709
-     * Calls the specific delete method for the instantiated class.
1710
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
-     * `EE_Base_Class::delete`
1713
-     *
1714
-     * @return bool|int
1715
-     * @throws ReflectionException
1716
-     * @throws InvalidArgumentException
1717
-     * @throws InvalidInterfaceException
1718
-     * @throws InvalidDataTypeException
1719
-     * @throws EE_Error
1720
-     */
1721
-    protected function _delete()
1722
-    {
1723
-        return $this->delete_permanently();
1724
-    }
1725
-
1726
-
1727
-    /**
1728
-     * Deletes this model object permanently from db
1729
-     * (but keep in mind related models may block the delete and return an error)
1730
-     *
1731
-     * @return bool | int
1732
-     * @throws ReflectionException
1733
-     * @throws InvalidArgumentException
1734
-     * @throws InvalidInterfaceException
1735
-     * @throws InvalidDataTypeException
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function delete_permanently()
1739
-    {
1740
-        /**
1741
-         * Called just before HARD deleting a model object
1742
-         *
1743
-         * @param EE_Base_Class $model_object about to be 'deleted'
1744
-         */
1745
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
-        $model = $this->get_model();
1747
-        $result = $model->delete_permanently_by_ID($this->ID());
1748
-        $this->refresh_cache_of_related_objects();
1749
-        /**
1750
-         * Called just after HARD deleting a model object
1751
-         *
1752
-         * @param EE_Base_Class $model_object that was just 'deleted'
1753
-         * @param boolean       $result
1754
-         */
1755
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
-        return $result;
1757
-    }
1758
-
1759
-
1760
-    /**
1761
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
-     * related model objects
1763
-     *
1764
-     * @throws ReflectionException
1765
-     * @throws InvalidArgumentException
1766
-     * @throws InvalidInterfaceException
1767
-     * @throws InvalidDataTypeException
1768
-     * @throws EE_Error
1769
-     */
1770
-    public function refresh_cache_of_related_objects()
1771
-    {
1772
-        $model = $this->get_model();
1773
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
-            if (! empty($this->_model_relations[ $relation_name ])) {
1775
-                $related_objects = $this->_model_relations[ $relation_name ];
1776
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
-                    // this relation only stores a single model object, not an array
1778
-                    // but let's make it consistent
1779
-                    $related_objects = array($related_objects);
1780
-                }
1781
-                foreach ($related_objects as $related_object) {
1782
-                    // only refresh their cache if they're in memory
1783
-                    if ($related_object instanceof EE_Base_Class) {
1784
-                        $related_object->clear_cache(
1785
-                            $model->get_this_model_name(),
1786
-                            $this
1787
-                        );
1788
-                    }
1789
-                }
1790
-            }
1791
-        }
1792
-    }
1793
-
1794
-
1795
-    /**
1796
-     *        Saves this object to the database. An array may be supplied to set some values on this
1797
-     * object just before saving.
1798
-     *
1799
-     * @access public
1800
-     * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
-     *                                  if provided during the save() method
1802
-     *                                  (often client code will change the fields' values before calling save)
1803
-     * @return false|int|string         1 on a successful update;
1804
-     *                                  the ID of the new entry on insert;
1805
-     *                                  0 on failure, or if the model object isn't allowed to persist
1806
-     *                                  (as determined by EE_Base_Class::allow_persist())
1807
-     * @throws InvalidInterfaceException
1808
-     * @throws InvalidDataTypeException
1809
-     * @throws EE_Error
1810
-     * @throws InvalidArgumentException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     * @throws ReflectionException
1814
-     */
1815
-    public function save($set_cols_n_values = array())
1816
-    {
1817
-        $model = $this->get_model();
1818
-        /**
1819
-         * Filters the fields we're about to save on the model object
1820
-         *
1821
-         * @param array         $set_cols_n_values
1822
-         * @param EE_Base_Class $model_object
1823
-         */
1824
-        $set_cols_n_values = (array) apply_filters(
1825
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
-            $set_cols_n_values,
1827
-            $this
1828
-        );
1829
-        // set attributes as provided in $set_cols_n_values
1830
-        foreach ($set_cols_n_values as $column => $value) {
1831
-            $this->set($column, $value);
1832
-        }
1833
-        // no changes ? then don't do anything
1834
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
-            return 0;
1836
-        }
1837
-        /**
1838
-         * Saving a model object.
1839
-         * Before we perform a save, this action is fired.
1840
-         *
1841
-         * @param EE_Base_Class $model_object the model object about to be saved.
1842
-         */
1843
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
-        if (! $this->allow_persist()) {
1845
-            return 0;
1846
-        }
1847
-        // now get current attribute values
1848
-        $save_cols_n_values = $this->_fields;
1849
-        // if the object already has an ID, update it. Otherwise, insert it
1850
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
-        // They have been
1852
-        $old_assumption_concerning_value_preparation = $model
1853
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1854
-        $model->assume_values_already_prepared_by_model_object(true);
1855
-        // does this model have an autoincrement PK?
1856
-        if ($model->has_primary_key_field()) {
1857
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1858
-                // ok check if it's set, if so: update; if not, insert
1859
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
-                } else {
1862
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
-                    $results = $model->insert($save_cols_n_values);
1864
-                    if ($results) {
1865
-                        // if successful, set the primary key
1866
-                        // but don't use the normal SET method, because it will check if
1867
-                        // an item with the same ID exists in the mapper & db, then
1868
-                        // will find it in the db (because we just added it) and THAT object
1869
-                        // will get added to the mapper before we can add this one!
1870
-                        // but if we just avoid using the SET method, all that headache can be avoided
1871
-                        $pk_field_name = $model->primary_key_name();
1872
-                        $this->_fields[ $pk_field_name ] = $results;
1873
-                        $this->_clear_cached_property($pk_field_name);
1874
-                        $model->add_to_entity_map($this);
1875
-                        $this->_update_cached_related_model_objs_fks();
1876
-                    }
1877
-                }
1878
-            } else {// PK is NOT auto-increment
1879
-                // so check if one like it already exists in the db
1880
-                if ($model->exists_by_ID($this->ID())) {
1881
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1882
-                        throw new EE_Error(
1883
-                            sprintf(
1884
-                                esc_html__(
1885
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1886
-                                    'event_espresso'
1887
-                                ),
1888
-                                get_class($this),
1889
-                                get_class($model) . '::instance()->add_to_entity_map()',
1890
-                                get_class($model) . '::instance()->get_one_by_ID()',
1891
-                                '<br />'
1892
-                            )
1893
-                        );
1894
-                    }
1895
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
-                } else {
1897
-                    $results = $model->insert($save_cols_n_values);
1898
-                    $this->_update_cached_related_model_objs_fks();
1899
-                }
1900
-            }
1901
-        } else {// there is NO primary key
1902
-            $already_in_db = false;
1903
-            foreach ($model->unique_indexes() as $index) {
1904
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
-                if ($model->exists(array($uniqueness_where_params))) {
1906
-                    $already_in_db = true;
1907
-                }
1908
-            }
1909
-            if ($already_in_db) {
1910
-                $combined_pk_fields_n_values = array_intersect_key(
1911
-                    $save_cols_n_values,
1912
-                    $model->get_combined_primary_key_fields()
1913
-                );
1914
-                $results = $model->update(
1915
-                    $save_cols_n_values,
1916
-                    $combined_pk_fields_n_values
1917
-                );
1918
-            } else {
1919
-                $results = $model->insert($save_cols_n_values);
1920
-            }
1921
-        }
1922
-        // restore the old assumption about values being prepared by the model object
1923
-        $model->assume_values_already_prepared_by_model_object(
1924
-            $old_assumption_concerning_value_preparation
1925
-        );
1926
-        /**
1927
-         * After saving the model object this action is called
1928
-         *
1929
-         * @param EE_Base_Class $model_object which was just saved
1930
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
-         */
1933
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
-        $this->_has_changes = false;
1935
-        return $results;
1936
-    }
1937
-
1938
-
1939
-    /**
1940
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1945
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
-     *
1948
-     * @return void
1949
-     * @throws ReflectionException
1950
-     * @throws InvalidArgumentException
1951
-     * @throws InvalidInterfaceException
1952
-     * @throws InvalidDataTypeException
1953
-     * @throws EE_Error
1954
-     */
1955
-    protected function _update_cached_related_model_objs_fks()
1956
-    {
1957
-        $model = $this->get_model();
1958
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
-                        $model->get_this_model_name()
1963
-                    );
1964
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
-                    if ($related_model_obj_in_cache->ID()) {
1966
-                        $related_model_obj_in_cache->save();
1967
-                    }
1968
-                }
1969
-            }
1970
-        }
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * Saves this model object and its NEW cached relations to the database.
1976
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1978
-     * because otherwise, there's a potential for infinite looping of saving
1979
-     * Saves the cached related model objects, and ensures the relation between them
1980
-     * and this object and properly setup
1981
-     *
1982
-     * @return int ID of new model object on save; 0 on failure+
1983
-     * @throws ReflectionException
1984
-     * @throws InvalidArgumentException
1985
-     * @throws InvalidInterfaceException
1986
-     * @throws InvalidDataTypeException
1987
-     * @throws EE_Error
1988
-     */
1989
-    public function save_new_cached_related_model_objs()
1990
-    {
1991
-        // make sure this has been saved
1992
-        if (! $this->ID()) {
1993
-            $id = $this->save();
1994
-        } else {
1995
-            $id = $this->ID();
1996
-        }
1997
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
-            if ($this->_model_relations[ $relationName ]) {
2000
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
-                /* @var $related_model_obj EE_Base_Class */
2003
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2005
-                    // but ONLY if it DOES NOT exist in the DB
2006
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2007
-                    // if( ! $related_model_obj->ID()){
2008
-                    $this->_add_relation_to($related_model_obj, $relationName);
2009
-                    $related_model_obj->save_new_cached_related_model_objs();
2010
-                    // }
2011
-                } else {
2012
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2014
-                        // but ONLY if it DOES NOT exist in the DB
2015
-                        // if( ! $related_model_obj->ID()){
2016
-                        $this->_add_relation_to($related_model_obj, $relationName);
2017
-                        $related_model_obj->save_new_cached_related_model_objs();
2018
-                        // }
2019
-                    }
2020
-                }
2021
-            }
2022
-        }
2023
-        return $id;
2024
-    }
2025
-
2026
-
2027
-    /**
2028
-     * for getting a model while instantiated.
2029
-     *
2030
-     * @return EEM_Base | EEM_CPT_Base
2031
-     * @throws ReflectionException
2032
-     * @throws InvalidArgumentException
2033
-     * @throws InvalidInterfaceException
2034
-     * @throws InvalidDataTypeException
2035
-     * @throws EE_Error
2036
-     */
2037
-    public function get_model()
2038
-    {
2039
-        if (! $this->_model) {
2040
-            $modelName = self::_get_model_classname(get_class($this));
2041
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
-        } else {
2043
-            $this->_model->set_timezone($this->_timezone);
2044
-        }
2045
-        return $this->_model;
2046
-    }
2047
-
2048
-
2049
-    /**
2050
-     * @param $props_n_values
2051
-     * @param $classname
2052
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
-     * @throws ReflectionException
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     */
2059
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
-    {
2061
-        // TODO: will not work for Term_Relationships because they have no PK!
2062
-        $primary_id_ref = self::_get_primary_key_name($classname);
2063
-        if (
2064
-            array_key_exists($primary_id_ref, $props_n_values)
2065
-            && ! empty($props_n_values[ $primary_id_ref ])
2066
-        ) {
2067
-            $id = $props_n_values[ $primary_id_ref ];
2068
-            return self::_get_model($classname)->get_from_entity_map($id);
2069
-        }
2070
-        return false;
2071
-    }
2072
-
2073
-
2074
-    /**
2075
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2078
-     * we return false.
2079
-     *
2080
-     * @param  array  $props_n_values   incoming array of properties and their values
2081
-     * @param  string $classname        the classname of the child class
2082
-     * @param null    $timezone
2083
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
-     *                                  date_format and the second value is the time format
2085
-     * @return mixed (EE_Base_Class|bool)
2086
-     * @throws InvalidArgumentException
2087
-     * @throws InvalidInterfaceException
2088
-     * @throws InvalidDataTypeException
2089
-     * @throws EE_Error
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     * @throws ReflectionException
2093
-     */
2094
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
-    {
2096
-        $existing = null;
2097
-        $model = self::_get_model($classname, $timezone);
2098
-        if ($model->has_primary_key_field()) {
2099
-            $primary_id_ref = self::_get_primary_key_name($classname);
2100
-            if (
2101
-                array_key_exists($primary_id_ref, $props_n_values)
2102
-                && ! empty($props_n_values[ $primary_id_ref ])
2103
-            ) {
2104
-                $existing = $model->get_one_by_ID(
2105
-                    $props_n_values[ $primary_id_ref ]
2106
-                );
2107
-            }
2108
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
-            // no primary key on this model, but there's still a matching item in the DB
2110
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
-                self::_get_model($classname, $timezone)
2112
-                    ->get_index_primary_key_string($props_n_values)
2113
-            );
2114
-        }
2115
-        if ($existing) {
2116
-            // set date formats if present before setting values
2117
-            if (! empty($date_formats) && is_array($date_formats)) {
2118
-                $existing->set_date_format($date_formats[0]);
2119
-                $existing->set_time_format($date_formats[1]);
2120
-            } else {
2121
-                // set default formats for date and time
2122
-                $existing->set_date_format(get_option('date_format'));
2123
-                $existing->set_time_format(get_option('time_format'));
2124
-            }
2125
-            foreach ($props_n_values as $property => $field_value) {
2126
-                $existing->set($property, $field_value);
2127
-            }
2128
-            return $existing;
2129
-        }
2130
-        return false;
2131
-    }
2132
-
2133
-
2134
-    /**
2135
-     * Gets the EEM_*_Model for this class
2136
-     *
2137
-     * @access public now, as this is more convenient
2138
-     * @param      $classname
2139
-     * @param null $timezone
2140
-     * @throws ReflectionException
2141
-     * @throws InvalidArgumentException
2142
-     * @throws InvalidInterfaceException
2143
-     * @throws InvalidDataTypeException
2144
-     * @throws EE_Error
2145
-     * @return EEM_Base
2146
-     */
2147
-    protected static function _get_model($classname, $timezone = null)
2148
-    {
2149
-        // find model for this class
2150
-        if (! $classname) {
2151
-            throw new EE_Error(
2152
-                sprintf(
2153
-                    esc_html__(
2154
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
-                        'event_espresso'
2156
-                    ),
2157
-                    $classname
2158
-                )
2159
-            );
2160
-        }
2161
-        $modelName = self::_get_model_classname($classname);
2162
-        return self::_get_model_instance_with_name($modelName, $timezone);
2163
-    }
2164
-
2165
-
2166
-    /**
2167
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
-     *
2169
-     * @param string $model_classname
2170
-     * @param null   $timezone
2171
-     * @return EEM_Base
2172
-     * @throws ReflectionException
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     */
2178
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
-    {
2180
-        $model_classname = str_replace('EEM_', '', $model_classname);
2181
-        $model = EE_Registry::instance()->load_model($model_classname);
2182
-        $model->set_timezone($timezone);
2183
-        return $model;
2184
-    }
2185
-
2186
-
2187
-    /**
2188
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2189
-     * Also works if a model class's classname is provided (eg EE_Registration).
2190
-     *
2191
-     * @param null $model_name
2192
-     * @return string like EEM_Attendee
2193
-     */
2194
-    private static function _get_model_classname($model_name = null)
2195
-    {
2196
-        if (strpos($model_name, 'EE_') === 0) {
2197
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
-        } else {
2199
-            $model_classname = 'EEM_' . $model_name;
2200
-        }
2201
-        return $model_classname;
2202
-    }
2203
-
2204
-
2205
-    /**
2206
-     * returns the name of the primary key attribute
2207
-     *
2208
-     * @param null $classname
2209
-     * @throws ReflectionException
2210
-     * @throws InvalidArgumentException
2211
-     * @throws InvalidInterfaceException
2212
-     * @throws InvalidDataTypeException
2213
-     * @throws EE_Error
2214
-     * @return string
2215
-     */
2216
-    protected static function _get_primary_key_name($classname = null)
2217
-    {
2218
-        if (! $classname) {
2219
-            throw new EE_Error(
2220
-                sprintf(
2221
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
-                    $classname
2223
-                )
2224
-            );
2225
-        }
2226
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
-    }
2228
-
2229
-
2230
-    /**
2231
-     * Gets the value of the primary key.
2232
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
-     *
2236
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
-     * @throws ReflectionException
2238
-     * @throws InvalidArgumentException
2239
-     * @throws InvalidInterfaceException
2240
-     * @throws InvalidDataTypeException
2241
-     * @throws EE_Error
2242
-     */
2243
-    public function ID()
2244
-    {
2245
-        $model = $this->get_model();
2246
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2247
-        if ($model->has_primary_key_field()) {
2248
-            return $this->_fields[ $model->primary_key_name() ];
2249
-        }
2250
-        return $model->get_index_primary_key_string($this->_fields);
2251
-    }
2252
-
2253
-
2254
-    /**
2255
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
-     *
2259
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
-     * @param string $relationName                     eg 'Events','Question',etc.
2261
-     *                                                 an attendee to a group, you also want to specify which role they
2262
-     *                                                 will have in that group. So you would use this parameter to
2263
-     *                                                 specify array('role-column-name'=>'role-id')
2264
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
-     *                                                 allow you to further constrict the relation to being added.
2266
-     *                                                 However, keep in mind that the columns (keys) given must match a
2267
-     *                                                 column on the JOIN table and currently only the HABTM models
2268
-     *                                                 accept these additional conditions.  Also remember that if an
2269
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
-     *                                                 NEW row is created in the join table.
2271
-     * @param null   $cache_id
2272
-     * @throws ReflectionException
2273
-     * @throws InvalidArgumentException
2274
-     * @throws InvalidInterfaceException
2275
-     * @throws InvalidDataTypeException
2276
-     * @throws EE_Error
2277
-     * @return EE_Base_Class the object the relation was added to
2278
-     */
2279
-    public function _add_relation_to(
2280
-        $otherObjectModelObjectOrID,
2281
-        $relationName,
2282
-        $extra_join_model_fields_n_values = array(),
2283
-        $cache_id = null
2284
-    ) {
2285
-        $model = $this->get_model();
2286
-        // if this thing exists in the DB, save the relation to the DB
2287
-        if ($this->ID()) {
2288
-            $otherObject = $model->add_relationship_to(
2289
-                $this,
2290
-                $otherObjectModelObjectOrID,
2291
-                $relationName,
2292
-                $extra_join_model_fields_n_values
2293
-            );
2294
-            // clear cache so future get_many_related and get_first_related() return new results.
2295
-            $this->clear_cache($relationName, $otherObject, true);
2296
-            if ($otherObject instanceof EE_Base_Class) {
2297
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2298
-            }
2299
-        } else {
2300
-            // this thing doesn't exist in the DB,  so just cache it
2301
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
-                throw new EE_Error(
2303
-                    sprintf(
2304
-                        esc_html__(
2305
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2306
-                            'event_espresso'
2307
-                        ),
2308
-                        $otherObjectModelObjectOrID,
2309
-                        get_class($this)
2310
-                    )
2311
-                );
2312
-            }
2313
-            $otherObject = $otherObjectModelObjectOrID;
2314
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
-        }
2316
-        if ($otherObject instanceof EE_Base_Class) {
2317
-            // fix the reciprocal relation too
2318
-            if ($otherObject->ID()) {
2319
-                // its saved so assumed relations exist in the DB, so we can just
2320
-                // clear the cache so future queries use the updated info in the DB
2321
-                $otherObject->clear_cache(
2322
-                    $model->get_this_model_name(),
2323
-                    null,
2324
-                    true
2325
-                );
2326
-            } else {
2327
-                // it's not saved, so it caches relations like this
2328
-                $otherObject->cache($model->get_this_model_name(), $this);
2329
-            }
2330
-        }
2331
-        return $otherObject;
2332
-    }
2333
-
2334
-
2335
-    /**
2336
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
-     * from the cache
2340
-     *
2341
-     * @param mixed  $otherObjectModelObjectOrID
2342
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
-     *                to the DB yet
2344
-     * @param string $relationName
2345
-     * @param array  $where_query
2346
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
-     *                deleted.
2351
-     * @return EE_Base_Class the relation was removed from
2352
-     * @throws ReflectionException
2353
-     * @throws InvalidArgumentException
2354
-     * @throws InvalidInterfaceException
2355
-     * @throws InvalidDataTypeException
2356
-     * @throws EE_Error
2357
-     */
2358
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
-    {
2360
-        if ($this->ID()) {
2361
-            // if this exists in the DB, save the relation change to the DB too
2362
-            $otherObject = $this->get_model()->remove_relationship_to(
2363
-                $this,
2364
-                $otherObjectModelObjectOrID,
2365
-                $relationName,
2366
-                $where_query
2367
-            );
2368
-            $this->clear_cache(
2369
-                $relationName,
2370
-                $otherObject
2371
-            );
2372
-        } else {
2373
-            // this doesn't exist in the DB, just remove it from the cache
2374
-            $otherObject = $this->clear_cache(
2375
-                $relationName,
2376
-                $otherObjectModelObjectOrID
2377
-            );
2378
-        }
2379
-        if ($otherObject instanceof EE_Base_Class) {
2380
-            $otherObject->clear_cache(
2381
-                $this->get_model()->get_this_model_name(),
2382
-                $this
2383
-            );
2384
-        }
2385
-        return $otherObject;
2386
-    }
2387
-
2388
-
2389
-    /**
2390
-     * Removes ALL the related things for the $relationName.
2391
-     *
2392
-     * @param string $relationName
2393
-     * @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
2394
-     * @return EE_Base_Class
2395
-     * @throws ReflectionException
2396
-     * @throws InvalidArgumentException
2397
-     * @throws InvalidInterfaceException
2398
-     * @throws InvalidDataTypeException
2399
-     * @throws EE_Error
2400
-     */
2401
-    public function _remove_relations($relationName, $where_query_params = array())
2402
-    {
2403
-        if ($this->ID()) {
2404
-            // if this exists in the DB, save the relation change to the DB too
2405
-            $otherObjects = $this->get_model()->remove_relations(
2406
-                $this,
2407
-                $relationName,
2408
-                $where_query_params
2409
-            );
2410
-            $this->clear_cache(
2411
-                $relationName,
2412
-                null,
2413
-                true
2414
-            );
2415
-        } else {
2416
-            // this doesn't exist in the DB, just remove it from the cache
2417
-            $otherObjects = $this->clear_cache(
2418
-                $relationName,
2419
-                null,
2420
-                true
2421
-            );
2422
-        }
2423
-        if (is_array($otherObjects)) {
2424
-            foreach ($otherObjects as $otherObject) {
2425
-                $otherObject->clear_cache(
2426
-                    $this->get_model()->get_this_model_name(),
2427
-                    $this
2428
-                );
2429
-            }
2430
-        }
2431
-        return $otherObjects;
2432
-    }
2433
-
2434
-
2435
-    /**
2436
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2437
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
-     * because we want to get even deleted items etc.
2440
-     *
2441
-     * @param string $relationName key in the model's _model_relations array
2442
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
-     *                             results if you want IDs
2446
-     * @throws ReflectionException
2447
-     * @throws InvalidArgumentException
2448
-     * @throws InvalidInterfaceException
2449
-     * @throws InvalidDataTypeException
2450
-     * @throws EE_Error
2451
-     */
2452
-    public function get_many_related($relationName, $query_params = array())
2453
-    {
2454
-        if ($this->ID()) {
2455
-            // this exists in the DB, so get the related things from either the cache or the DB
2456
-            // if there are query parameters, forget about caching the related model objects.
2457
-            if ($query_params) {
2458
-                $related_model_objects = $this->get_model()->get_all_related(
2459
-                    $this,
2460
-                    $relationName,
2461
-                    $query_params
2462
-                );
2463
-            } else {
2464
-                // did we already cache the result of this query?
2465
-                $cached_results = $this->get_all_from_cache($relationName);
2466
-                if (! $cached_results) {
2467
-                    $related_model_objects = $this->get_model()->get_all_related(
2468
-                        $this,
2469
-                        $relationName,
2470
-                        $query_params
2471
-                    );
2472
-                    // if no query parameters were passed, then we got all the related model objects
2473
-                    // for that relation. We can cache them then.
2474
-                    foreach ($related_model_objects as $related_model_object) {
2475
-                        $this->cache($relationName, $related_model_object);
2476
-                    }
2477
-                } else {
2478
-                    $related_model_objects = $cached_results;
2479
-                }
2480
-            }
2481
-        } else {
2482
-            // this doesn't exist in the DB, so just get the related things from the cache
2483
-            $related_model_objects = $this->get_all_from_cache($relationName);
2484
-        }
2485
-        return $related_model_objects;
2486
-    }
2487
-
2488
-
2489
-    /**
2490
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
-     * unless otherwise specified in the $query_params
2492
-     *
2493
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2496
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
-     *                               that by the setting $distinct to TRUE;
2498
-     * @return int
2499
-     * @throws ReflectionException
2500
-     * @throws InvalidArgumentException
2501
-     * @throws InvalidInterfaceException
2502
-     * @throws InvalidDataTypeException
2503
-     * @throws EE_Error
2504
-     */
2505
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
-    {
2507
-        return $this->get_model()->count_related(
2508
-            $this,
2509
-            $relation_name,
2510
-            $query_params,
2511
-            $field_to_count,
2512
-            $distinct
2513
-        );
2514
-    }
2515
-
2516
-
2517
-    /**
2518
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
-     *
2521
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2522
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
-     * @param string $field_to_sum  name of field to count by.
2524
-     *                              By default, uses primary key
2525
-     *                              (which doesn't make much sense, so you should probably change it)
2526
-     * @return int
2527
-     * @throws ReflectionException
2528
-     * @throws InvalidArgumentException
2529
-     * @throws InvalidInterfaceException
2530
-     * @throws InvalidDataTypeException
2531
-     * @throws EE_Error
2532
-     */
2533
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
-    {
2535
-        return $this->get_model()->sum_related(
2536
-            $this,
2537
-            $relation_name,
2538
-            $query_params,
2539
-            $field_to_sum
2540
-        );
2541
-    }
2542
-
2543
-
2544
-    /**
2545
-     * Gets the first (ie, one) related model object of the specified type.
2546
-     *
2547
-     * @param string $relationName key in the model's _model_relations array
2548
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
-     * @return EE_Base_Class (not an array, a single object)
2550
-     * @throws ReflectionException
2551
-     * @throws InvalidArgumentException
2552
-     * @throws InvalidInterfaceException
2553
-     * @throws InvalidDataTypeException
2554
-     * @throws EE_Error
2555
-     */
2556
-    public function get_first_related($relationName, $query_params = array())
2557
-    {
2558
-        $model = $this->get_model();
2559
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
-            // if they've provided some query parameters, don't bother trying to cache the result
2561
-            // also make sure we're not caching the result of get_first_related
2562
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2563
-            if (
2564
-                $query_params
2565
-                || ! $model->related_settings_for($relationName)
2566
-                     instanceof
2567
-                     EE_Belongs_To_Relation
2568
-            ) {
2569
-                $related_model_object = $model->get_first_related(
2570
-                    $this,
2571
-                    $relationName,
2572
-                    $query_params
2573
-                );
2574
-            } else {
2575
-                // first, check if we've already cached the result of this query
2576
-                $cached_result = $this->get_one_from_cache($relationName);
2577
-                if (! $cached_result) {
2578
-                    $related_model_object = $model->get_first_related(
2579
-                        $this,
2580
-                        $relationName,
2581
-                        $query_params
2582
-                    );
2583
-                    $this->cache($relationName, $related_model_object);
2584
-                } else {
2585
-                    $related_model_object = $cached_result;
2586
-                }
2587
-            }
2588
-        } else {
2589
-            $related_model_object = null;
2590
-            // this doesn't exist in the Db,
2591
-            // but maybe the relation is of type belongs to, and so the related thing might
2592
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
-                $related_model_object = $model->get_first_related(
2594
-                    $this,
2595
-                    $relationName,
2596
-                    $query_params
2597
-                );
2598
-            }
2599
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
-            // just get what's cached on this object
2601
-            if (! $related_model_object) {
2602
-                $related_model_object = $this->get_one_from_cache($relationName);
2603
-            }
2604
-        }
2605
-        return $related_model_object;
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Does a delete on all related objects of type $relationName and removes
2611
-     * the current model object's relation to them. If they can't be deleted (because
2612
-     * of blocking related model objects) does nothing. If the related model objects are
2613
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
-     * If this model object doesn't exist yet in the DB, just removes its related things
2615
-     *
2616
-     * @param string $relationName
2617
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
-     * @return int how many deleted
2619
-     * @throws ReflectionException
2620
-     * @throws InvalidArgumentException
2621
-     * @throws InvalidInterfaceException
2622
-     * @throws InvalidDataTypeException
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($relationName, $query_params = array())
2626
-    {
2627
-        if ($this->ID()) {
2628
-            $count = $this->get_model()->delete_related(
2629
-                $this,
2630
-                $relationName,
2631
-                $query_params
2632
-            );
2633
-        } else {
2634
-            $count = count($this->get_all_from_cache($relationName));
2635
-            $this->clear_cache($relationName, null, true);
2636
-        }
2637
-        return $count;
2638
-    }
2639
-
2640
-
2641
-    /**
2642
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
-     * the current model object's relation to them. If they can't be deleted (because
2644
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
-     * If the related thing isn't a soft-deletable model object, this function is identical
2646
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
-     *
2648
-     * @param string $relationName
2649
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
-     * @return int how many deleted (including those soft deleted)
2651
-     * @throws ReflectionException
2652
-     * @throws InvalidArgumentException
2653
-     * @throws InvalidInterfaceException
2654
-     * @throws InvalidDataTypeException
2655
-     * @throws EE_Error
2656
-     */
2657
-    public function delete_related_permanently($relationName, $query_params = array())
2658
-    {
2659
-        if ($this->ID()) {
2660
-            $count = $this->get_model()->delete_related_permanently(
2661
-                $this,
2662
-                $relationName,
2663
-                $query_params
2664
-            );
2665
-        } else {
2666
-            $count = count($this->get_all_from_cache($relationName));
2667
-        }
2668
-        $this->clear_cache($relationName, null, true);
2669
-        return $count;
2670
-    }
2671
-
2672
-
2673
-    /**
2674
-     * is_set
2675
-     * Just a simple utility function children can use for checking if property exists
2676
-     *
2677
-     * @access  public
2678
-     * @param  string $field_name property to check
2679
-     * @return bool                              TRUE if existing,FALSE if not.
2680
-     */
2681
-    public function is_set($field_name)
2682
-    {
2683
-        return isset($this->_fields[ $field_name ]);
2684
-    }
2685
-
2686
-
2687
-    /**
2688
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
-     * EE_Error exception if they don't
2690
-     *
2691
-     * @param  mixed (string|array) $properties properties to check
2692
-     * @throws EE_Error
2693
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2694
-     */
2695
-    protected function _property_exists($properties)
2696
-    {
2697
-        foreach ((array) $properties as $property_name) {
2698
-            // first make sure this property exists
2699
-            if (! $this->_fields[ $property_name ]) {
2700
-                throw new EE_Error(
2701
-                    sprintf(
2702
-                        esc_html__(
2703
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
-                            'event_espresso'
2705
-                        ),
2706
-                        $property_name
2707
-                    )
2708
-                );
2709
-            }
2710
-        }
2711
-        return true;
2712
-    }
2713
-
2714
-
2715
-    /**
2716
-     * This simply returns an array of model fields for this object
2717
-     *
2718
-     * @return array
2719
-     * @throws ReflectionException
2720
-     * @throws InvalidArgumentException
2721
-     * @throws InvalidInterfaceException
2722
-     * @throws InvalidDataTypeException
2723
-     * @throws EE_Error
2724
-     */
2725
-    public function model_field_array()
2726
-    {
2727
-        $fields = $this->get_model()->field_settings(false);
2728
-        $properties = array();
2729
-        // remove prepended underscore
2730
-        foreach ($fields as $field_name => $settings) {
2731
-            $properties[ $field_name ] = $this->get($field_name);
2732
-        }
2733
-        return $properties;
2734
-    }
2735
-
2736
-
2737
-    /**
2738
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
-     * Instead of requiring a plugin to extend the EE_Base_Class
2742
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2743
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
-     * and accepts 2 arguments: the object on which the function was called,
2746
-     * and an array of the original arguments passed to the function.
2747
-     * Whatever their callback function returns will be returned by this function.
2748
-     * Example: in functions.php (or in a plugin):
2749
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2750
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2751
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2752
-     *          return $previousReturnValue.$returnString;
2753
-     *      }
2754
-     * require('EE_Answer.class.php');
2755
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2756
-     *      ->my_callback('monkeys',100);
2757
-     * // will output "you called my_callback! and passed args:monkeys,100"
2758
-     *
2759
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2760
-     * @param array  $args       array of original arguments passed to the function
2761
-     * @throws EE_Error
2762
-     * @return mixed whatever the plugin which calls add_filter decides
2763
-     */
2764
-    public function __call($methodName, $args)
2765
-    {
2766
-        $className = get_class($this);
2767
-        $tagName = "FHEE__{$className}__{$methodName}";
2768
-        if (! has_filter($tagName)) {
2769
-            throw new EE_Error(
2770
-                sprintf(
2771
-                    esc_html__(
2772
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2773
-                        'event_espresso'
2774
-                    ),
2775
-                    $methodName,
2776
-                    $className,
2777
-                    $tagName
2778
-                )
2779
-            );
2780
-        }
2781
-        return apply_filters($tagName, null, $this, $args);
2782
-    }
2783
-
2784
-
2785
-    /**
2786
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2787
-     * A $previous_value can be specified in case there are many meta rows with the same key
2788
-     *
2789
-     * @param string $meta_key
2790
-     * @param mixed  $meta_value
2791
-     * @param mixed  $previous_value
2792
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2793
-     *                  NOTE: if the values haven't changed, returns 0
2794
-     * @throws InvalidArgumentException
2795
-     * @throws InvalidInterfaceException
2796
-     * @throws InvalidDataTypeException
2797
-     * @throws EE_Error
2798
-     * @throws ReflectionException
2799
-     */
2800
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2801
-    {
2802
-        $query_params = array(
2803
-            array(
2804
-                'EXM_key'  => $meta_key,
2805
-                'OBJ_ID'   => $this->ID(),
2806
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2807
-            ),
2808
-        );
2809
-        if ($previous_value !== null) {
2810
-            $query_params[0]['EXM_value'] = $meta_value;
2811
-        }
2812
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2813
-        if (! $existing_rows_like_that) {
2814
-            return $this->add_extra_meta($meta_key, $meta_value);
2815
-        }
2816
-        foreach ($existing_rows_like_that as $existing_row) {
2817
-            $existing_row->save(array('EXM_value' => $meta_value));
2818
-        }
2819
-        return count($existing_rows_like_that);
2820
-    }
2821
-
2822
-
2823
-    /**
2824
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2825
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2826
-     * extra meta row was entered, false if not
2827
-     *
2828
-     * @param string  $meta_key
2829
-     * @param mixed   $meta_value
2830
-     * @param boolean $unique
2831
-     * @return boolean
2832
-     * @throws InvalidArgumentException
2833
-     * @throws InvalidInterfaceException
2834
-     * @throws InvalidDataTypeException
2835
-     * @throws EE_Error
2836
-     * @throws ReflectionException
2837
-     * @throws ReflectionException
2838
-     */
2839
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2840
-    {
2841
-        if ($unique) {
2842
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2843
-                array(
2844
-                    array(
2845
-                        'EXM_key'  => $meta_key,
2846
-                        'OBJ_ID'   => $this->ID(),
2847
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2848
-                    ),
2849
-                )
2850
-            );
2851
-            if ($existing_extra_meta) {
2852
-                return false;
2853
-            }
2854
-        }
2855
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2856
-            array(
2857
-                'EXM_key'   => $meta_key,
2858
-                'EXM_value' => $meta_value,
2859
-                'OBJ_ID'    => $this->ID(),
2860
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2861
-            )
2862
-        );
2863
-        $new_extra_meta->save();
2864
-        return true;
2865
-    }
2866
-
2867
-
2868
-    /**
2869
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2870
-     * is specified, only deletes extra meta records with that value.
2871
-     *
2872
-     * @param string $meta_key
2873
-     * @param mixed  $meta_value
2874
-     * @return int number of extra meta rows deleted
2875
-     * @throws InvalidArgumentException
2876
-     * @throws InvalidInterfaceException
2877
-     * @throws InvalidDataTypeException
2878
-     * @throws EE_Error
2879
-     * @throws ReflectionException
2880
-     */
2881
-    public function delete_extra_meta($meta_key, $meta_value = null)
2882
-    {
2883
-        $query_params = array(
2884
-            array(
2885
-                'EXM_key'  => $meta_key,
2886
-                'OBJ_ID'   => $this->ID(),
2887
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2888
-            ),
2889
-        );
2890
-        if ($meta_value !== null) {
2891
-            $query_params[0]['EXM_value'] = $meta_value;
2892
-        }
2893
-        return EEM_Extra_Meta::instance()->delete($query_params);
2894
-    }
2895
-
2896
-
2897
-    /**
2898
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2899
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2900
-     * You can specify $default is case you haven't found the extra meta
2901
-     *
2902
-     * @param string  $meta_key
2903
-     * @param boolean $single
2904
-     * @param mixed   $default if we don't find anything, what should we return?
2905
-     * @return mixed single value if $single; array if ! $single
2906
-     * @throws ReflectionException
2907
-     * @throws InvalidArgumentException
2908
-     * @throws InvalidInterfaceException
2909
-     * @throws InvalidDataTypeException
2910
-     * @throws EE_Error
2911
-     */
2912
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2913
-    {
2914
-        if ($single) {
2915
-            $result = $this->get_first_related(
2916
-                'Extra_Meta',
2917
-                array(array('EXM_key' => $meta_key))
2918
-            );
2919
-            if ($result instanceof EE_Extra_Meta) {
2920
-                return $result->value();
2921
-            }
2922
-        } else {
2923
-            $results = $this->get_many_related(
2924
-                'Extra_Meta',
2925
-                array(array('EXM_key' => $meta_key))
2926
-            );
2927
-            if ($results) {
2928
-                $values = array();
2929
-                foreach ($results as $result) {
2930
-                    if ($result instanceof EE_Extra_Meta) {
2931
-                        $values[ $result->ID() ] = $result->value();
2932
-                    }
2933
-                }
2934
-                return $values;
2935
-            }
2936
-        }
2937
-        // if nothing discovered yet return default.
2938
-        return apply_filters(
2939
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2940
-            $default,
2941
-            $meta_key,
2942
-            $single,
2943
-            $this
2944
-        );
2945
-    }
2946
-
2947
-
2948
-    /**
2949
-     * Returns a simple array of all the extra meta associated with this model object.
2950
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2951
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2952
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2953
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2954
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2955
-     * finally the extra meta's value as each sub-value. (eg
2956
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2957
-     *
2958
-     * @param boolean $one_of_each_key
2959
-     * @return array
2960
-     * @throws ReflectionException
2961
-     * @throws InvalidArgumentException
2962
-     * @throws InvalidInterfaceException
2963
-     * @throws InvalidDataTypeException
2964
-     * @throws EE_Error
2965
-     */
2966
-    public function all_extra_meta_array($one_of_each_key = true)
2967
-    {
2968
-        $return_array = array();
2969
-        if ($one_of_each_key) {
2970
-            $extra_meta_objs = $this->get_many_related(
2971
-                'Extra_Meta',
2972
-                array('group_by' => 'EXM_key')
2973
-            );
2974
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2975
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2976
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2977
-                }
2978
-            }
2979
-        } else {
2980
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2981
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2982
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2983
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2984
-                        $return_array[ $extra_meta_obj->key() ] = array();
2985
-                    }
2986
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2987
-                }
2988
-            }
2989
-        }
2990
-        return $return_array;
2991
-    }
2992
-
2993
-
2994
-    /**
2995
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2996
-     *
2997
-     * @return string
2998
-     * @throws ReflectionException
2999
-     * @throws InvalidArgumentException
3000
-     * @throws InvalidInterfaceException
3001
-     * @throws InvalidDataTypeException
3002
-     * @throws EE_Error
3003
-     */
3004
-    public function name()
3005
-    {
3006
-        // find a field that's not a text field
3007
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3008
-        if ($field_we_can_use) {
3009
-            return $this->get($field_we_can_use->get_name());
3010
-        }
3011
-        $first_few_properties = $this->model_field_array();
3012
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3013
-        $name_parts = array();
3014
-        foreach ($first_few_properties as $name => $value) {
3015
-            $name_parts[] = "$name:$value";
3016
-        }
3017
-        return implode(',', $name_parts);
3018
-    }
3019
-
3020
-
3021
-    /**
3022
-     * in_entity_map
3023
-     * Checks if this model object has been proven to already be in the entity map
3024
-     *
3025
-     * @return boolean
3026
-     * @throws ReflectionException
3027
-     * @throws InvalidArgumentException
3028
-     * @throws InvalidInterfaceException
3029
-     * @throws InvalidDataTypeException
3030
-     * @throws EE_Error
3031
-     */
3032
-    public function in_entity_map()
3033
-    {
3034
-        // well, if we looked, did we find it in the entity map?
3035
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3036
-    }
3037
-
3038
-
3039
-    /**
3040
-     * refresh_from_db
3041
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3042
-     *
3043
-     * @throws ReflectionException
3044
-     * @throws InvalidArgumentException
3045
-     * @throws InvalidInterfaceException
3046
-     * @throws InvalidDataTypeException
3047
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3048
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3049
-     */
3050
-    public function refresh_from_db()
3051
-    {
3052
-        if ($this->ID() && $this->in_entity_map()) {
3053
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3054
-        } else {
3055
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3056
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3057
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3058
-            // absolutely nothing in it for this ID
3059
-            if (WP_DEBUG) {
3060
-                throw new EE_Error(
3061
-                    sprintf(
3062
-                        esc_html__(
3063
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3064
-                            'event_espresso'
3065
-                        ),
3066
-                        $this->ID(),
3067
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3068
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3069
-                    )
3070
-                );
3071
-            }
3072
-        }
3073
-    }
3074
-
3075
-
3076
-    /**
3077
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3078
-     *
3079
-     * @since 4.9.80.p
3080
-     * @param EE_Model_Field_Base[] $fields
3081
-     * @param string $new_value_sql
3082
-     *      example: 'column_name=123',
3083
-     *      or 'column_name=column_name+1',
3084
-     *      or 'column_name= CASE
3085
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3086
-     *          THEN `column_name` + 5
3087
-     *          ELSE `column_name`
3088
-     *      END'
3089
-     *      Also updates $field on this model object with the latest value from the database.
3090
-     * @return bool
3091
-     * @throws EE_Error
3092
-     * @throws InvalidArgumentException
3093
-     * @throws InvalidDataTypeException
3094
-     * @throws InvalidInterfaceException
3095
-     * @throws ReflectionException
3096
-     */
3097
-    protected function updateFieldsInDB($fields, $new_value_sql)
3098
-    {
3099
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3100
-        // if it wasn't even there to start off.
3101
-        if (! $this->ID()) {
3102
-            $this->save();
3103
-        }
3104
-        global $wpdb;
3105
-        if (empty($fields)) {
3106
-            throw new InvalidArgumentException(
3107
-                esc_html__(
3108
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3109
-                    'event_espresso'
3110
-                )
3111
-            );
3112
-        }
3113
-        $first_field = reset($fields);
3114
-        $table_alias = $first_field->get_table_alias();
3115
-        foreach ($fields as $field) {
3116
-            if ($table_alias !== $field->get_table_alias()) {
3117
-                throw new InvalidArgumentException(
3118
-                    sprintf(
3119
-                        esc_html__(
3120
-                            // @codingStandardsIgnoreStart
3121
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3122
-                            // @codingStandardsIgnoreEnd
3123
-                            'event_espresso'
3124
-                        ),
3125
-                        $table_alias,
3126
-                        $field->get_table_alias()
3127
-                    )
3128
-                );
3129
-            }
3130
-        }
3131
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3132
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3133
-        $table_pk_value = $this->ID();
3134
-        $table_name = $table_obj->get_table_name();
3135
-        if ($table_obj instanceof EE_Secondary_Table) {
3136
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3137
-        } else {
3138
-            $table_pk_field_name = $table_obj->get_pk_column();
3139
-        }
3140
-
3141
-        $query =
3142
-            "UPDATE `{$table_name}`
338
+				$this->_props_n_values_provided_in_constructor
339
+				&& $field_value
340
+				&& $field_name === $model->primary_key_name()
341
+			) {
342
+				// if so, we want all this object's fields to be filled either with
343
+				// what we've explicitly set on this model
344
+				// or what we have in the db
345
+				// echo "setting primary key!";
346
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
347
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
348
+				foreach ($fields_on_model as $field_obj) {
349
+					if (
350
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
351
+						&& $field_obj->get_name() !== $field_name
352
+					) {
353
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
354
+					}
355
+				}
356
+				// oh this model object has an ID? well make sure its in the entity mapper
357
+				$model->add_to_entity_map($this);
358
+			}
359
+			// let's unset any cache for this field_name from the $_cached_properties property.
360
+			$this->_clear_cached_property($field_name);
361
+		} else {
362
+			throw new EE_Error(
363
+				sprintf(
364
+					esc_html__(
365
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
366
+						'event_espresso'
367
+					),
368
+					$field_name
369
+				)
370
+			);
371
+		}
372
+	}
373
+
374
+
375
+	/**
376
+	 * Set custom select values for model.
377
+	 *
378
+	 * @param array $custom_select_values
379
+	 */
380
+	public function setCustomSelectsValues(array $custom_select_values)
381
+	{
382
+		$this->custom_selection_results = $custom_select_values;
383
+	}
384
+
385
+
386
+	/**
387
+	 * Returns the custom select value for the provided alias if its set.
388
+	 * If not set, returns null.
389
+	 *
390
+	 * @param string $alias
391
+	 * @return string|int|float|null
392
+	 */
393
+	public function getCustomSelect($alias)
394
+	{
395
+		return isset($this->custom_selection_results[ $alias ])
396
+			? $this->custom_selection_results[ $alias ]
397
+			: null;
398
+	}
399
+
400
+
401
+	/**
402
+	 * This sets the field value on the db column if it exists for the given $column_name or
403
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
+	 *
405
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
406
+	 * @param string $field_name  Must be the exact column name.
407
+	 * @param mixed  $field_value The value to set.
408
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidInterfaceException
411
+	 * @throws InvalidDataTypeException
412
+	 * @throws EE_Error
413
+	 * @throws ReflectionException
414
+	 */
415
+	public function set_field_or_extra_meta($field_name, $field_value)
416
+	{
417
+		if ($this->get_model()->has_field($field_name)) {
418
+			$this->set($field_name, $field_value);
419
+			return true;
420
+		}
421
+		// ensure this object is saved first so that extra meta can be properly related.
422
+		$this->save();
423
+		return $this->update_extra_meta($field_name, $field_value);
424
+	}
425
+
426
+
427
+	/**
428
+	 * This retrieves the value of the db column set on this class or if that's not present
429
+	 * it will attempt to retrieve from extra_meta if found.
430
+	 * Example Usage:
431
+	 * Via EE_Message child class:
432
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
435
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
+	 * value for those extra fields dynamically via the EE_message object.
437
+	 *
438
+	 * @param  string $field_name expecting the fully qualified field name.
439
+	 * @return mixed|null  value for the field if found.  null if not found.
440
+	 * @throws ReflectionException
441
+	 * @throws InvalidArgumentException
442
+	 * @throws InvalidInterfaceException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws EE_Error
445
+	 */
446
+	public function get_field_or_extra_meta($field_name)
447
+	{
448
+		if ($this->get_model()->has_field($field_name)) {
449
+			$column_value = $this->get($field_name);
450
+		} else {
451
+			// This isn't a column in the main table, let's see if it is in the extra meta.
452
+			$column_value = $this->get_extra_meta($field_name, true, null);
453
+		}
454
+		return $column_value;
455
+	}
456
+
457
+
458
+	/**
459
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
+	 *
464
+	 * @access public
465
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
+	 * @return void
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidInterfaceException
469
+	 * @throws InvalidDataTypeException
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function set_timezone($timezone = '')
474
+	{
475
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
476
+		// make sure we clear all cached properties because they won't be relevant now
477
+		$this->_clear_cached_properties();
478
+		// make sure we update field settings and the date for all EE_Datetime_Fields
479
+		$model_fields = $this->get_model()->field_settings(false);
480
+		foreach ($model_fields as $field_name => $field_obj) {
481
+			if ($field_obj instanceof EE_Datetime_Field) {
482
+				$field_obj->set_timezone($this->_timezone);
483
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
484
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
+				}
486
+			}
487
+		}
488
+	}
489
+
490
+
491
+	/**
492
+	 * This just returns whatever is set for the current timezone.
493
+	 *
494
+	 * @access public
495
+	 * @return string timezone string
496
+	 */
497
+	public function get_timezone()
498
+	{
499
+		return $this->_timezone;
500
+	}
501
+
502
+
503
+	/**
504
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
505
+	 * internally instead of wp set date format options
506
+	 *
507
+	 * @since 4.6
508
+	 * @param string $format should be a format recognizable by PHP date() functions.
509
+	 */
510
+	public function set_date_format($format)
511
+	{
512
+		$this->_dt_frmt = $format;
513
+		// clear cached_properties because they won't be relevant now.
514
+		$this->_clear_cached_properties();
515
+	}
516
+
517
+
518
+	/**
519
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
520
+	 * class internally instead of wp set time format options.
521
+	 *
522
+	 * @since 4.6
523
+	 * @param string $format should be a format recognizable by PHP date() functions.
524
+	 */
525
+	public function set_time_format($format)
526
+	{
527
+		$this->_tm_frmt = $format;
528
+		// clear cached_properties because they won't be relevant now.
529
+		$this->_clear_cached_properties();
530
+	}
531
+
532
+
533
+	/**
534
+	 * This returns the current internal set format for the date and time formats.
535
+	 *
536
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
537
+	 *                             where the first value is the date format and the second value is the time format.
538
+	 * @return mixed string|array
539
+	 */
540
+	public function get_format($full = true)
541
+	{
542
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
+	}
544
+
545
+
546
+	/**
547
+	 * cache
548
+	 * stores the passed model object on the current model object.
549
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
550
+	 *
551
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
552
+	 *                                       'Registration' associated with this model object
553
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
554
+	 *                                       that could be a payment or a registration)
555
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
556
+	 *                                       items which will be stored in an array on this object
557
+	 * @throws ReflectionException
558
+	 * @throws InvalidArgumentException
559
+	 * @throws InvalidInterfaceException
560
+	 * @throws InvalidDataTypeException
561
+	 * @throws EE_Error
562
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
563
+	 *                                       related thing, no array)
564
+	 */
565
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
566
+	{
567
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
568
+		if (! $object_to_cache instanceof EE_Base_Class) {
569
+			return false;
570
+		}
571
+		// also get "how" the object is related, or throw an error
572
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
+			throw new EE_Error(
574
+				sprintf(
575
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
576
+					$relationName,
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		// how many things are related ?
582
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
583
+			// if it's a "belongs to" relationship, then there's only one related model object
584
+			// eg, if this is a registration, there's only 1 attendee for it
585
+			// so for these model objects just set it to be cached
586
+			$this->_model_relations[ $relationName ] = $object_to_cache;
587
+			$return = true;
588
+		} else {
589
+			// otherwise, this is the "many" side of a one to many relationship,
590
+			// so we'll add the object to the array of related objects for that type.
591
+			// eg: if this is an event, there are many registrations for that event,
592
+			// so we cache the registrations in an array
593
+			if (! is_array($this->_model_relations[ $relationName ])) {
594
+				// if for some reason, the cached item is a model object,
595
+				// then stick that in the array, otherwise start with an empty array
596
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
+														   instanceof
598
+														   EE_Base_Class
599
+					? array($this->_model_relations[ $relationName ]) : array();
600
+			}
601
+			// first check for a cache_id which is normally empty
602
+			if (! empty($cache_id)) {
603
+				// if the cache_id exists, then it means we are purposely trying to cache this
604
+				// with a known key that can then be used to retrieve the object later on
605
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
+				$return = $cache_id;
607
+			} elseif ($object_to_cache->ID()) {
608
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
609
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
+				$return = $object_to_cache->ID();
611
+			} else {
612
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
613
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
614
+				// move the internal pointer to the end of the array
615
+				end($this->_model_relations[ $relationName ]);
616
+				// and grab the key so that we can return it
617
+				$return = key($this->_model_relations[ $relationName ]);
618
+			}
619
+		}
620
+		return $return;
621
+	}
622
+
623
+
624
+	/**
625
+	 * For adding an item to the cached_properties property.
626
+	 *
627
+	 * @access protected
628
+	 * @param string      $fieldname the property item the corresponding value is for.
629
+	 * @param mixed       $value     The value we are caching.
630
+	 * @param string|null $cache_type
631
+	 * @return void
632
+	 * @throws ReflectionException
633
+	 * @throws InvalidArgumentException
634
+	 * @throws InvalidInterfaceException
635
+	 * @throws InvalidDataTypeException
636
+	 * @throws EE_Error
637
+	 */
638
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
639
+	{
640
+		// first make sure this property exists
641
+		$this->get_model()->field_settings_for($fieldname);
642
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
643
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
+	}
645
+
646
+
647
+	/**
648
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
649
+	 * This also SETS the cache if we return the actual property!
650
+	 *
651
+	 * @param string $fieldname        the name of the property we're trying to retrieve
652
+	 * @param bool   $pretty
653
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
654
+	 *                                 (in cases where the same property may be used for different outputs
655
+	 *                                 - i.e. datetime, money etc.)
656
+	 *                                 It can also accept certain pre-defined "schema" strings
657
+	 *                                 to define how to output the property.
658
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
659
+	 * @return mixed                   whatever the value for the property is we're retrieving
660
+	 * @throws ReflectionException
661
+	 * @throws InvalidArgumentException
662
+	 * @throws InvalidInterfaceException
663
+	 * @throws InvalidDataTypeException
664
+	 * @throws EE_Error
665
+	 */
666
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
667
+	{
668
+		// verify the field exists
669
+		$model = $this->get_model();
670
+		$model->field_settings_for($fieldname);
671
+		$cache_type = $pretty ? 'pretty' : 'standard';
672
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
673
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
674
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
+		}
676
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
677
+		$this->_set_cached_property($fieldname, $value, $cache_type);
678
+		return $value;
679
+	}
680
+
681
+
682
+	/**
683
+	 * If the cache didn't fetch the needed item, this fetches it.
684
+	 *
685
+	 * @param string $fieldname
686
+	 * @param bool   $pretty
687
+	 * @param string $extra_cache_ref
688
+	 * @return mixed
689
+	 * @throws InvalidArgumentException
690
+	 * @throws InvalidInterfaceException
691
+	 * @throws InvalidDataTypeException
692
+	 * @throws EE_Error
693
+	 * @throws ReflectionException
694
+	 */
695
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
696
+	{
697
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
698
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
699
+		if ($field_obj instanceof EE_Datetime_Field) {
700
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
701
+		}
702
+		if (! isset($this->_fields[ $fieldname ])) {
703
+			$this->_fields[ $fieldname ] = null;
704
+		}
705
+		$value = $pretty
706
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
707
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
+		return $value;
709
+	}
710
+
711
+
712
+	/**
713
+	 * set timezone, formats, and output for EE_Datetime_Field objects
714
+	 *
715
+	 * @param \EE_Datetime_Field $datetime_field
716
+	 * @param bool               $pretty
717
+	 * @param null               $date_or_time
718
+	 * @return void
719
+	 * @throws InvalidArgumentException
720
+	 * @throws InvalidInterfaceException
721
+	 * @throws InvalidDataTypeException
722
+	 * @throws EE_Error
723
+	 */
724
+	protected function _prepare_datetime_field(
725
+		EE_Datetime_Field $datetime_field,
726
+		$pretty = false,
727
+		$date_or_time = null
728
+	) {
729
+		$datetime_field->set_timezone($this->_timezone);
730
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
+		// set the output returned
733
+		switch ($date_or_time) {
734
+			case 'D':
735
+				$datetime_field->set_date_time_output('date');
736
+				break;
737
+			case 'T':
738
+				$datetime_field->set_date_time_output('time');
739
+				break;
740
+			default:
741
+				$datetime_field->set_date_time_output();
742
+		}
743
+	}
744
+
745
+
746
+	/**
747
+	 * This just takes care of clearing out the cached_properties
748
+	 *
749
+	 * @return void
750
+	 */
751
+	protected function _clear_cached_properties()
752
+	{
753
+		$this->_cached_properties = array();
754
+	}
755
+
756
+
757
+	/**
758
+	 * This just clears out ONE property if it exists in the cache
759
+	 *
760
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
761
+	 * @return void
762
+	 */
763
+	protected function _clear_cached_property($property_name)
764
+	{
765
+		if (isset($this->_cached_properties[ $property_name ])) {
766
+			unset($this->_cached_properties[ $property_name ]);
767
+		}
768
+	}
769
+
770
+
771
+	/**
772
+	 * Ensures that this related thing is a model object.
773
+	 *
774
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
776
+	 * @return EE_Base_Class
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
+	{
785
+		$other_model_instance = self::_get_model_instance_with_name(
786
+			self::_get_model_classname($model_name),
787
+			$this->_timezone
788
+		);
789
+		return $other_model_instance->ensure_is_obj($object_or_id);
790
+	}
791
+
792
+
793
+	/**
794
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
795
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
798
+	 *
799
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
800
+	 *                                                     Eg 'Registration'
801
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
804
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
+	 *                                                     this is HasMany or HABTM.
806
+	 * @throws ReflectionException
807
+	 * @throws InvalidArgumentException
808
+	 * @throws InvalidInterfaceException
809
+	 * @throws InvalidDataTypeException
810
+	 * @throws EE_Error
811
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
812
+	 *                                                     relation from all
813
+	 */
814
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
+	{
816
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
817
+		$index_in_cache = '';
818
+		if (! $relationship_to_model) {
819
+			throw new EE_Error(
820
+				sprintf(
821
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
822
+					$relationName,
823
+					get_class($this)
824
+				)
825
+			);
826
+		}
827
+		if ($clear_all) {
828
+			$obj_removed = true;
829
+			$this->_model_relations[ $relationName ] = null;
830
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
+			$obj_removed = $this->_model_relations[ $relationName ];
832
+			$this->_model_relations[ $relationName ] = null;
833
+		} else {
834
+			if (
835
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
836
+				&& $object_to_remove_or_index_into_array->ID()
837
+			) {
838
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
839
+				if (
840
+					is_array($this->_model_relations[ $relationName ])
841
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
842
+				) {
843
+					$index_found_at = null;
844
+					// find this object in the array even though it has a different key
845
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
846
+						/** @noinspection TypeUnsafeComparisonInspection */
847
+						if (
848
+							$obj instanceof EE_Base_Class
849
+							&& (
850
+								$obj == $object_to_remove_or_index_into_array
851
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
852
+							)
853
+						) {
854
+							$index_found_at = $index;
855
+							break;
856
+						}
857
+					}
858
+					if ($index_found_at) {
859
+						$index_in_cache = $index_found_at;
860
+					} else {
861
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
862
+						// if it wasn't in it to begin with. So we're done
863
+						return $object_to_remove_or_index_into_array;
864
+					}
865
+				}
866
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
867
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
868
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
869
+					/** @noinspection TypeUnsafeComparisonInspection */
870
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
871
+						$index_in_cache = $index;
872
+					}
873
+				}
874
+			} else {
875
+				$index_in_cache = $object_to_remove_or_index_into_array;
876
+			}
877
+			// supposedly we've found it. But it could just be that the client code
878
+			// provided a bad index/object
879
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
880
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
881
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
882
+			} else {
883
+				// that thing was never cached anyways.
884
+				$obj_removed = null;
885
+			}
886
+		}
887
+		return $obj_removed;
888
+	}
889
+
890
+
891
+	/**
892
+	 * update_cache_after_object_save
893
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
894
+	 * obtained after being saved to the db
895
+	 *
896
+	 * @param string        $relationName       - the type of object that is cached
897
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
898
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
899
+	 * @return boolean TRUE on success, FALSE on fail
900
+	 * @throws ReflectionException
901
+	 * @throws InvalidArgumentException
902
+	 * @throws InvalidInterfaceException
903
+	 * @throws InvalidDataTypeException
904
+	 * @throws EE_Error
905
+	 */
906
+	public function update_cache_after_object_save(
907
+		$relationName,
908
+		EE_Base_Class $newly_saved_object,
909
+		$current_cache_id = ''
910
+	) {
911
+		// verify that incoming object is of the correct type
912
+		$obj_class = 'EE_' . $relationName;
913
+		if ($newly_saved_object instanceof $obj_class) {
914
+			/* @type EE_Base_Class $newly_saved_object */
915
+			// now get the type of relation
916
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
917
+			// if this is a 1:1 relationship
918
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919
+				// then just replace the cached object with the newly saved object
920
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
921
+				return true;
922
+				// or if it's some kind of sordid feral polyamorous relationship...
923
+			}
924
+			if (
925
+				is_array($this->_model_relations[ $relationName ])
926
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
927
+			) {
928
+				// then remove the current cached item
929
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
930
+				// and cache the newly saved object using it's new ID
931
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
+				return true;
933
+			}
934
+		}
935
+		return false;
936
+	}
937
+
938
+
939
+	/**
940
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
941
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
942
+	 *
943
+	 * @param string $relationName
944
+	 * @return EE_Base_Class
945
+	 */
946
+	public function get_one_from_cache($relationName)
947
+	{
948
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
949
+			? $this->_model_relations[ $relationName ]
950
+			: null;
951
+		if (is_array($cached_array_or_object)) {
952
+			return array_shift($cached_array_or_object);
953
+		}
954
+		return $cached_array_or_object;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
960
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
961
+	 *
962
+	 * @param string $relationName
963
+	 * @throws ReflectionException
964
+	 * @throws InvalidArgumentException
965
+	 * @throws InvalidInterfaceException
966
+	 * @throws InvalidDataTypeException
967
+	 * @throws EE_Error
968
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
969
+	 */
970
+	public function get_all_from_cache($relationName)
971
+	{
972
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
973
+		// if the result is not an array, but exists, make it an array
974
+		$objects = is_array($objects) ? $objects : array($objects);
975
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
976
+		// basically, if this model object was stored in the session, and these cached model objects
977
+		// already have IDs, let's make sure they're in their model's entity mapper
978
+		// otherwise we will have duplicates next time we call
979
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
980
+		$model = EE_Registry::instance()->load_model($relationName);
981
+		foreach ($objects as $model_object) {
982
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
983
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
984
+				if ($model_object->ID()) {
985
+					$model->add_to_entity_map($model_object);
986
+				}
987
+			} else {
988
+				throw new EE_Error(
989
+					sprintf(
990
+						esc_html__(
991
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
992
+							'event_espresso'
993
+						),
994
+						$relationName,
995
+						gettype($model_object)
996
+					)
997
+				);
998
+			}
999
+		}
1000
+		return $objects;
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1006
+	 * matching the given query conditions.
1007
+	 *
1008
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1009
+	 * @param int   $limit              How many objects to return.
1010
+	 * @param array $query_params       Any additional conditions on the query.
1011
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1012
+	 *                                  you can indicate just the columns you want returned
1013
+	 * @return array|EE_Base_Class[]
1014
+	 * @throws ReflectionException
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidInterfaceException
1017
+	 * @throws InvalidDataTypeException
1018
+	 * @throws EE_Error
1019
+	 */
1020
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1021
+	{
1022
+		$model = $this->get_model();
1023
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1024
+			? $model->get_primary_key_field()->get_name()
1025
+			: $field_to_order_by;
1026
+		$current_value = ! empty($field) ? $this->get($field) : null;
1027
+		if (empty($field) || empty($current_value)) {
1028
+			return array();
1029
+		}
1030
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1036
+	 * matching the given query conditions.
1037
+	 *
1038
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1039
+	 * @param int   $limit              How many objects to return.
1040
+	 * @param array $query_params       Any additional conditions on the query.
1041
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1042
+	 *                                  you can indicate just the columns you want returned
1043
+	 * @return array|EE_Base_Class[]
1044
+	 * @throws ReflectionException
1045
+	 * @throws InvalidArgumentException
1046
+	 * @throws InvalidInterfaceException
1047
+	 * @throws InvalidDataTypeException
1048
+	 * @throws EE_Error
1049
+	 */
1050
+	public function previous_x(
1051
+		$field_to_order_by = null,
1052
+		$limit = 1,
1053
+		$query_params = array(),
1054
+		$columns_to_select = null
1055
+	) {
1056
+		$model = $this->get_model();
1057
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1058
+			? $model->get_primary_key_field()->get_name()
1059
+			: $field_to_order_by;
1060
+		$current_value = ! empty($field) ? $this->get($field) : null;
1061
+		if (empty($field) || empty($current_value)) {
1062
+			return array();
1063
+		}
1064
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1070
+	 * matching the given query conditions.
1071
+	 *
1072
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1073
+	 * @param array $query_params       Any additional conditions on the query.
1074
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1075
+	 *                                  you can indicate just the columns you want returned
1076
+	 * @return array|EE_Base_Class
1077
+	 * @throws ReflectionException
1078
+	 * @throws InvalidArgumentException
1079
+	 * @throws InvalidInterfaceException
1080
+	 * @throws InvalidDataTypeException
1081
+	 * @throws EE_Error
1082
+	 */
1083
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1084
+	{
1085
+		$model = $this->get_model();
1086
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1087
+			? $model->get_primary_key_field()->get_name()
1088
+			: $field_to_order_by;
1089
+		$current_value = ! empty($field) ? $this->get($field) : null;
1090
+		if (empty($field) || empty($current_value)) {
1091
+			return array();
1092
+		}
1093
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1099
+	 * matching the given query conditions.
1100
+	 *
1101
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1102
+	 * @param array $query_params       Any additional conditions on the query.
1103
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1104
+	 *                                  you can indicate just the column you want returned
1105
+	 * @return array|EE_Base_Class
1106
+	 * @throws ReflectionException
1107
+	 * @throws InvalidArgumentException
1108
+	 * @throws InvalidInterfaceException
1109
+	 * @throws InvalidDataTypeException
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1113
+	{
1114
+		$model = $this->get_model();
1115
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1116
+			? $model->get_primary_key_field()->get_name()
1117
+			: $field_to_order_by;
1118
+		$current_value = ! empty($field) ? $this->get($field) : null;
1119
+		if (empty($field) || empty($current_value)) {
1120
+			return array();
1121
+		}
1122
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Overrides parent because parent expects old models.
1128
+	 * This also doesn't do any validation, and won't work for serialized arrays
1129
+	 *
1130
+	 * @param string $field_name
1131
+	 * @param mixed  $field_value_from_db
1132
+	 * @throws ReflectionException
1133
+	 * @throws InvalidArgumentException
1134
+	 * @throws InvalidInterfaceException
1135
+	 * @throws InvalidDataTypeException
1136
+	 * @throws EE_Error
1137
+	 */
1138
+	public function set_from_db($field_name, $field_value_from_db)
1139
+	{
1140
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1141
+		if ($field_obj instanceof EE_Model_Field_Base) {
1142
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1143
+			// eg, a CPT model object could have an entry in the posts table, but no
1144
+			// entry in the meta table. Meaning that all its columns in the meta table
1145
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1146
+			if ($field_value_from_db === null) {
1147
+				if ($field_obj->is_nullable()) {
1148
+					// if the field allows nulls, then let it be null
1149
+					$field_value = null;
1150
+				} else {
1151
+					$field_value = $field_obj->get_default_value();
1152
+				}
1153
+			} else {
1154
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1155
+			}
1156
+			$this->_fields[ $field_name ] = $field_value;
1157
+			$this->_clear_cached_property($field_name);
1158
+		}
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * verifies that the specified field is of the correct type
1164
+	 *
1165
+	 * @param string $field_name
1166
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
+	 *                                (in cases where the same property may be used for different outputs
1168
+	 *                                - i.e. datetime, money etc.)
1169
+	 * @return mixed
1170
+	 * @throws ReflectionException
1171
+	 * @throws InvalidArgumentException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @throws InvalidDataTypeException
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get($field_name, $extra_cache_ref = null)
1177
+	{
1178
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1179
+	}
1180
+
1181
+
1182
+	/**
1183
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1184
+	 *
1185
+	 * @param  string $field_name A valid fieldname
1186
+	 * @return mixed              Whatever the raw value stored on the property is.
1187
+	 * @throws ReflectionException
1188
+	 * @throws InvalidArgumentException
1189
+	 * @throws InvalidInterfaceException
1190
+	 * @throws InvalidDataTypeException
1191
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1192
+	 */
1193
+	public function get_raw($field_name)
1194
+	{
1195
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1196
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1197
+			? $this->_fields[ $field_name ]->format('U')
1198
+			: $this->_fields[ $field_name ];
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * This is used to return the internal DateTime object used for a field that is a
1204
+	 * EE_Datetime_Field.
1205
+	 *
1206
+	 * @param string $field_name               The field name retrieving the DateTime object.
1207
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1208
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1209
+	 *                                         EE_Datetime_Field and but the field value is null, then
1210
+	 *                                         just null is returned (because that indicates that likely
1211
+	 *                                         this field is nullable).
1212
+	 * @throws InvalidArgumentException
1213
+	 * @throws InvalidDataTypeException
1214
+	 * @throws InvalidInterfaceException
1215
+	 * @throws ReflectionException
1216
+	 */
1217
+	public function get_DateTime_object($field_name)
1218
+	{
1219
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1220
+		if (! $field_settings instanceof EE_Datetime_Field) {
1221
+			EE_Error::add_error(
1222
+				sprintf(
1223
+					esc_html__(
1224
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1225
+						'event_espresso'
1226
+					),
1227
+					$field_name
1228
+				),
1229
+				__FILE__,
1230
+				__FUNCTION__,
1231
+				__LINE__
1232
+			);
1233
+			return false;
1234
+		}
1235
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1236
+			? clone $this->_fields[ $field_name ]
1237
+			: null;
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * To be used in template to immediately echo out the value, and format it for output.
1243
+	 * Eg, should call stripslashes and whatnot before echoing
1244
+	 *
1245
+	 * @param string $field_name      the name of the field as it appears in the DB
1246
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1247
+	 *                                (in cases where the same property may be used for different outputs
1248
+	 *                                - i.e. datetime, money etc.)
1249
+	 * @return void
1250
+	 * @throws ReflectionException
1251
+	 * @throws InvalidArgumentException
1252
+	 * @throws InvalidInterfaceException
1253
+	 * @throws InvalidDataTypeException
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function e($field_name, $extra_cache_ref = null)
1257
+	{
1258
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1264
+	 * can be easily used as the value of form input.
1265
+	 *
1266
+	 * @param string $field_name
1267
+	 * @return void
1268
+	 * @throws ReflectionException
1269
+	 * @throws InvalidArgumentException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws InvalidDataTypeException
1272
+	 * @throws EE_Error
1273
+	 */
1274
+	public function f($field_name)
1275
+	{
1276
+		$this->e($field_name, 'form_input');
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * Same as `f()` but just returns the value instead of echoing it
1282
+	 *
1283
+	 * @param string $field_name
1284
+	 * @return string
1285
+	 * @throws ReflectionException
1286
+	 * @throws InvalidArgumentException
1287
+	 * @throws InvalidInterfaceException
1288
+	 * @throws InvalidDataTypeException
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function get_f($field_name)
1292
+	{
1293
+		return (string) $this->get_pretty($field_name, 'form_input');
1294
+	}
1295
+
1296
+
1297
+	/**
1298
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1299
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1300
+	 * to see what options are available.
1301
+	 *
1302
+	 * @param string $field_name
1303
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1304
+	 *                                (in cases where the same property may be used for different outputs
1305
+	 *                                - i.e. datetime, money etc.)
1306
+	 * @return mixed
1307
+	 * @throws ReflectionException
1308
+	 * @throws InvalidArgumentException
1309
+	 * @throws InvalidInterfaceException
1310
+	 * @throws InvalidDataTypeException
1311
+	 * @throws EE_Error
1312
+	 */
1313
+	public function get_pretty($field_name, $extra_cache_ref = null)
1314
+	{
1315
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * This simply returns the datetime for the given field name
1321
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1322
+	 * (and the equivalent e_date, e_time, e_datetime).
1323
+	 *
1324
+	 * @access   protected
1325
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1326
+	 * @param string   $dt_frmt      valid datetime format used for date
1327
+	 *                               (if '' then we just use the default on the field,
1328
+	 *                               if NULL we use the last-used format)
1329
+	 * @param string   $tm_frmt      Same as above except this is for time format
1330
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1331
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1332
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1333
+	 *                               if field is not a valid dtt field, or void if echoing
1334
+	 * @throws ReflectionException
1335
+	 * @throws InvalidArgumentException
1336
+	 * @throws InvalidInterfaceException
1337
+	 * @throws InvalidDataTypeException
1338
+	 * @throws EE_Error
1339
+	 */
1340
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1341
+	{
1342
+		// clear cached property
1343
+		$this->_clear_cached_property($field_name);
1344
+		// reset format properties because they are used in get()
1345
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1346
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1347
+		if ($echo) {
1348
+			$this->e($field_name, $date_or_time);
1349
+			return '';
1350
+		}
1351
+		return $this->get($field_name, $date_or_time);
1352
+	}
1353
+
1354
+
1355
+	/**
1356
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1357
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1358
+	 * other echoes the pretty value for dtt)
1359
+	 *
1360
+	 * @param  string $field_name name of model object datetime field holding the value
1361
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1362
+	 * @return string            datetime value formatted
1363
+	 * @throws ReflectionException
1364
+	 * @throws InvalidArgumentException
1365
+	 * @throws InvalidInterfaceException
1366
+	 * @throws InvalidDataTypeException
1367
+	 * @throws EE_Error
1368
+	 */
1369
+	public function get_date($field_name, $format = '')
1370
+	{
1371
+		return $this->_get_datetime($field_name, $format, null, 'D');
1372
+	}
1373
+
1374
+
1375
+	/**
1376
+	 * @param        $field_name
1377
+	 * @param string $format
1378
+	 * @throws ReflectionException
1379
+	 * @throws InvalidArgumentException
1380
+	 * @throws InvalidInterfaceException
1381
+	 * @throws InvalidDataTypeException
1382
+	 * @throws EE_Error
1383
+	 */
1384
+	public function e_date($field_name, $format = '')
1385
+	{
1386
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1392
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1393
+	 * other echoes the pretty value for dtt)
1394
+	 *
1395
+	 * @param  string $field_name name of model object datetime field holding the value
1396
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1397
+	 * @return string             datetime value formatted
1398
+	 * @throws ReflectionException
1399
+	 * @throws InvalidArgumentException
1400
+	 * @throws InvalidInterfaceException
1401
+	 * @throws InvalidDataTypeException
1402
+	 * @throws EE_Error
1403
+	 */
1404
+	public function get_time($field_name, $format = '')
1405
+	{
1406
+		return $this->_get_datetime($field_name, null, $format, 'T');
1407
+	}
1408
+
1409
+
1410
+	/**
1411
+	 * @param        $field_name
1412
+	 * @param string $format
1413
+	 * @throws ReflectionException
1414
+	 * @throws InvalidArgumentException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws InvalidDataTypeException
1417
+	 * @throws EE_Error
1418
+	 */
1419
+	public function e_time($field_name, $format = '')
1420
+	{
1421
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1427
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1428
+	 * other echoes the pretty value for dtt)
1429
+	 *
1430
+	 * @param  string $field_name name of model object datetime field holding the value
1431
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1432
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1433
+	 * @return string             datetime value formatted
1434
+	 * @throws ReflectionException
1435
+	 * @throws InvalidArgumentException
1436
+	 * @throws InvalidInterfaceException
1437
+	 * @throws InvalidDataTypeException
1438
+	 * @throws EE_Error
1439
+	 */
1440
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1441
+	{
1442
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * @param string $field_name
1448
+	 * @param string $dt_frmt
1449
+	 * @param string $tm_frmt
1450
+	 * @throws ReflectionException
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws EE_Error
1455
+	 */
1456
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1457
+	{
1458
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1459
+	}
1460
+
1461
+
1462
+	/**
1463
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1464
+	 *
1465
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1466
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1467
+	 *                           on the object will be used.
1468
+	 * @return string Date and time string in set locale or false if no field exists for the given
1469
+	 * @throws ReflectionException
1470
+	 * @throws InvalidArgumentException
1471
+	 * @throws InvalidInterfaceException
1472
+	 * @throws InvalidDataTypeException
1473
+	 * @throws EE_Error
1474
+	 *                           field name.
1475
+	 */
1476
+	public function get_i18n_datetime($field_name, $format = '')
1477
+	{
1478
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
+		return date_i18n(
1480
+			$format,
1481
+			EEH_DTT_Helper::get_timestamp_with_offset(
1482
+				$this->get_raw($field_name),
1483
+				$this->_timezone
1484
+			)
1485
+		);
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1491
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1492
+	 * thrown.
1493
+	 *
1494
+	 * @param  string $field_name The field name being checked
1495
+	 * @throws ReflectionException
1496
+	 * @throws InvalidArgumentException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws InvalidDataTypeException
1499
+	 * @throws EE_Error
1500
+	 * @return EE_Datetime_Field
1501
+	 */
1502
+	protected function _get_dtt_field_settings($field_name)
1503
+	{
1504
+		$field = $this->get_model()->field_settings_for($field_name);
1505
+		// check if field is dtt
1506
+		if ($field instanceof EE_Datetime_Field) {
1507
+			return $field;
1508
+		}
1509
+		throw new EE_Error(
1510
+			sprintf(
1511
+				esc_html__(
1512
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1513
+					'event_espresso'
1514
+				),
1515
+				$field_name,
1516
+				self::_get_model_classname(get_class($this))
1517
+			)
1518
+		);
1519
+	}
1520
+
1521
+
1522
+
1523
+
1524
+	/**
1525
+	 * NOTE ABOUT BELOW:
1526
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1527
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1528
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1529
+	 * method and make sure you send the entire datetime value for setting.
1530
+	 */
1531
+	/**
1532
+	 * sets the time on a datetime property
1533
+	 *
1534
+	 * @access protected
1535
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1536
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1537
+	 * @throws ReflectionException
1538
+	 * @throws InvalidArgumentException
1539
+	 * @throws InvalidInterfaceException
1540
+	 * @throws InvalidDataTypeException
1541
+	 * @throws EE_Error
1542
+	 */
1543
+	protected function _set_time_for($time, $fieldname)
1544
+	{
1545
+		$this->_set_date_time('T', $time, $fieldname);
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * sets the date on a datetime property
1551
+	 *
1552
+	 * @access protected
1553
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1554
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1555
+	 * @throws ReflectionException
1556
+	 * @throws InvalidArgumentException
1557
+	 * @throws InvalidInterfaceException
1558
+	 * @throws InvalidDataTypeException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	protected function _set_date_for($date, $fieldname)
1562
+	{
1563
+		$this->_set_date_time('D', $date, $fieldname);
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1569
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1570
+	 *
1571
+	 * @access protected
1572
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1573
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1574
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1575
+	 *                                        EE_Datetime_Field property)
1576
+	 * @throws ReflectionException
1577
+	 * @throws InvalidArgumentException
1578
+	 * @throws InvalidInterfaceException
1579
+	 * @throws InvalidDataTypeException
1580
+	 * @throws EE_Error
1581
+	 */
1582
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1583
+	{
1584
+		$field = $this->_get_dtt_field_settings($fieldname);
1585
+		$field->set_timezone($this->_timezone);
1586
+		$field->set_date_format($this->_dt_frmt);
1587
+		$field->set_time_format($this->_tm_frmt);
1588
+		switch ($what) {
1589
+			case 'T':
1590
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
+					$datetime_value,
1592
+					$this->_fields[ $fieldname ]
1593
+				);
1594
+				$this->_has_changes = true;
1595
+				break;
1596
+			case 'D':
1597
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
+					$datetime_value,
1599
+					$this->_fields[ $fieldname ]
1600
+				);
1601
+				$this->_has_changes = true;
1602
+				break;
1603
+			case 'B':
1604
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
+				$this->_has_changes = true;
1606
+				break;
1607
+		}
1608
+		$this->_clear_cached_property($fieldname);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
+	 * that could lead to some unexpected results!
1617
+	 *
1618
+	 * @access public
1619
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
+	 *                                         value being returned.
1621
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1624
+	 * @param string $append                   You can include something to append on the timestamp
1625
+	 * @throws ReflectionException
1626
+	 * @throws InvalidArgumentException
1627
+	 * @throws InvalidInterfaceException
1628
+	 * @throws InvalidDataTypeException
1629
+	 * @throws EE_Error
1630
+	 * @return string timestamp
1631
+	 */
1632
+	public function display_in_my_timezone(
1633
+		$field_name,
1634
+		$callback = 'get_datetime',
1635
+		$args = null,
1636
+		$prepend = '',
1637
+		$append = ''
1638
+	) {
1639
+		$timezone = EEH_DTT_Helper::get_timezone();
1640
+		if ($timezone === $this->_timezone) {
1641
+			return '';
1642
+		}
1643
+		$original_timezone = $this->_timezone;
1644
+		$this->set_timezone($timezone);
1645
+		$fn = (array) $field_name;
1646
+		$args = array_merge($fn, (array) $args);
1647
+		if (! method_exists($this, $callback)) {
1648
+			throw new EE_Error(
1649
+				sprintf(
1650
+					esc_html__(
1651
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
+						'event_espresso'
1653
+					),
1654
+					$callback
1655
+				)
1656
+			);
1657
+		}
1658
+		$args = (array) $args;
1659
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
+		$this->set_timezone($original_timezone);
1661
+		return $return;
1662
+	}
1663
+
1664
+
1665
+	/**
1666
+	 * Deletes this model object.
1667
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
+	 * override
1669
+	 * `EE_Base_Class::_delete` NOT this class.
1670
+	 *
1671
+	 * @return boolean | int
1672
+	 * @throws ReflectionException
1673
+	 * @throws InvalidArgumentException
1674
+	 * @throws InvalidInterfaceException
1675
+	 * @throws InvalidDataTypeException
1676
+	 * @throws EE_Error
1677
+	 */
1678
+	public function delete()
1679
+	{
1680
+		/**
1681
+		 * Called just before the `EE_Base_Class::_delete` method call.
1682
+		 * Note:
1683
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
+		 * should be aware that `_delete` may not always result in a permanent delete.
1685
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
+		 * soft deletes (trash) the object and does not permanently delete it.
1687
+		 *
1688
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1689
+		 */
1690
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
+		$result = $this->_delete();
1692
+		/**
1693
+		 * Called just after the `EE_Base_Class::_delete` method call.
1694
+		 * Note:
1695
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
+		 * should be aware that `_delete` may not always result in a permanent delete.
1697
+		 * For example `EE_Soft_Base_Class::_delete`
1698
+		 * soft deletes (trash) the object and does not permanently delete it.
1699
+		 *
1700
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1701
+		 * @param boolean       $result
1702
+		 */
1703
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
+		return $result;
1705
+	}
1706
+
1707
+
1708
+	/**
1709
+	 * Calls the specific delete method for the instantiated class.
1710
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
+	 * `EE_Base_Class::delete`
1713
+	 *
1714
+	 * @return bool|int
1715
+	 * @throws ReflectionException
1716
+	 * @throws InvalidArgumentException
1717
+	 * @throws InvalidInterfaceException
1718
+	 * @throws InvalidDataTypeException
1719
+	 * @throws EE_Error
1720
+	 */
1721
+	protected function _delete()
1722
+	{
1723
+		return $this->delete_permanently();
1724
+	}
1725
+
1726
+
1727
+	/**
1728
+	 * Deletes this model object permanently from db
1729
+	 * (but keep in mind related models may block the delete and return an error)
1730
+	 *
1731
+	 * @return bool | int
1732
+	 * @throws ReflectionException
1733
+	 * @throws InvalidArgumentException
1734
+	 * @throws InvalidInterfaceException
1735
+	 * @throws InvalidDataTypeException
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function delete_permanently()
1739
+	{
1740
+		/**
1741
+		 * Called just before HARD deleting a model object
1742
+		 *
1743
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1744
+		 */
1745
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
+		$model = $this->get_model();
1747
+		$result = $model->delete_permanently_by_ID($this->ID());
1748
+		$this->refresh_cache_of_related_objects();
1749
+		/**
1750
+		 * Called just after HARD deleting a model object
1751
+		 *
1752
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1753
+		 * @param boolean       $result
1754
+		 */
1755
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
+		return $result;
1757
+	}
1758
+
1759
+
1760
+	/**
1761
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
+	 * related model objects
1763
+	 *
1764
+	 * @throws ReflectionException
1765
+	 * @throws InvalidArgumentException
1766
+	 * @throws InvalidInterfaceException
1767
+	 * @throws InvalidDataTypeException
1768
+	 * @throws EE_Error
1769
+	 */
1770
+	public function refresh_cache_of_related_objects()
1771
+	{
1772
+		$model = $this->get_model();
1773
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
+			if (! empty($this->_model_relations[ $relation_name ])) {
1775
+				$related_objects = $this->_model_relations[ $relation_name ];
1776
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
+					// this relation only stores a single model object, not an array
1778
+					// but let's make it consistent
1779
+					$related_objects = array($related_objects);
1780
+				}
1781
+				foreach ($related_objects as $related_object) {
1782
+					// only refresh their cache if they're in memory
1783
+					if ($related_object instanceof EE_Base_Class) {
1784
+						$related_object->clear_cache(
1785
+							$model->get_this_model_name(),
1786
+							$this
1787
+						);
1788
+					}
1789
+				}
1790
+			}
1791
+		}
1792
+	}
1793
+
1794
+
1795
+	/**
1796
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1797
+	 * object just before saving.
1798
+	 *
1799
+	 * @access public
1800
+	 * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
+	 *                                  if provided during the save() method
1802
+	 *                                  (often client code will change the fields' values before calling save)
1803
+	 * @return false|int|string         1 on a successful update;
1804
+	 *                                  the ID of the new entry on insert;
1805
+	 *                                  0 on failure, or if the model object isn't allowed to persist
1806
+	 *                                  (as determined by EE_Base_Class::allow_persist())
1807
+	 * @throws InvalidInterfaceException
1808
+	 * @throws InvalidDataTypeException
1809
+	 * @throws EE_Error
1810
+	 * @throws InvalidArgumentException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 * @throws ReflectionException
1814
+	 */
1815
+	public function save($set_cols_n_values = array())
1816
+	{
1817
+		$model = $this->get_model();
1818
+		/**
1819
+		 * Filters the fields we're about to save on the model object
1820
+		 *
1821
+		 * @param array         $set_cols_n_values
1822
+		 * @param EE_Base_Class $model_object
1823
+		 */
1824
+		$set_cols_n_values = (array) apply_filters(
1825
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
+			$set_cols_n_values,
1827
+			$this
1828
+		);
1829
+		// set attributes as provided in $set_cols_n_values
1830
+		foreach ($set_cols_n_values as $column => $value) {
1831
+			$this->set($column, $value);
1832
+		}
1833
+		// no changes ? then don't do anything
1834
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
+			return 0;
1836
+		}
1837
+		/**
1838
+		 * Saving a model object.
1839
+		 * Before we perform a save, this action is fired.
1840
+		 *
1841
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1842
+		 */
1843
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
+		if (! $this->allow_persist()) {
1845
+			return 0;
1846
+		}
1847
+		// now get current attribute values
1848
+		$save_cols_n_values = $this->_fields;
1849
+		// if the object already has an ID, update it. Otherwise, insert it
1850
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
+		// They have been
1852
+		$old_assumption_concerning_value_preparation = $model
1853
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1854
+		$model->assume_values_already_prepared_by_model_object(true);
1855
+		// does this model have an autoincrement PK?
1856
+		if ($model->has_primary_key_field()) {
1857
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1858
+				// ok check if it's set, if so: update; if not, insert
1859
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
+				} else {
1862
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
+					$results = $model->insert($save_cols_n_values);
1864
+					if ($results) {
1865
+						// if successful, set the primary key
1866
+						// but don't use the normal SET method, because it will check if
1867
+						// an item with the same ID exists in the mapper & db, then
1868
+						// will find it in the db (because we just added it) and THAT object
1869
+						// will get added to the mapper before we can add this one!
1870
+						// but if we just avoid using the SET method, all that headache can be avoided
1871
+						$pk_field_name = $model->primary_key_name();
1872
+						$this->_fields[ $pk_field_name ] = $results;
1873
+						$this->_clear_cached_property($pk_field_name);
1874
+						$model->add_to_entity_map($this);
1875
+						$this->_update_cached_related_model_objs_fks();
1876
+					}
1877
+				}
1878
+			} else {// PK is NOT auto-increment
1879
+				// so check if one like it already exists in the db
1880
+				if ($model->exists_by_ID($this->ID())) {
1881
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1882
+						throw new EE_Error(
1883
+							sprintf(
1884
+								esc_html__(
1885
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1886
+									'event_espresso'
1887
+								),
1888
+								get_class($this),
1889
+								get_class($model) . '::instance()->add_to_entity_map()',
1890
+								get_class($model) . '::instance()->get_one_by_ID()',
1891
+								'<br />'
1892
+							)
1893
+						);
1894
+					}
1895
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
+				} else {
1897
+					$results = $model->insert($save_cols_n_values);
1898
+					$this->_update_cached_related_model_objs_fks();
1899
+				}
1900
+			}
1901
+		} else {// there is NO primary key
1902
+			$already_in_db = false;
1903
+			foreach ($model->unique_indexes() as $index) {
1904
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
+				if ($model->exists(array($uniqueness_where_params))) {
1906
+					$already_in_db = true;
1907
+				}
1908
+			}
1909
+			if ($already_in_db) {
1910
+				$combined_pk_fields_n_values = array_intersect_key(
1911
+					$save_cols_n_values,
1912
+					$model->get_combined_primary_key_fields()
1913
+				);
1914
+				$results = $model->update(
1915
+					$save_cols_n_values,
1916
+					$combined_pk_fields_n_values
1917
+				);
1918
+			} else {
1919
+				$results = $model->insert($save_cols_n_values);
1920
+			}
1921
+		}
1922
+		// restore the old assumption about values being prepared by the model object
1923
+		$model->assume_values_already_prepared_by_model_object(
1924
+			$old_assumption_concerning_value_preparation
1925
+		);
1926
+		/**
1927
+		 * After saving the model object this action is called
1928
+		 *
1929
+		 * @param EE_Base_Class $model_object which was just saved
1930
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
+		 */
1933
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
+		$this->_has_changes = false;
1935
+		return $results;
1936
+	}
1937
+
1938
+
1939
+	/**
1940
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1945
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
+	 *
1948
+	 * @return void
1949
+	 * @throws ReflectionException
1950
+	 * @throws InvalidArgumentException
1951
+	 * @throws InvalidInterfaceException
1952
+	 * @throws InvalidDataTypeException
1953
+	 * @throws EE_Error
1954
+	 */
1955
+	protected function _update_cached_related_model_objs_fks()
1956
+	{
1957
+		$model = $this->get_model();
1958
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
+						$model->get_this_model_name()
1963
+					);
1964
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
+					if ($related_model_obj_in_cache->ID()) {
1966
+						$related_model_obj_in_cache->save();
1967
+					}
1968
+				}
1969
+			}
1970
+		}
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * Saves this model object and its NEW cached relations to the database.
1976
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1978
+	 * because otherwise, there's a potential for infinite looping of saving
1979
+	 * Saves the cached related model objects, and ensures the relation between them
1980
+	 * and this object and properly setup
1981
+	 *
1982
+	 * @return int ID of new model object on save; 0 on failure+
1983
+	 * @throws ReflectionException
1984
+	 * @throws InvalidArgumentException
1985
+	 * @throws InvalidInterfaceException
1986
+	 * @throws InvalidDataTypeException
1987
+	 * @throws EE_Error
1988
+	 */
1989
+	public function save_new_cached_related_model_objs()
1990
+	{
1991
+		// make sure this has been saved
1992
+		if (! $this->ID()) {
1993
+			$id = $this->save();
1994
+		} else {
1995
+			$id = $this->ID();
1996
+		}
1997
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
+			if ($this->_model_relations[ $relationName ]) {
2000
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
+				/* @var $related_model_obj EE_Base_Class */
2003
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2005
+					// but ONLY if it DOES NOT exist in the DB
2006
+					$related_model_obj = $this->_model_relations[ $relationName ];
2007
+					// if( ! $related_model_obj->ID()){
2008
+					$this->_add_relation_to($related_model_obj, $relationName);
2009
+					$related_model_obj->save_new_cached_related_model_objs();
2010
+					// }
2011
+				} else {
2012
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2014
+						// but ONLY if it DOES NOT exist in the DB
2015
+						// if( ! $related_model_obj->ID()){
2016
+						$this->_add_relation_to($related_model_obj, $relationName);
2017
+						$related_model_obj->save_new_cached_related_model_objs();
2018
+						// }
2019
+					}
2020
+				}
2021
+			}
2022
+		}
2023
+		return $id;
2024
+	}
2025
+
2026
+
2027
+	/**
2028
+	 * for getting a model while instantiated.
2029
+	 *
2030
+	 * @return EEM_Base | EEM_CPT_Base
2031
+	 * @throws ReflectionException
2032
+	 * @throws InvalidArgumentException
2033
+	 * @throws InvalidInterfaceException
2034
+	 * @throws InvalidDataTypeException
2035
+	 * @throws EE_Error
2036
+	 */
2037
+	public function get_model()
2038
+	{
2039
+		if (! $this->_model) {
2040
+			$modelName = self::_get_model_classname(get_class($this));
2041
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
+		} else {
2043
+			$this->_model->set_timezone($this->_timezone);
2044
+		}
2045
+		return $this->_model;
2046
+	}
2047
+
2048
+
2049
+	/**
2050
+	 * @param $props_n_values
2051
+	 * @param $classname
2052
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
+	 * @throws ReflectionException
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 */
2059
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
+	{
2061
+		// TODO: will not work for Term_Relationships because they have no PK!
2062
+		$primary_id_ref = self::_get_primary_key_name($classname);
2063
+		if (
2064
+			array_key_exists($primary_id_ref, $props_n_values)
2065
+			&& ! empty($props_n_values[ $primary_id_ref ])
2066
+		) {
2067
+			$id = $props_n_values[ $primary_id_ref ];
2068
+			return self::_get_model($classname)->get_from_entity_map($id);
2069
+		}
2070
+		return false;
2071
+	}
2072
+
2073
+
2074
+	/**
2075
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2078
+	 * we return false.
2079
+	 *
2080
+	 * @param  array  $props_n_values   incoming array of properties and their values
2081
+	 * @param  string $classname        the classname of the child class
2082
+	 * @param null    $timezone
2083
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
+	 *                                  date_format and the second value is the time format
2085
+	 * @return mixed (EE_Base_Class|bool)
2086
+	 * @throws InvalidArgumentException
2087
+	 * @throws InvalidInterfaceException
2088
+	 * @throws InvalidDataTypeException
2089
+	 * @throws EE_Error
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 * @throws ReflectionException
2093
+	 */
2094
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
+	{
2096
+		$existing = null;
2097
+		$model = self::_get_model($classname, $timezone);
2098
+		if ($model->has_primary_key_field()) {
2099
+			$primary_id_ref = self::_get_primary_key_name($classname);
2100
+			if (
2101
+				array_key_exists($primary_id_ref, $props_n_values)
2102
+				&& ! empty($props_n_values[ $primary_id_ref ])
2103
+			) {
2104
+				$existing = $model->get_one_by_ID(
2105
+					$props_n_values[ $primary_id_ref ]
2106
+				);
2107
+			}
2108
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
+			// no primary key on this model, but there's still a matching item in the DB
2110
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
+				self::_get_model($classname, $timezone)
2112
+					->get_index_primary_key_string($props_n_values)
2113
+			);
2114
+		}
2115
+		if ($existing) {
2116
+			// set date formats if present before setting values
2117
+			if (! empty($date_formats) && is_array($date_formats)) {
2118
+				$existing->set_date_format($date_formats[0]);
2119
+				$existing->set_time_format($date_formats[1]);
2120
+			} else {
2121
+				// set default formats for date and time
2122
+				$existing->set_date_format(get_option('date_format'));
2123
+				$existing->set_time_format(get_option('time_format'));
2124
+			}
2125
+			foreach ($props_n_values as $property => $field_value) {
2126
+				$existing->set($property, $field_value);
2127
+			}
2128
+			return $existing;
2129
+		}
2130
+		return false;
2131
+	}
2132
+
2133
+
2134
+	/**
2135
+	 * Gets the EEM_*_Model for this class
2136
+	 *
2137
+	 * @access public now, as this is more convenient
2138
+	 * @param      $classname
2139
+	 * @param null $timezone
2140
+	 * @throws ReflectionException
2141
+	 * @throws InvalidArgumentException
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @throws InvalidDataTypeException
2144
+	 * @throws EE_Error
2145
+	 * @return EEM_Base
2146
+	 */
2147
+	protected static function _get_model($classname, $timezone = null)
2148
+	{
2149
+		// find model for this class
2150
+		if (! $classname) {
2151
+			throw new EE_Error(
2152
+				sprintf(
2153
+					esc_html__(
2154
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
+						'event_espresso'
2156
+					),
2157
+					$classname
2158
+				)
2159
+			);
2160
+		}
2161
+		$modelName = self::_get_model_classname($classname);
2162
+		return self::_get_model_instance_with_name($modelName, $timezone);
2163
+	}
2164
+
2165
+
2166
+	/**
2167
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
+	 *
2169
+	 * @param string $model_classname
2170
+	 * @param null   $timezone
2171
+	 * @return EEM_Base
2172
+	 * @throws ReflectionException
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 */
2178
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
+	{
2180
+		$model_classname = str_replace('EEM_', '', $model_classname);
2181
+		$model = EE_Registry::instance()->load_model($model_classname);
2182
+		$model->set_timezone($timezone);
2183
+		return $model;
2184
+	}
2185
+
2186
+
2187
+	/**
2188
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2189
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2190
+	 *
2191
+	 * @param null $model_name
2192
+	 * @return string like EEM_Attendee
2193
+	 */
2194
+	private static function _get_model_classname($model_name = null)
2195
+	{
2196
+		if (strpos($model_name, 'EE_') === 0) {
2197
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
+		} else {
2199
+			$model_classname = 'EEM_' . $model_name;
2200
+		}
2201
+		return $model_classname;
2202
+	}
2203
+
2204
+
2205
+	/**
2206
+	 * returns the name of the primary key attribute
2207
+	 *
2208
+	 * @param null $classname
2209
+	 * @throws ReflectionException
2210
+	 * @throws InvalidArgumentException
2211
+	 * @throws InvalidInterfaceException
2212
+	 * @throws InvalidDataTypeException
2213
+	 * @throws EE_Error
2214
+	 * @return string
2215
+	 */
2216
+	protected static function _get_primary_key_name($classname = null)
2217
+	{
2218
+		if (! $classname) {
2219
+			throw new EE_Error(
2220
+				sprintf(
2221
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
+					$classname
2223
+				)
2224
+			);
2225
+		}
2226
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
+	}
2228
+
2229
+
2230
+	/**
2231
+	 * Gets the value of the primary key.
2232
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
+	 *
2236
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
+	 * @throws ReflectionException
2238
+	 * @throws InvalidArgumentException
2239
+	 * @throws InvalidInterfaceException
2240
+	 * @throws InvalidDataTypeException
2241
+	 * @throws EE_Error
2242
+	 */
2243
+	public function ID()
2244
+	{
2245
+		$model = $this->get_model();
2246
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2247
+		if ($model->has_primary_key_field()) {
2248
+			return $this->_fields[ $model->primary_key_name() ];
2249
+		}
2250
+		return $model->get_index_primary_key_string($this->_fields);
2251
+	}
2252
+
2253
+
2254
+	/**
2255
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
+	 *
2259
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
+	 * @param string $relationName                     eg 'Events','Question',etc.
2261
+	 *                                                 an attendee to a group, you also want to specify which role they
2262
+	 *                                                 will have in that group. So you would use this parameter to
2263
+	 *                                                 specify array('role-column-name'=>'role-id')
2264
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
+	 *                                                 allow you to further constrict the relation to being added.
2266
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2267
+	 *                                                 column on the JOIN table and currently only the HABTM models
2268
+	 *                                                 accept these additional conditions.  Also remember that if an
2269
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
+	 *                                                 NEW row is created in the join table.
2271
+	 * @param null   $cache_id
2272
+	 * @throws ReflectionException
2273
+	 * @throws InvalidArgumentException
2274
+	 * @throws InvalidInterfaceException
2275
+	 * @throws InvalidDataTypeException
2276
+	 * @throws EE_Error
2277
+	 * @return EE_Base_Class the object the relation was added to
2278
+	 */
2279
+	public function _add_relation_to(
2280
+		$otherObjectModelObjectOrID,
2281
+		$relationName,
2282
+		$extra_join_model_fields_n_values = array(),
2283
+		$cache_id = null
2284
+	) {
2285
+		$model = $this->get_model();
2286
+		// if this thing exists in the DB, save the relation to the DB
2287
+		if ($this->ID()) {
2288
+			$otherObject = $model->add_relationship_to(
2289
+				$this,
2290
+				$otherObjectModelObjectOrID,
2291
+				$relationName,
2292
+				$extra_join_model_fields_n_values
2293
+			);
2294
+			// clear cache so future get_many_related and get_first_related() return new results.
2295
+			$this->clear_cache($relationName, $otherObject, true);
2296
+			if ($otherObject instanceof EE_Base_Class) {
2297
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2298
+			}
2299
+		} else {
2300
+			// this thing doesn't exist in the DB,  so just cache it
2301
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
+				throw new EE_Error(
2303
+					sprintf(
2304
+						esc_html__(
2305
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2306
+							'event_espresso'
2307
+						),
2308
+						$otherObjectModelObjectOrID,
2309
+						get_class($this)
2310
+					)
2311
+				);
2312
+			}
2313
+			$otherObject = $otherObjectModelObjectOrID;
2314
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
+		}
2316
+		if ($otherObject instanceof EE_Base_Class) {
2317
+			// fix the reciprocal relation too
2318
+			if ($otherObject->ID()) {
2319
+				// its saved so assumed relations exist in the DB, so we can just
2320
+				// clear the cache so future queries use the updated info in the DB
2321
+				$otherObject->clear_cache(
2322
+					$model->get_this_model_name(),
2323
+					null,
2324
+					true
2325
+				);
2326
+			} else {
2327
+				// it's not saved, so it caches relations like this
2328
+				$otherObject->cache($model->get_this_model_name(), $this);
2329
+			}
2330
+		}
2331
+		return $otherObject;
2332
+	}
2333
+
2334
+
2335
+	/**
2336
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
+	 * from the cache
2340
+	 *
2341
+	 * @param mixed  $otherObjectModelObjectOrID
2342
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
+	 *                to the DB yet
2344
+	 * @param string $relationName
2345
+	 * @param array  $where_query
2346
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
+	 *                deleted.
2351
+	 * @return EE_Base_Class the relation was removed from
2352
+	 * @throws ReflectionException
2353
+	 * @throws InvalidArgumentException
2354
+	 * @throws InvalidInterfaceException
2355
+	 * @throws InvalidDataTypeException
2356
+	 * @throws EE_Error
2357
+	 */
2358
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
+	{
2360
+		if ($this->ID()) {
2361
+			// if this exists in the DB, save the relation change to the DB too
2362
+			$otherObject = $this->get_model()->remove_relationship_to(
2363
+				$this,
2364
+				$otherObjectModelObjectOrID,
2365
+				$relationName,
2366
+				$where_query
2367
+			);
2368
+			$this->clear_cache(
2369
+				$relationName,
2370
+				$otherObject
2371
+			);
2372
+		} else {
2373
+			// this doesn't exist in the DB, just remove it from the cache
2374
+			$otherObject = $this->clear_cache(
2375
+				$relationName,
2376
+				$otherObjectModelObjectOrID
2377
+			);
2378
+		}
2379
+		if ($otherObject instanceof EE_Base_Class) {
2380
+			$otherObject->clear_cache(
2381
+				$this->get_model()->get_this_model_name(),
2382
+				$this
2383
+			);
2384
+		}
2385
+		return $otherObject;
2386
+	}
2387
+
2388
+
2389
+	/**
2390
+	 * Removes ALL the related things for the $relationName.
2391
+	 *
2392
+	 * @param string $relationName
2393
+	 * @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
2394
+	 * @return EE_Base_Class
2395
+	 * @throws ReflectionException
2396
+	 * @throws InvalidArgumentException
2397
+	 * @throws InvalidInterfaceException
2398
+	 * @throws InvalidDataTypeException
2399
+	 * @throws EE_Error
2400
+	 */
2401
+	public function _remove_relations($relationName, $where_query_params = array())
2402
+	{
2403
+		if ($this->ID()) {
2404
+			// if this exists in the DB, save the relation change to the DB too
2405
+			$otherObjects = $this->get_model()->remove_relations(
2406
+				$this,
2407
+				$relationName,
2408
+				$where_query_params
2409
+			);
2410
+			$this->clear_cache(
2411
+				$relationName,
2412
+				null,
2413
+				true
2414
+			);
2415
+		} else {
2416
+			// this doesn't exist in the DB, just remove it from the cache
2417
+			$otherObjects = $this->clear_cache(
2418
+				$relationName,
2419
+				null,
2420
+				true
2421
+			);
2422
+		}
2423
+		if (is_array($otherObjects)) {
2424
+			foreach ($otherObjects as $otherObject) {
2425
+				$otherObject->clear_cache(
2426
+					$this->get_model()->get_this_model_name(),
2427
+					$this
2428
+				);
2429
+			}
2430
+		}
2431
+		return $otherObjects;
2432
+	}
2433
+
2434
+
2435
+	/**
2436
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2437
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
+	 * because we want to get even deleted items etc.
2440
+	 *
2441
+	 * @param string $relationName key in the model's _model_relations array
2442
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
+	 *                             results if you want IDs
2446
+	 * @throws ReflectionException
2447
+	 * @throws InvalidArgumentException
2448
+	 * @throws InvalidInterfaceException
2449
+	 * @throws InvalidDataTypeException
2450
+	 * @throws EE_Error
2451
+	 */
2452
+	public function get_many_related($relationName, $query_params = array())
2453
+	{
2454
+		if ($this->ID()) {
2455
+			// this exists in the DB, so get the related things from either the cache or the DB
2456
+			// if there are query parameters, forget about caching the related model objects.
2457
+			if ($query_params) {
2458
+				$related_model_objects = $this->get_model()->get_all_related(
2459
+					$this,
2460
+					$relationName,
2461
+					$query_params
2462
+				);
2463
+			} else {
2464
+				// did we already cache the result of this query?
2465
+				$cached_results = $this->get_all_from_cache($relationName);
2466
+				if (! $cached_results) {
2467
+					$related_model_objects = $this->get_model()->get_all_related(
2468
+						$this,
2469
+						$relationName,
2470
+						$query_params
2471
+					);
2472
+					// if no query parameters were passed, then we got all the related model objects
2473
+					// for that relation. We can cache them then.
2474
+					foreach ($related_model_objects as $related_model_object) {
2475
+						$this->cache($relationName, $related_model_object);
2476
+					}
2477
+				} else {
2478
+					$related_model_objects = $cached_results;
2479
+				}
2480
+			}
2481
+		} else {
2482
+			// this doesn't exist in the DB, so just get the related things from the cache
2483
+			$related_model_objects = $this->get_all_from_cache($relationName);
2484
+		}
2485
+		return $related_model_objects;
2486
+	}
2487
+
2488
+
2489
+	/**
2490
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
+	 * unless otherwise specified in the $query_params
2492
+	 *
2493
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2496
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
+	 *                               that by the setting $distinct to TRUE;
2498
+	 * @return int
2499
+	 * @throws ReflectionException
2500
+	 * @throws InvalidArgumentException
2501
+	 * @throws InvalidInterfaceException
2502
+	 * @throws InvalidDataTypeException
2503
+	 * @throws EE_Error
2504
+	 */
2505
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
+	{
2507
+		return $this->get_model()->count_related(
2508
+			$this,
2509
+			$relation_name,
2510
+			$query_params,
2511
+			$field_to_count,
2512
+			$distinct
2513
+		);
2514
+	}
2515
+
2516
+
2517
+	/**
2518
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
+	 *
2521
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2522
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
+	 * @param string $field_to_sum  name of field to count by.
2524
+	 *                              By default, uses primary key
2525
+	 *                              (which doesn't make much sense, so you should probably change it)
2526
+	 * @return int
2527
+	 * @throws ReflectionException
2528
+	 * @throws InvalidArgumentException
2529
+	 * @throws InvalidInterfaceException
2530
+	 * @throws InvalidDataTypeException
2531
+	 * @throws EE_Error
2532
+	 */
2533
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
+	{
2535
+		return $this->get_model()->sum_related(
2536
+			$this,
2537
+			$relation_name,
2538
+			$query_params,
2539
+			$field_to_sum
2540
+		);
2541
+	}
2542
+
2543
+
2544
+	/**
2545
+	 * Gets the first (ie, one) related model object of the specified type.
2546
+	 *
2547
+	 * @param string $relationName key in the model's _model_relations array
2548
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
+	 * @return EE_Base_Class (not an array, a single object)
2550
+	 * @throws ReflectionException
2551
+	 * @throws InvalidArgumentException
2552
+	 * @throws InvalidInterfaceException
2553
+	 * @throws InvalidDataTypeException
2554
+	 * @throws EE_Error
2555
+	 */
2556
+	public function get_first_related($relationName, $query_params = array())
2557
+	{
2558
+		$model = $this->get_model();
2559
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
+			// if they've provided some query parameters, don't bother trying to cache the result
2561
+			// also make sure we're not caching the result of get_first_related
2562
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2563
+			if (
2564
+				$query_params
2565
+				|| ! $model->related_settings_for($relationName)
2566
+					 instanceof
2567
+					 EE_Belongs_To_Relation
2568
+			) {
2569
+				$related_model_object = $model->get_first_related(
2570
+					$this,
2571
+					$relationName,
2572
+					$query_params
2573
+				);
2574
+			} else {
2575
+				// first, check if we've already cached the result of this query
2576
+				$cached_result = $this->get_one_from_cache($relationName);
2577
+				if (! $cached_result) {
2578
+					$related_model_object = $model->get_first_related(
2579
+						$this,
2580
+						$relationName,
2581
+						$query_params
2582
+					);
2583
+					$this->cache($relationName, $related_model_object);
2584
+				} else {
2585
+					$related_model_object = $cached_result;
2586
+				}
2587
+			}
2588
+		} else {
2589
+			$related_model_object = null;
2590
+			// this doesn't exist in the Db,
2591
+			// but maybe the relation is of type belongs to, and so the related thing might
2592
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
+				$related_model_object = $model->get_first_related(
2594
+					$this,
2595
+					$relationName,
2596
+					$query_params
2597
+				);
2598
+			}
2599
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
+			// just get what's cached on this object
2601
+			if (! $related_model_object) {
2602
+				$related_model_object = $this->get_one_from_cache($relationName);
2603
+			}
2604
+		}
2605
+		return $related_model_object;
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Does a delete on all related objects of type $relationName and removes
2611
+	 * the current model object's relation to them. If they can't be deleted (because
2612
+	 * of blocking related model objects) does nothing. If the related model objects are
2613
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2615
+	 *
2616
+	 * @param string $relationName
2617
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
+	 * @return int how many deleted
2619
+	 * @throws ReflectionException
2620
+	 * @throws InvalidArgumentException
2621
+	 * @throws InvalidInterfaceException
2622
+	 * @throws InvalidDataTypeException
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($relationName, $query_params = array())
2626
+	{
2627
+		if ($this->ID()) {
2628
+			$count = $this->get_model()->delete_related(
2629
+				$this,
2630
+				$relationName,
2631
+				$query_params
2632
+			);
2633
+		} else {
2634
+			$count = count($this->get_all_from_cache($relationName));
2635
+			$this->clear_cache($relationName, null, true);
2636
+		}
2637
+		return $count;
2638
+	}
2639
+
2640
+
2641
+	/**
2642
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
+	 * the current model object's relation to them. If they can't be deleted (because
2644
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2646
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
+	 *
2648
+	 * @param string $relationName
2649
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
+	 * @return int how many deleted (including those soft deleted)
2651
+	 * @throws ReflectionException
2652
+	 * @throws InvalidArgumentException
2653
+	 * @throws InvalidInterfaceException
2654
+	 * @throws InvalidDataTypeException
2655
+	 * @throws EE_Error
2656
+	 */
2657
+	public function delete_related_permanently($relationName, $query_params = array())
2658
+	{
2659
+		if ($this->ID()) {
2660
+			$count = $this->get_model()->delete_related_permanently(
2661
+				$this,
2662
+				$relationName,
2663
+				$query_params
2664
+			);
2665
+		} else {
2666
+			$count = count($this->get_all_from_cache($relationName));
2667
+		}
2668
+		$this->clear_cache($relationName, null, true);
2669
+		return $count;
2670
+	}
2671
+
2672
+
2673
+	/**
2674
+	 * is_set
2675
+	 * Just a simple utility function children can use for checking if property exists
2676
+	 *
2677
+	 * @access  public
2678
+	 * @param  string $field_name property to check
2679
+	 * @return bool                              TRUE if existing,FALSE if not.
2680
+	 */
2681
+	public function is_set($field_name)
2682
+	{
2683
+		return isset($this->_fields[ $field_name ]);
2684
+	}
2685
+
2686
+
2687
+	/**
2688
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
+	 * EE_Error exception if they don't
2690
+	 *
2691
+	 * @param  mixed (string|array) $properties properties to check
2692
+	 * @throws EE_Error
2693
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2694
+	 */
2695
+	protected function _property_exists($properties)
2696
+	{
2697
+		foreach ((array) $properties as $property_name) {
2698
+			// first make sure this property exists
2699
+			if (! $this->_fields[ $property_name ]) {
2700
+				throw new EE_Error(
2701
+					sprintf(
2702
+						esc_html__(
2703
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
+							'event_espresso'
2705
+						),
2706
+						$property_name
2707
+					)
2708
+				);
2709
+			}
2710
+		}
2711
+		return true;
2712
+	}
2713
+
2714
+
2715
+	/**
2716
+	 * This simply returns an array of model fields for this object
2717
+	 *
2718
+	 * @return array
2719
+	 * @throws ReflectionException
2720
+	 * @throws InvalidArgumentException
2721
+	 * @throws InvalidInterfaceException
2722
+	 * @throws InvalidDataTypeException
2723
+	 * @throws EE_Error
2724
+	 */
2725
+	public function model_field_array()
2726
+	{
2727
+		$fields = $this->get_model()->field_settings(false);
2728
+		$properties = array();
2729
+		// remove prepended underscore
2730
+		foreach ($fields as $field_name => $settings) {
2731
+			$properties[ $field_name ] = $this->get($field_name);
2732
+		}
2733
+		return $properties;
2734
+	}
2735
+
2736
+
2737
+	/**
2738
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2742
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2743
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
+	 * and accepts 2 arguments: the object on which the function was called,
2746
+	 * and an array of the original arguments passed to the function.
2747
+	 * Whatever their callback function returns will be returned by this function.
2748
+	 * Example: in functions.php (or in a plugin):
2749
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2750
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2751
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2752
+	 *          return $previousReturnValue.$returnString;
2753
+	 *      }
2754
+	 * require('EE_Answer.class.php');
2755
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2756
+	 *      ->my_callback('monkeys',100);
2757
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2758
+	 *
2759
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2760
+	 * @param array  $args       array of original arguments passed to the function
2761
+	 * @throws EE_Error
2762
+	 * @return mixed whatever the plugin which calls add_filter decides
2763
+	 */
2764
+	public function __call($methodName, $args)
2765
+	{
2766
+		$className = get_class($this);
2767
+		$tagName = "FHEE__{$className}__{$methodName}";
2768
+		if (! has_filter($tagName)) {
2769
+			throw new EE_Error(
2770
+				sprintf(
2771
+					esc_html__(
2772
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2773
+						'event_espresso'
2774
+					),
2775
+					$methodName,
2776
+					$className,
2777
+					$tagName
2778
+				)
2779
+			);
2780
+		}
2781
+		return apply_filters($tagName, null, $this, $args);
2782
+	}
2783
+
2784
+
2785
+	/**
2786
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2787
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2788
+	 *
2789
+	 * @param string $meta_key
2790
+	 * @param mixed  $meta_value
2791
+	 * @param mixed  $previous_value
2792
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2793
+	 *                  NOTE: if the values haven't changed, returns 0
2794
+	 * @throws InvalidArgumentException
2795
+	 * @throws InvalidInterfaceException
2796
+	 * @throws InvalidDataTypeException
2797
+	 * @throws EE_Error
2798
+	 * @throws ReflectionException
2799
+	 */
2800
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2801
+	{
2802
+		$query_params = array(
2803
+			array(
2804
+				'EXM_key'  => $meta_key,
2805
+				'OBJ_ID'   => $this->ID(),
2806
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2807
+			),
2808
+		);
2809
+		if ($previous_value !== null) {
2810
+			$query_params[0]['EXM_value'] = $meta_value;
2811
+		}
2812
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2813
+		if (! $existing_rows_like_that) {
2814
+			return $this->add_extra_meta($meta_key, $meta_value);
2815
+		}
2816
+		foreach ($existing_rows_like_that as $existing_row) {
2817
+			$existing_row->save(array('EXM_value' => $meta_value));
2818
+		}
2819
+		return count($existing_rows_like_that);
2820
+	}
2821
+
2822
+
2823
+	/**
2824
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2825
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2826
+	 * extra meta row was entered, false if not
2827
+	 *
2828
+	 * @param string  $meta_key
2829
+	 * @param mixed   $meta_value
2830
+	 * @param boolean $unique
2831
+	 * @return boolean
2832
+	 * @throws InvalidArgumentException
2833
+	 * @throws InvalidInterfaceException
2834
+	 * @throws InvalidDataTypeException
2835
+	 * @throws EE_Error
2836
+	 * @throws ReflectionException
2837
+	 * @throws ReflectionException
2838
+	 */
2839
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2840
+	{
2841
+		if ($unique) {
2842
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2843
+				array(
2844
+					array(
2845
+						'EXM_key'  => $meta_key,
2846
+						'OBJ_ID'   => $this->ID(),
2847
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2848
+					),
2849
+				)
2850
+			);
2851
+			if ($existing_extra_meta) {
2852
+				return false;
2853
+			}
2854
+		}
2855
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2856
+			array(
2857
+				'EXM_key'   => $meta_key,
2858
+				'EXM_value' => $meta_value,
2859
+				'OBJ_ID'    => $this->ID(),
2860
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2861
+			)
2862
+		);
2863
+		$new_extra_meta->save();
2864
+		return true;
2865
+	}
2866
+
2867
+
2868
+	/**
2869
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2870
+	 * is specified, only deletes extra meta records with that value.
2871
+	 *
2872
+	 * @param string $meta_key
2873
+	 * @param mixed  $meta_value
2874
+	 * @return int number of extra meta rows deleted
2875
+	 * @throws InvalidArgumentException
2876
+	 * @throws InvalidInterfaceException
2877
+	 * @throws InvalidDataTypeException
2878
+	 * @throws EE_Error
2879
+	 * @throws ReflectionException
2880
+	 */
2881
+	public function delete_extra_meta($meta_key, $meta_value = null)
2882
+	{
2883
+		$query_params = array(
2884
+			array(
2885
+				'EXM_key'  => $meta_key,
2886
+				'OBJ_ID'   => $this->ID(),
2887
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2888
+			),
2889
+		);
2890
+		if ($meta_value !== null) {
2891
+			$query_params[0]['EXM_value'] = $meta_value;
2892
+		}
2893
+		return EEM_Extra_Meta::instance()->delete($query_params);
2894
+	}
2895
+
2896
+
2897
+	/**
2898
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2899
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2900
+	 * You can specify $default is case you haven't found the extra meta
2901
+	 *
2902
+	 * @param string  $meta_key
2903
+	 * @param boolean $single
2904
+	 * @param mixed   $default if we don't find anything, what should we return?
2905
+	 * @return mixed single value if $single; array if ! $single
2906
+	 * @throws ReflectionException
2907
+	 * @throws InvalidArgumentException
2908
+	 * @throws InvalidInterfaceException
2909
+	 * @throws InvalidDataTypeException
2910
+	 * @throws EE_Error
2911
+	 */
2912
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2913
+	{
2914
+		if ($single) {
2915
+			$result = $this->get_first_related(
2916
+				'Extra_Meta',
2917
+				array(array('EXM_key' => $meta_key))
2918
+			);
2919
+			if ($result instanceof EE_Extra_Meta) {
2920
+				return $result->value();
2921
+			}
2922
+		} else {
2923
+			$results = $this->get_many_related(
2924
+				'Extra_Meta',
2925
+				array(array('EXM_key' => $meta_key))
2926
+			);
2927
+			if ($results) {
2928
+				$values = array();
2929
+				foreach ($results as $result) {
2930
+					if ($result instanceof EE_Extra_Meta) {
2931
+						$values[ $result->ID() ] = $result->value();
2932
+					}
2933
+				}
2934
+				return $values;
2935
+			}
2936
+		}
2937
+		// if nothing discovered yet return default.
2938
+		return apply_filters(
2939
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2940
+			$default,
2941
+			$meta_key,
2942
+			$single,
2943
+			$this
2944
+		);
2945
+	}
2946
+
2947
+
2948
+	/**
2949
+	 * Returns a simple array of all the extra meta associated with this model object.
2950
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2951
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2952
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2953
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2954
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2955
+	 * finally the extra meta's value as each sub-value. (eg
2956
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2957
+	 *
2958
+	 * @param boolean $one_of_each_key
2959
+	 * @return array
2960
+	 * @throws ReflectionException
2961
+	 * @throws InvalidArgumentException
2962
+	 * @throws InvalidInterfaceException
2963
+	 * @throws InvalidDataTypeException
2964
+	 * @throws EE_Error
2965
+	 */
2966
+	public function all_extra_meta_array($one_of_each_key = true)
2967
+	{
2968
+		$return_array = array();
2969
+		if ($one_of_each_key) {
2970
+			$extra_meta_objs = $this->get_many_related(
2971
+				'Extra_Meta',
2972
+				array('group_by' => 'EXM_key')
2973
+			);
2974
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2975
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2976
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2977
+				}
2978
+			}
2979
+		} else {
2980
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2981
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2982
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2983
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2984
+						$return_array[ $extra_meta_obj->key() ] = array();
2985
+					}
2986
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2987
+				}
2988
+			}
2989
+		}
2990
+		return $return_array;
2991
+	}
2992
+
2993
+
2994
+	/**
2995
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2996
+	 *
2997
+	 * @return string
2998
+	 * @throws ReflectionException
2999
+	 * @throws InvalidArgumentException
3000
+	 * @throws InvalidInterfaceException
3001
+	 * @throws InvalidDataTypeException
3002
+	 * @throws EE_Error
3003
+	 */
3004
+	public function name()
3005
+	{
3006
+		// find a field that's not a text field
3007
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3008
+		if ($field_we_can_use) {
3009
+			return $this->get($field_we_can_use->get_name());
3010
+		}
3011
+		$first_few_properties = $this->model_field_array();
3012
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3013
+		$name_parts = array();
3014
+		foreach ($first_few_properties as $name => $value) {
3015
+			$name_parts[] = "$name:$value";
3016
+		}
3017
+		return implode(',', $name_parts);
3018
+	}
3019
+
3020
+
3021
+	/**
3022
+	 * in_entity_map
3023
+	 * Checks if this model object has been proven to already be in the entity map
3024
+	 *
3025
+	 * @return boolean
3026
+	 * @throws ReflectionException
3027
+	 * @throws InvalidArgumentException
3028
+	 * @throws InvalidInterfaceException
3029
+	 * @throws InvalidDataTypeException
3030
+	 * @throws EE_Error
3031
+	 */
3032
+	public function in_entity_map()
3033
+	{
3034
+		// well, if we looked, did we find it in the entity map?
3035
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3036
+	}
3037
+
3038
+
3039
+	/**
3040
+	 * refresh_from_db
3041
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3042
+	 *
3043
+	 * @throws ReflectionException
3044
+	 * @throws InvalidArgumentException
3045
+	 * @throws InvalidInterfaceException
3046
+	 * @throws InvalidDataTypeException
3047
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3048
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3049
+	 */
3050
+	public function refresh_from_db()
3051
+	{
3052
+		if ($this->ID() && $this->in_entity_map()) {
3053
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3054
+		} else {
3055
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3056
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3057
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3058
+			// absolutely nothing in it for this ID
3059
+			if (WP_DEBUG) {
3060
+				throw new EE_Error(
3061
+					sprintf(
3062
+						esc_html__(
3063
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3064
+							'event_espresso'
3065
+						),
3066
+						$this->ID(),
3067
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3068
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3069
+					)
3070
+				);
3071
+			}
3072
+		}
3073
+	}
3074
+
3075
+
3076
+	/**
3077
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3078
+	 *
3079
+	 * @since 4.9.80.p
3080
+	 * @param EE_Model_Field_Base[] $fields
3081
+	 * @param string $new_value_sql
3082
+	 *      example: 'column_name=123',
3083
+	 *      or 'column_name=column_name+1',
3084
+	 *      or 'column_name= CASE
3085
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3086
+	 *          THEN `column_name` + 5
3087
+	 *          ELSE `column_name`
3088
+	 *      END'
3089
+	 *      Also updates $field on this model object with the latest value from the database.
3090
+	 * @return bool
3091
+	 * @throws EE_Error
3092
+	 * @throws InvalidArgumentException
3093
+	 * @throws InvalidDataTypeException
3094
+	 * @throws InvalidInterfaceException
3095
+	 * @throws ReflectionException
3096
+	 */
3097
+	protected function updateFieldsInDB($fields, $new_value_sql)
3098
+	{
3099
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3100
+		// if it wasn't even there to start off.
3101
+		if (! $this->ID()) {
3102
+			$this->save();
3103
+		}
3104
+		global $wpdb;
3105
+		if (empty($fields)) {
3106
+			throw new InvalidArgumentException(
3107
+				esc_html__(
3108
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3109
+					'event_espresso'
3110
+				)
3111
+			);
3112
+		}
3113
+		$first_field = reset($fields);
3114
+		$table_alias = $first_field->get_table_alias();
3115
+		foreach ($fields as $field) {
3116
+			if ($table_alias !== $field->get_table_alias()) {
3117
+				throw new InvalidArgumentException(
3118
+					sprintf(
3119
+						esc_html__(
3120
+							// @codingStandardsIgnoreStart
3121
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3122
+							// @codingStandardsIgnoreEnd
3123
+							'event_espresso'
3124
+						),
3125
+						$table_alias,
3126
+						$field->get_table_alias()
3127
+					)
3128
+				);
3129
+			}
3130
+		}
3131
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3132
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3133
+		$table_pk_value = $this->ID();
3134
+		$table_name = $table_obj->get_table_name();
3135
+		if ($table_obj instanceof EE_Secondary_Table) {
3136
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3137
+		} else {
3138
+			$table_pk_field_name = $table_obj->get_pk_column();
3139
+		}
3140
+
3141
+		$query =
3142
+			"UPDATE `{$table_name}`
3143 3143
             SET "
3144
-            . $new_value_sql
3145
-            . $wpdb->prepare(
3146
-                "
3144
+			. $new_value_sql
3145
+			. $wpdb->prepare(
3146
+				"
3147 3147
             WHERE `{$table_pk_field_name}` = %d;",
3148
-                $table_pk_value
3149
-            );
3150
-        $result = $wpdb->query($query);
3151
-        foreach ($fields as $field) {
3152
-            // If it was successful, we'd like to know the new value.
3153
-            // If it failed, we'd also like to know the new value.
3154
-            $new_value = $this->get_model()->get_var(
3155
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3156
-                    $this->get_model()->get_index_primary_key_string(
3157
-                        $this->model_field_array()
3158
-                    ),
3159
-                    array(
3160
-                        'default_where_conditions' => 'minimum',
3161
-                    )
3162
-                ),
3163
-                $field->get_name()
3164
-            );
3165
-            $this->set_from_db(
3166
-                $field->get_name(),
3167
-                $new_value
3168
-            );
3169
-        }
3170
-        return (bool) $result;
3171
-    }
3172
-
3173
-
3174
-    /**
3175
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3176
-     * Does not allow negative values, however.
3177
-     *
3178
-     * @since 4.9.80.p
3179
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3180
-     *                                   (positive or negative). One important gotcha: all these values must be
3181
-     *                                   on the same table (eg don't pass in one field for the posts table and
3182
-     *                                   another for the event meta table.)
3183
-     * @return bool
3184
-     * @throws EE_Error
3185
-     * @throws InvalidArgumentException
3186
-     * @throws InvalidDataTypeException
3187
-     * @throws InvalidInterfaceException
3188
-     * @throws ReflectionException
3189
-     */
3190
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3191
-    {
3192
-        global $wpdb;
3193
-        if (empty($fields_n_quantities)) {
3194
-            // No fields to update? Well sure, we updated them to that value just fine.
3195
-            return true;
3196
-        }
3197
-        $fields = [];
3198
-        $set_sql_statements = [];
3199
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3200
-            $field = $this->get_model()->field_settings_for($field_name, true);
3201
-            $fields[] = $field;
3202
-            $column_name = $field->get_table_column();
3203
-
3204
-            $abs_qty = absint($quantity);
3205
-            if ($quantity > 0) {
3206
-                // don't let the value be negative as often these fields are unsigned
3207
-                $set_sql_statements[] = $wpdb->prepare(
3208
-                    "`{$column_name}` = `{$column_name}` + %d",
3209
-                    $abs_qty
3210
-                );
3211
-            } else {
3212
-                $set_sql_statements[] = $wpdb->prepare(
3213
-                    "`{$column_name}` = CASE
3148
+				$table_pk_value
3149
+			);
3150
+		$result = $wpdb->query($query);
3151
+		foreach ($fields as $field) {
3152
+			// If it was successful, we'd like to know the new value.
3153
+			// If it failed, we'd also like to know the new value.
3154
+			$new_value = $this->get_model()->get_var(
3155
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3156
+					$this->get_model()->get_index_primary_key_string(
3157
+						$this->model_field_array()
3158
+					),
3159
+					array(
3160
+						'default_where_conditions' => 'minimum',
3161
+					)
3162
+				),
3163
+				$field->get_name()
3164
+			);
3165
+			$this->set_from_db(
3166
+				$field->get_name(),
3167
+				$new_value
3168
+			);
3169
+		}
3170
+		return (bool) $result;
3171
+	}
3172
+
3173
+
3174
+	/**
3175
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3176
+	 * Does not allow negative values, however.
3177
+	 *
3178
+	 * @since 4.9.80.p
3179
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3180
+	 *                                   (positive or negative). One important gotcha: all these values must be
3181
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3182
+	 *                                   another for the event meta table.)
3183
+	 * @return bool
3184
+	 * @throws EE_Error
3185
+	 * @throws InvalidArgumentException
3186
+	 * @throws InvalidDataTypeException
3187
+	 * @throws InvalidInterfaceException
3188
+	 * @throws ReflectionException
3189
+	 */
3190
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3191
+	{
3192
+		global $wpdb;
3193
+		if (empty($fields_n_quantities)) {
3194
+			// No fields to update? Well sure, we updated them to that value just fine.
3195
+			return true;
3196
+		}
3197
+		$fields = [];
3198
+		$set_sql_statements = [];
3199
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3200
+			$field = $this->get_model()->field_settings_for($field_name, true);
3201
+			$fields[] = $field;
3202
+			$column_name = $field->get_table_column();
3203
+
3204
+			$abs_qty = absint($quantity);
3205
+			if ($quantity > 0) {
3206
+				// don't let the value be negative as often these fields are unsigned
3207
+				$set_sql_statements[] = $wpdb->prepare(
3208
+					"`{$column_name}` = `{$column_name}` + %d",
3209
+					$abs_qty
3210
+				);
3211
+			} else {
3212
+				$set_sql_statements[] = $wpdb->prepare(
3213
+					"`{$column_name}` = CASE
3214 3214
                        WHEN (`{$column_name}` >= %d)
3215 3215
                        THEN `{$column_name}` - %d
3216 3216
                        ELSE 0
3217 3217
                     END",
3218
-                    $abs_qty,
3219
-                    $abs_qty
3220
-                );
3221
-            }
3222
-        }
3223
-        return $this->updateFieldsInDB(
3224
-            $fields,
3225
-            implode(', ', $set_sql_statements)
3226
-        );
3227
-    }
3228
-
3229
-
3230
-    /**
3231
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3232
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3233
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3234
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3235
-     * Otherwise returns false.
3236
-     *
3237
-     * @since 4.9.80.p
3238
-     * @param string $field_name_to_bump
3239
-     * @param string $field_name_affecting_total
3240
-     * @param string $limit_field_name
3241
-     * @param int    $quantity
3242
-     * @return bool
3243
-     * @throws EE_Error
3244
-     * @throws InvalidArgumentException
3245
-     * @throws InvalidDataTypeException
3246
-     * @throws InvalidInterfaceException
3247
-     * @throws ReflectionException
3248
-     */
3249
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3250
-    {
3251
-        global $wpdb;
3252
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3253
-        $column_name = $field->get_table_column();
3254
-
3255
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3256
-        $column_affecting_total = $field_affecting_total->get_table_column();
3257
-
3258
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3259
-        $limiting_column = $limiting_field->get_table_column();
3260
-        return $this->updateFieldsInDB(
3261
-            [$field],
3262
-            $wpdb->prepare(
3263
-                "`{$column_name}` =
3218
+					$abs_qty,
3219
+					$abs_qty
3220
+				);
3221
+			}
3222
+		}
3223
+		return $this->updateFieldsInDB(
3224
+			$fields,
3225
+			implode(', ', $set_sql_statements)
3226
+		);
3227
+	}
3228
+
3229
+
3230
+	/**
3231
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3232
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3233
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3234
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3235
+	 * Otherwise returns false.
3236
+	 *
3237
+	 * @since 4.9.80.p
3238
+	 * @param string $field_name_to_bump
3239
+	 * @param string $field_name_affecting_total
3240
+	 * @param string $limit_field_name
3241
+	 * @param int    $quantity
3242
+	 * @return bool
3243
+	 * @throws EE_Error
3244
+	 * @throws InvalidArgumentException
3245
+	 * @throws InvalidDataTypeException
3246
+	 * @throws InvalidInterfaceException
3247
+	 * @throws ReflectionException
3248
+	 */
3249
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3250
+	{
3251
+		global $wpdb;
3252
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3253
+		$column_name = $field->get_table_column();
3254
+
3255
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3256
+		$column_affecting_total = $field_affecting_total->get_table_column();
3257
+
3258
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3259
+		$limiting_column = $limiting_field->get_table_column();
3260
+		return $this->updateFieldsInDB(
3261
+			[$field],
3262
+			$wpdb->prepare(
3263
+				"`{$column_name}` =
3264 3264
             CASE
3265 3265
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3266 3266
                THEN `{$column_name}` + %d
3267 3267
                ELSE `{$column_name}`
3268 3268
             END",
3269
-                $quantity,
3270
-                EE_INF_IN_DB,
3271
-                $quantity
3272
-            )
3273
-        );
3274
-    }
3275
-
3276
-
3277
-    /**
3278
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3279
-     * (probably a bad assumption they have made, oh well)
3280
-     *
3281
-     * @return string
3282
-     */
3283
-    public function __toString()
3284
-    {
3285
-        try {
3286
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3287
-        } catch (Exception $e) {
3288
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3289
-            return '';
3290
-        }
3291
-    }
3292
-
3293
-
3294
-    /**
3295
-     * Clear related model objects if they're already in the DB, because otherwise when we
3296
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3297
-     * This means if we have made changes to those related model objects, and want to unserialize
3298
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3299
-     * Instead, those related model objects should be directly serialized and stored.
3300
-     * Eg, the following won't work:
3301
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3302
-     * $att = $reg->attendee();
3303
-     * $att->set( 'ATT_fname', 'Dirk' );
3304
-     * update_option( 'my_option', serialize( $reg ) );
3305
-     * //END REQUEST
3306
-     * //START NEXT REQUEST
3307
-     * $reg = get_option( 'my_option' );
3308
-     * $reg->attendee()->save();
3309
-     * And would need to be replace with:
3310
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3311
-     * $att = $reg->attendee();
3312
-     * $att->set( 'ATT_fname', 'Dirk' );
3313
-     * update_option( 'my_option', serialize( $reg ) );
3314
-     * //END REQUEST
3315
-     * //START NEXT REQUEST
3316
-     * $att = get_option( 'my_option' );
3317
-     * $att->save();
3318
-     *
3319
-     * @return array
3320
-     * @throws ReflectionException
3321
-     * @throws InvalidArgumentException
3322
-     * @throws InvalidInterfaceException
3323
-     * @throws InvalidDataTypeException
3324
-     * @throws EE_Error
3325
-     */
3326
-    public function __sleep()
3327
-    {
3328
-        $model = $this->get_model();
3329
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3330
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3331
-                $classname = 'EE_' . $model->get_this_model_name();
3332
-                if (
3333
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3334
-                    && $this->get_one_from_cache($relation_name)->ID()
3335
-                ) {
3336
-                    $this->clear_cache(
3337
-                        $relation_name,
3338
-                        $this->get_one_from_cache($relation_name)->ID()
3339
-                    );
3340
-                }
3341
-            }
3342
-        }
3343
-        $this->_props_n_values_provided_in_constructor = array();
3344
-        $properties_to_serialize = get_object_vars($this);
3345
-        // don't serialize the model. It's big and that risks recursion
3346
-        unset($properties_to_serialize['_model']);
3347
-        return array_keys($properties_to_serialize);
3348
-    }
3349
-
3350
-
3351
-    /**
3352
-     * restore _props_n_values_provided_in_constructor
3353
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3354
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3355
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3356
-     */
3357
-    public function __wakeup()
3358
-    {
3359
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3365
-     * distinct with the clone host instance are also cloned.
3366
-     */
3367
-    public function __clone()
3368
-    {
3369
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3370
-        foreach ($this->_fields as $field => $value) {
3371
-            if ($value instanceof DateTime) {
3372
-                $this->_fields[ $field ] = clone $value;
3373
-            }
3374
-        }
3375
-    }
3269
+				$quantity,
3270
+				EE_INF_IN_DB,
3271
+				$quantity
3272
+			)
3273
+		);
3274
+	}
3275
+
3276
+
3277
+	/**
3278
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3279
+	 * (probably a bad assumption they have made, oh well)
3280
+	 *
3281
+	 * @return string
3282
+	 */
3283
+	public function __toString()
3284
+	{
3285
+		try {
3286
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3287
+		} catch (Exception $e) {
3288
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3289
+			return '';
3290
+		}
3291
+	}
3292
+
3293
+
3294
+	/**
3295
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3296
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3297
+	 * This means if we have made changes to those related model objects, and want to unserialize
3298
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3299
+	 * Instead, those related model objects should be directly serialized and stored.
3300
+	 * Eg, the following won't work:
3301
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3302
+	 * $att = $reg->attendee();
3303
+	 * $att->set( 'ATT_fname', 'Dirk' );
3304
+	 * update_option( 'my_option', serialize( $reg ) );
3305
+	 * //END REQUEST
3306
+	 * //START NEXT REQUEST
3307
+	 * $reg = get_option( 'my_option' );
3308
+	 * $reg->attendee()->save();
3309
+	 * And would need to be replace with:
3310
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3311
+	 * $att = $reg->attendee();
3312
+	 * $att->set( 'ATT_fname', 'Dirk' );
3313
+	 * update_option( 'my_option', serialize( $reg ) );
3314
+	 * //END REQUEST
3315
+	 * //START NEXT REQUEST
3316
+	 * $att = get_option( 'my_option' );
3317
+	 * $att->save();
3318
+	 *
3319
+	 * @return array
3320
+	 * @throws ReflectionException
3321
+	 * @throws InvalidArgumentException
3322
+	 * @throws InvalidInterfaceException
3323
+	 * @throws InvalidDataTypeException
3324
+	 * @throws EE_Error
3325
+	 */
3326
+	public function __sleep()
3327
+	{
3328
+		$model = $this->get_model();
3329
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3330
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3331
+				$classname = 'EE_' . $model->get_this_model_name();
3332
+				if (
3333
+					$this->get_one_from_cache($relation_name) instanceof $classname
3334
+					&& $this->get_one_from_cache($relation_name)->ID()
3335
+				) {
3336
+					$this->clear_cache(
3337
+						$relation_name,
3338
+						$this->get_one_from_cache($relation_name)->ID()
3339
+					);
3340
+				}
3341
+			}
3342
+		}
3343
+		$this->_props_n_values_provided_in_constructor = array();
3344
+		$properties_to_serialize = get_object_vars($this);
3345
+		// don't serialize the model. It's big and that risks recursion
3346
+		unset($properties_to_serialize['_model']);
3347
+		return array_keys($properties_to_serialize);
3348
+	}
3349
+
3350
+
3351
+	/**
3352
+	 * restore _props_n_values_provided_in_constructor
3353
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3354
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3355
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3356
+	 */
3357
+	public function __wakeup()
3358
+	{
3359
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3365
+	 * distinct with the clone host instance are also cloned.
3366
+	 */
3367
+	public function __clone()
3368
+	{
3369
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3370
+		foreach ($this->_fields as $field => $value) {
3371
+			if ($value instanceof DateTime) {
3372
+				$this->_fields[ $field ] = clone $value;
3373
+			}
3374
+		}
3375
+	}
3376 3376
 }
Please login to merge, or discard this patch.
core/entities/models/JsonModelSchema.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -25,255 +25,255 @@
 block discarded – undo
25 25
 class JsonModelSchema
26 26
 {
27 27
 
28
-    /**
29
-     * @var EEM_Base
30
-     */
31
-    protected $model;
28
+	/**
29
+	 * @var EEM_Base
30
+	 */
31
+	protected $model;
32 32
 
33
-    /**
34
-     * @var CalculatedModelFields
35
-     */
36
-    protected $fields_calculator;
33
+	/**
34
+	 * @var CalculatedModelFields
35
+	 */
36
+	protected $fields_calculator;
37 37
 
38 38
 
39
-    /**
40
-     * JsonModelSchema constructor.
41
-     *
42
-     * @param EEM_Base              $model
43
-     * @param CalculatedModelFields $fields_calculator
44
-     */
45
-    public function __construct(EEM_Base $model, CalculatedModelFields $fields_calculator)
46
-    {
47
-        $this->model = $model;
48
-        $this->fields_calculator = $fields_calculator;
49
-    }
39
+	/**
40
+	 * JsonModelSchema constructor.
41
+	 *
42
+	 * @param EEM_Base              $model
43
+	 * @param CalculatedModelFields $fields_calculator
44
+	 */
45
+	public function __construct(EEM_Base $model, CalculatedModelFields $fields_calculator)
46
+	{
47
+		$this->model = $model;
48
+		$this->fields_calculator = $fields_calculator;
49
+	}
50 50
 
51 51
 
52
-    /**
53
-     * Return the schema for a given model from a given model.
54
-     *
55
-     * @return array
56
-     */
57
-    public function getModelSchema()
58
-    {
59
-        return $this->getModelSchemaForRelations(
60
-            $this->model->relation_settings(),
61
-            $this->getModelSchemaForFields(
62
-                $this->model->field_settings(),
63
-                $this->getInitialSchemaStructure()
64
-            )
65
-        );
66
-    }
52
+	/**
53
+	 * Return the schema for a given model from a given model.
54
+	 *
55
+	 * @return array
56
+	 */
57
+	public function getModelSchema()
58
+	{
59
+		return $this->getModelSchemaForRelations(
60
+			$this->model->relation_settings(),
61
+			$this->getModelSchemaForFields(
62
+				$this->model->field_settings(),
63
+				$this->getInitialSchemaStructure()
64
+			)
65
+		);
66
+	}
67 67
 
68 68
 
69
-    /**
70
-     * Get the schema for a given set of model fields.
71
-     *
72
-     * @param EE_Model_Field_Base[] $model_fields
73
-     * @param array                  $schema
74
-     * @return array
75
-     */
76
-    public function getModelSchemaForFields(array $model_fields, array $schema)
77
-    {
78
-        foreach ($model_fields as $field => $model_field) {
79
-            if (! $model_field instanceof EE_Model_Field_Base) {
80
-                continue;
81
-            }
82
-            $schema['properties'][ $field ] = $model_field->getSchema();
69
+	/**
70
+	 * Get the schema for a given set of model fields.
71
+	 *
72
+	 * @param EE_Model_Field_Base[] $model_fields
73
+	 * @param array                  $schema
74
+	 * @return array
75
+	 */
76
+	public function getModelSchemaForFields(array $model_fields, array $schema)
77
+	{
78
+		foreach ($model_fields as $field => $model_field) {
79
+			if (! $model_field instanceof EE_Model_Field_Base) {
80
+				continue;
81
+			}
82
+			$schema['properties'][ $field ] = $model_field->getSchema();
83 83
 
84
-            // if this is a primary key field add the primary key item
85
-            if ($model_field instanceof EE_Primary_Key_Field_Base) {
86
-                $schema['properties'][ $field ]['primary_key'] = true;
87
-                if ($model_field instanceof EE_Primary_Key_Int_Field) {
88
-                    $schema['properties'][ $field ]['readonly'] = true;
89
-                }
90
-            }
84
+			// if this is a primary key field add the primary key item
85
+			if ($model_field instanceof EE_Primary_Key_Field_Base) {
86
+				$schema['properties'][ $field ]['primary_key'] = true;
87
+				if ($model_field instanceof EE_Primary_Key_Int_Field) {
88
+					$schema['properties'][ $field ]['readonly'] = true;
89
+				}
90
+			}
91 91
 
92
-            // if this is a foreign key field add the foreign key item
93
-            if ($model_field instanceof EE_Foreign_Key_Field_Base) {
94
-                $schema['properties'][ $field ]['foreign_key'] = array(
95
-                    'description' => esc_html__(
96
-                        'This is a foreign key the points to the given models.',
97
-                        'event_espresso'
98
-                    ),
99
-                    'type'        => 'array',
100
-                    'enum'        => $model_field->get_model_class_names_pointed_to(),
101
-                );
102
-            }
103
-        }
104
-        return $schema;
105
-    }
92
+			// if this is a foreign key field add the foreign key item
93
+			if ($model_field instanceof EE_Foreign_Key_Field_Base) {
94
+				$schema['properties'][ $field ]['foreign_key'] = array(
95
+					'description' => esc_html__(
96
+						'This is a foreign key the points to the given models.',
97
+						'event_espresso'
98
+					),
99
+					'type'        => 'array',
100
+					'enum'        => $model_field->get_model_class_names_pointed_to(),
101
+				);
102
+			}
103
+		}
104
+		return $schema;
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * Get the schema for a given set of model relations
110
-     *
111
-     * @param EE_Model_Relation_Base[] $relations_on_model
112
-     * @param array                    $schema
113
-     * @return array
114
-     */
115
-    public function getModelSchemaForRelations(array $relations_on_model, array $schema)
116
-    {
117
-        foreach ($relations_on_model as $model_name => $relation) {
118
-            if (! $relation instanceof EE_Model_Relation_Base) {
119
-                continue;
120
-            }
121
-            $model_name_for_schema = $relation instanceof EE_Belongs_To_Relation
122
-                ? strtolower($model_name)
123
-                : EEH_Inflector::pluralize_and_lower($model_name);
124
-            $schema['properties'][ $model_name_for_schema ] = $relation->getSchema();
125
-            $schema['properties'][ $model_name_for_schema ]['relation_model'] = $model_name;
108
+	/**
109
+	 * Get the schema for a given set of model relations
110
+	 *
111
+	 * @param EE_Model_Relation_Base[] $relations_on_model
112
+	 * @param array                    $schema
113
+	 * @return array
114
+	 */
115
+	public function getModelSchemaForRelations(array $relations_on_model, array $schema)
116
+	{
117
+		foreach ($relations_on_model as $model_name => $relation) {
118
+			if (! $relation instanceof EE_Model_Relation_Base) {
119
+				continue;
120
+			}
121
+			$model_name_for_schema = $relation instanceof EE_Belongs_To_Relation
122
+				? strtolower($model_name)
123
+				: EEH_Inflector::pluralize_and_lower($model_name);
124
+			$schema['properties'][ $model_name_for_schema ] = $relation->getSchema();
125
+			$schema['properties'][ $model_name_for_schema ]['relation_model'] = $model_name;
126 126
 
127
-            // links schema
128
-            $links_key = 'https://api.eventespresso.com/' . strtolower($model_name);
129
-            $schema['properties']['_links']['properties'][ $links_key ] = array(
130
-                'description' => esc_html__(
131
-                    'Array of objects describing the link(s) for this relation resource.',
132
-                    'event_espresso'
133
-                ),
134
-                'type' => 'array',
135
-                'readonly' => true,
136
-                'items' => array(
137
-                    'type' => 'object',
138
-                    'properties' => array(
139
-                        'href' => array(
140
-                            'type' => 'string',
141
-                            'description' => sprintf(
142
-                                // translators: placeholder is the model name for the relation.
143
-                                esc_html__(
144
-                                    'The link to the resource for the %s relation(s) to this entity',
145
-                                    'event_espresso'
146
-                                ),
147
-                                $model_name
148
-                            ),
149
-                        ),
150
-                        'single' => array(
151
-                            'type' => 'boolean',
152
-                            'description' => sprintf(
153
-                                // translators: placeholder is the model name for the relation.
154
-                                esc_html__(
155
-                                    'Whether or not there is only a single %s relation to this entity',
156
-                                    'event_espresso'
157
-                                ),
158
-                                $model_name
159
-                            ),
160
-                        ),
161
-                    ),
162
-                    'additionalProperties' => false
163
-                ),
164
-            );
165
-        }
166
-        return $schema;
167
-    }
127
+			// links schema
128
+			$links_key = 'https://api.eventespresso.com/' . strtolower($model_name);
129
+			$schema['properties']['_links']['properties'][ $links_key ] = array(
130
+				'description' => esc_html__(
131
+					'Array of objects describing the link(s) for this relation resource.',
132
+					'event_espresso'
133
+				),
134
+				'type' => 'array',
135
+				'readonly' => true,
136
+				'items' => array(
137
+					'type' => 'object',
138
+					'properties' => array(
139
+						'href' => array(
140
+							'type' => 'string',
141
+							'description' => sprintf(
142
+								// translators: placeholder is the model name for the relation.
143
+								esc_html__(
144
+									'The link to the resource for the %s relation(s) to this entity',
145
+									'event_espresso'
146
+								),
147
+								$model_name
148
+							),
149
+						),
150
+						'single' => array(
151
+							'type' => 'boolean',
152
+							'description' => sprintf(
153
+								// translators: placeholder is the model name for the relation.
154
+								esc_html__(
155
+									'Whether or not there is only a single %s relation to this entity',
156
+									'event_espresso'
157
+								),
158
+								$model_name
159
+							),
160
+						),
161
+					),
162
+					'additionalProperties' => false
163
+				),
164
+			);
165
+		}
166
+		return $schema;
167
+	}
168 168
 
169 169
 
170
-    /**
171
-     * Outputs the schema header for a model.
172
-     *
173
-     * @return array
174
-     */
175
-    public function getInitialSchemaStructure()
176
-    {
177
-        return array(
178
-            '$schema'    => 'http://json-schema.org/draft-04/schema#',
179
-            'title'      => $this->model->get_this_model_name(),
180
-            'type'       => 'object',
181
-            'properties' => array(
182
-                'link' => array(
183
-                    'description' => esc_html__(
184
-                        'Link to event on WordPress site hosting events.',
185
-                        'event_espresso'
186
-                    ),
187
-                    'type' => 'string',
188
-                    'readonly' => true,
189
-                ),
190
-                '_links' => array(
191
-                    'description' => esc_html__(
192
-                        'Various links for resources related to the entity.',
193
-                        'event_espresso'
194
-                    ),
195
-                    'type' => 'object',
196
-                    'readonly' => true,
197
-                    'properties' => array(
198
-                        'self' => array(
199
-                            'description' => esc_html__(
200
-                                'Link to this entities resource.',
201
-                                'event_espresso'
202
-                            ),
203
-                            'type' => 'array',
204
-                            'items' => array(
205
-                                'type' => 'object',
206
-                                'properties' => array(
207
-                                    'href' => array(
208
-                                        'type' => 'string',
209
-                                    ),
210
-                                ),
211
-                                'additionalProperties' => false
212
-                            ),
213
-                            'readonly' => true
214
-                        ),
215
-                        'collection' => array(
216
-                            'description' => esc_html__(
217
-                                'Link to this entities collection resource.',
218
-                                'event_espresso'
219
-                            ),
220
-                            'type' => 'array',
221
-                            'items' => array(
222
-                                'type' => 'object',
223
-                                'properties' => array(
224
-                                    'href' => array(
225
-                                        'type' => 'string'
226
-                                    ),
227
-                                ),
228
-                                'additionalProperties' => false
229
-                            ),
230
-                            'readonly' => true
231
-                        ),
232
-                    ),
233
-                    'additionalProperties' => false,
234
-                ),
235
-                '_calculated_fields' => array_merge(
236
-                    $this->fields_calculator->getJsonSchemaForModel($this->model),
237
-                    array(
238
-                        '_protected' => $this->getProtectedFieldsSchema()
239
-                    )
240
-                ),
241
-                '_protected' => $this->getProtectedFieldsSchema()
242
-            ),
243
-            'additionalProperties' => false,
244
-        );
245
-    }
170
+	/**
171
+	 * Outputs the schema header for a model.
172
+	 *
173
+	 * @return array
174
+	 */
175
+	public function getInitialSchemaStructure()
176
+	{
177
+		return array(
178
+			'$schema'    => 'http://json-schema.org/draft-04/schema#',
179
+			'title'      => $this->model->get_this_model_name(),
180
+			'type'       => 'object',
181
+			'properties' => array(
182
+				'link' => array(
183
+					'description' => esc_html__(
184
+						'Link to event on WordPress site hosting events.',
185
+						'event_espresso'
186
+					),
187
+					'type' => 'string',
188
+					'readonly' => true,
189
+				),
190
+				'_links' => array(
191
+					'description' => esc_html__(
192
+						'Various links for resources related to the entity.',
193
+						'event_espresso'
194
+					),
195
+					'type' => 'object',
196
+					'readonly' => true,
197
+					'properties' => array(
198
+						'self' => array(
199
+							'description' => esc_html__(
200
+								'Link to this entities resource.',
201
+								'event_espresso'
202
+							),
203
+							'type' => 'array',
204
+							'items' => array(
205
+								'type' => 'object',
206
+								'properties' => array(
207
+									'href' => array(
208
+										'type' => 'string',
209
+									),
210
+								),
211
+								'additionalProperties' => false
212
+							),
213
+							'readonly' => true
214
+						),
215
+						'collection' => array(
216
+							'description' => esc_html__(
217
+								'Link to this entities collection resource.',
218
+								'event_espresso'
219
+							),
220
+							'type' => 'array',
221
+							'items' => array(
222
+								'type' => 'object',
223
+								'properties' => array(
224
+									'href' => array(
225
+										'type' => 'string'
226
+									),
227
+								),
228
+								'additionalProperties' => false
229
+							),
230
+							'readonly' => true
231
+						),
232
+					),
233
+					'additionalProperties' => false,
234
+				),
235
+				'_calculated_fields' => array_merge(
236
+					$this->fields_calculator->getJsonSchemaForModel($this->model),
237
+					array(
238
+						'_protected' => $this->getProtectedFieldsSchema()
239
+					)
240
+				),
241
+				'_protected' => $this->getProtectedFieldsSchema()
242
+			),
243
+			'additionalProperties' => false,
244
+		);
245
+	}
246 246
 
247
-    /**
248
-     * Returns an array of JSON schema to describe the _protected property on responses
249
-     * @since 4.9.74.p
250
-     * @return array
251
-     */
252
-    protected function getProtectedFieldsSchema()
253
-    {
254
-        return array(
255
-            'description' => esc_html__('Array of property names whose values were replaced with their default (because they are related to a password-protected entity.)', 'event_espresso'),
256
-            'type' => 'array',
257
-            'items' => array(
258
-                'description' => esc_html__('Each name corresponds to a property that is protected by password for this entity and has its default value returned in the response.', 'event_espresso'),
259
-                'type' => 'string',
260
-                'readonly' => true,
261
-            ),
262
-            'readonly' => true
263
-        );
264
-    }
247
+	/**
248
+	 * Returns an array of JSON schema to describe the _protected property on responses
249
+	 * @since 4.9.74.p
250
+	 * @return array
251
+	 */
252
+	protected function getProtectedFieldsSchema()
253
+	{
254
+		return array(
255
+			'description' => esc_html__('Array of property names whose values were replaced with their default (because they are related to a password-protected entity.)', 'event_espresso'),
256
+			'type' => 'array',
257
+			'items' => array(
258
+				'description' => esc_html__('Each name corresponds to a property that is protected by password for this entity and has its default value returned in the response.', 'event_espresso'),
259
+				'type' => 'string',
260
+				'readonly' => true,
261
+			),
262
+			'readonly' => true
263
+		);
264
+	}
265 265
 
266 266
 
267
-    /**
268
-     * Allows one to just use the object as a string to get the json.
269
-     * eg.
270
-     * $json_schema = new JsonModelSchema(EEM_Event::instance(), new CalculatedModelFields);
271
-     * // if echoed, would convert schema to a json formatted string.
272
-     *
273
-     * @return bool|false|mixed|string
274
-     */
275
-    public function __toString()
276
-    {
277
-        return wp_json_encode($this->getModelSchema());
278
-    }
267
+	/**
268
+	 * Allows one to just use the object as a string to get the json.
269
+	 * eg.
270
+	 * $json_schema = new JsonModelSchema(EEM_Event::instance(), new CalculatedModelFields);
271
+	 * // if echoed, would convert schema to a json formatted string.
272
+	 *
273
+	 * @return bool|false|mixed|string
274
+	 */
275
+	public function __toString()
276
+	{
277
+		return wp_json_encode($this->getModelSchema());
278
+	}
279 279
 }
Please login to merge, or discard this patch.