Completed
Branch models-cleanup/main (de94a1)
by
unknown
61:24 queued 51:13
created
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916 916
      * foreign key to the WP_User table)
917 917
      *
918
-     * @return string|boolean string on success, boolean false when there is no
918
+     * @return string|false string on success, boolean false when there is no
919 919
      * foreign key to the WP_User table
920 920
      * @throws ReflectionException
921 921
      */
@@ -1045,7 +1045,7 @@  discard block
 block discarded – undo
1045 1045
      *
1046 1046
      * @param array  $query_params
1047 1047
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1048
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049 1049
      *                                  fields on the model, and the models we joined to in the query. However, you can
1050 1050
      *                                  override this and set the select to "*", or a specific column name, like
1051 1051
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
      * found in the database matching the given query conditions.
1213 1213
      *
1214 1214
      * @param mixed $current_field_value    Value used for the reference point.
1215
-     * @param null  $field_to_order_by      What field is used for the
1215
+     * @param string  $field_to_order_by      What field is used for the
1216 1216
      *                                      reference point.
1217 1217
      * @param int   $limit                  How many to return.
1218 1218
      * @param array $query_params           Extra conditions on the query.
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
      * as found in the database matching the given query conditions.
1248 1248
      *
1249 1249
      * @param mixed $current_field_value    Value used for the reference point.
1250
-     * @param null  $field_to_order_by      What field is used for the
1250
+     * @param string  $field_to_order_by      What field is used for the
1251 1251
      *                                      reference point.
1252 1252
      * @param int   $limit                  How many to return.
1253 1253
      * @param array $query_params           Extra conditions on the query.
@@ -1282,7 +1282,7 @@  discard block
 block discarded – undo
1282 1282
      * database matching the given query conditions.
1283 1283
      *
1284 1284
      * @param mixed $current_field_value    Value used for the reference point.
1285
-     * @param null  $field_to_order_by      What field is used for the
1285
+     * @param string  $field_to_order_by      What field is used for the
1286 1286
      *                                      reference point.
1287 1287
      * @param array $query_params           Extra conditions on the query.
1288 1288
      * @param null  $columns_to_select      If left null, then an EE_Base_Class
@@ -1317,7 +1317,7 @@  discard block
 block discarded – undo
1317 1317
      * the database matching the given query conditions.
1318 1318
      *
1319 1319
      * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1320
+     * @param string  $field_to_order_by      What field is used for the
1321 1321
      *                                      reference point.
1322 1322
      * @param array $query_params           Extra conditions on the query.
1323 1323
      * @param null  $columns_to_select      If left null, then an EE_Base_Class
@@ -1478,7 +1478,7 @@  discard block
 block discarded – undo
1478 1478
      *
1479 1479
      * @param string $field_name The name of the field the formats are being retrieved for.
1480 1480
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1481
-     * @return array formats in an array with the date format first, and the time format last.
1481
+     * @return string[] formats in an array with the date format first, and the time format last.
1482 1482
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1483 1483
      * @since 4.6.x
1484 1484
      */
@@ -2478,7 +2478,7 @@  discard block
 block discarded – undo
2478 2478
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2479 2479
      * EEM_Base::$_db_verification_level
2480 2480
      *
2481
-     * @param $wpdb_method
2481
+     * @param string $wpdb_method
2482 2482
      * @param $arguments_to_provide
2483 2483
      * @return string
2484 2484
      * @throws EE_Error
@@ -2597,6 +2597,7 @@  discard block
 block discarded – undo
2597 2597
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2598 2598
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2599 2599
      *                             because these will be inserted in any new rows created as well.
2600
+     * @param EE_Base_Class $id_or_obj
2600 2601
      * @return boolean of success
2601 2602
      * @throws EE_Error
2602 2603
      */
@@ -2608,7 +2609,7 @@  discard block
 block discarded – undo
2608 2609
 
2609 2610
 
2610 2611
     /**
2611
-     * @param mixed  $id_or_obj
2612
+     * @param EE_Base_Class  $id_or_obj
2612 2613
      * @param string $relationName
2613 2614
      * @param array  $where_query_params
2614 2615
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2649,7 +2650,7 @@  discard block
 block discarded – undo
2649 2650
      * However, if the model objects can't be deleted because of blocking related model objects, then
2650 2651
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2651 2652
      *
2652
-     * @param EE_Base_Class|int|string $id_or_obj
2653
+     * @param EE_Base_Class $id_or_obj
2653 2654
      * @param string                   $model_name
2654 2655
      * @param array                    $query_params
2655 2656
      * @return int how many deleted
@@ -2670,7 +2671,7 @@  discard block
 block discarded – undo
2670 2671
      * the model objects can't be hard deleted because of blocking related model objects,
2671 2672
      * just does a soft-delete on them instead.
2672 2673
      *
2673
-     * @param EE_Base_Class|int|string $id_or_obj
2674
+     * @param EE_Base_Class $id_or_obj
2674 2675
      * @param string                   $model_name
2675 2676
      * @param array                    $query_params
2676 2677
      * @return int how many deleted
@@ -2728,6 +2729,7 @@  discard block
 block discarded – undo
2728 2729
      * @param string $model_name   like 'Event', or 'Registration'
2729 2730
      * @param array  $query_params
2730 2731
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2732
+     * @param EE_Base_Class $id_or_obj
2731 2733
      * @return float
2732 2734
      * @throws EE_Error
2733 2735
      * @throws ReflectionException
@@ -3761,7 +3763,7 @@  discard block
 block discarded – undo
3761 3763
      * We should use default where conditions on related models when they requested to use default where conditions
3762 3764
      * on all models, or specifically just on other related models
3763 3765
      *
3764
-     * @param      $default_where_conditions_value
3766
+     * @param      string $default_where_conditions_value
3765 3767
      * @param bool $for_this_model false means this is for OTHER related models
3766 3768
      * @return bool
3767 3769
      */
@@ -3801,7 +3803,7 @@  discard block
 block discarded – undo
3801 3803
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802 3804
      * on this model or others
3803 3805
      *
3804
-     * @param      $default_where_conditions_value
3806
+     * @param      string $default_where_conditions_value
3805 3807
      * @param bool $for_this_model false means this is for OTHER related models
3806 3808
      * @return bool
3807 3809
      */
@@ -4990,7 +4992,7 @@  discard block
 block discarded – undo
4990 4992
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4991 4993
      * Eg, on EE_Answer that would be ANS_ID field object
4992 4994
      *
4993
-     * @param $field_obj
4995
+     * @param EE_Model_Field_Base $field_obj
4994 4996
      * @return boolean
4995 4997
      */
4996 4998
     public function is_primary_key_field($field_obj)
@@ -5799,7 +5801,7 @@  discard block
 block discarded – undo
5799 5801
     /**
5800 5802
      * Read comments for assume_values_already_prepared_by_model_object()
5801 5803
      *
5802
-     * @return int
5804
+     * @return boolean
5803 5805
      */
5804 5806
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5805 5807
     {
@@ -6434,7 +6436,7 @@  discard block
 block discarded – undo
6434 6436
     /**
6435 6437
      * Returns the password field on this model, if there is one
6436 6438
      *
6437
-     * @return EE_Password_Field|null
6439
+     * @return EE_Model_Field_Base|null
6438 6440
      * @since 4.9.74.p
6439 6441
      */
6440 6442
     public function getPasswordField()
Please login to merge, or discard this patch.
Indentation   +6562 added lines, -6562 removed lines patch added patch discarded remove patch
@@ -37,6568 +37,6568 @@
 block discarded – undo
37 37
 abstract class EEM_Base extends EE_Base implements ResettableInterface
38 38
 {
39 39
 
40
-    /**
41
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
-     */
43
-    const caps_read       = 'read';
44
-
45
-    const caps_read_admin = 'read_admin';
46
-
47
-    const caps_edit       = 'edit';
48
-
49
-    const caps_delete     = 'delete';
50
-
51
-
52
-    /**
53
-     * constant used to show EEM_Base has not yet verified the db on this http request
54
-     */
55
-    const db_verified_none = 0;
56
-
57
-    /**
58
-     * constant used to show EEM_Base has verified the EE core db on this http request,
59
-     * but not the addons' dbs
60
-     */
61
-    const db_verified_core = 1;
62
-
63
-    /**
64
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
-     * the EE core db too)
66
-     */
67
-    const db_verified_addons = 2;
68
-
69
-    /**
70
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
-     *        registrations for non-trashed tickets for non-trashed datetimes)
73
-     */
74
-    const default_where_conditions_all = 'all';
75
-
76
-    /**
77
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
-     *        models which share tables with other models, this can return data for the wrong model.
82
-     */
83
-    const default_where_conditions_this_only = 'this_model_only';
84
-
85
-    /**
86
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
-     */
90
-    const default_where_conditions_others_only = 'other_models_only';
91
-
92
-    /**
93
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
96
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
-     *        (regardless of whether those events and venues are trashed)
98
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
-     *        events.
100
-     */
101
-    const default_where_conditions_minimum_all = 'minimum';
102
-
103
-    /**
104
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
-     *        not)
108
-     */
109
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
-
111
-    /**
112
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
-     *        it's possible it will return table entries for other models. You should use
115
-     *        EEM_Base::default_where_conditions_minimum_all instead.
116
-     */
117
-    const default_where_conditions_none = 'none';
118
-
119
-    /**
120
-     * when $_values_already_prepared_by_model_object equals this, we assume
121
-     * the data is just like form input that needs to have the model fields'
122
-     * prepare_for_set and prepare_for_use_in_db called on it
123
-     */
124
-    const not_prepared_by_model_object = 0;
125
-
126
-    /**
127
-     * when $_values_already_prepared_by_model_object equals this, we
128
-     * assume this value is coming from a model object and doesn't need to have
129
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
130
-     */
131
-    const prepared_by_model_object = 1;
132
-
133
-    /**
134
-     * when $_values_already_prepared_by_model_object equals this, we assume
135
-     * the values are already to be used in the database (ie no processing is done
136
-     * on them by the model's fields)
137
-     */
138
-    const prepared_for_use_in_db = 2;
139
-
140
-    /**
141
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
-     * They almost always WILL NOT, but it's not necessarily a requirement.
144
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
-     *
146
-     * @var boolean
147
-     */
148
-    private $_values_already_prepared_by_model_object = 0;
149
-
150
-
151
-    /**
152
-     * @var string
153
-     */
154
-    protected $singular_item = 'Item';
155
-
156
-    /**
157
-     * @var string
158
-     */
159
-    protected $plural_item = 'Items';
160
-
161
-    /**
162
-     * array of EE_Table objects for defining which tables comprise this model.
163
-     *
164
-     * @type EE_Table_Base[] $_tables
165
-     */
166
-    protected $_tables;
167
-
168
-    /**
169
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
-     *
173
-     * @var EE_Model_Field_Base[][] $_fields
174
-     */
175
-    protected $_fields;
176
-
177
-    /**
178
-     * array of different kinds of relations
179
-     *
180
-     * @var EE_Model_Relation_Base[] $_model_relations
181
-     */
182
-    protected $_model_relations;
183
-
184
-    /**
185
-     * @var EE_Index[] $_indexes
186
-     */
187
-    protected $_indexes = [];
188
-
189
-    /**
190
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
191
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
-     * by setting the same columns as used in these queries in the query yourself.
193
-     *
194
-     * @var EE_Default_Where_Conditions
195
-     */
196
-    protected $_default_where_conditions_strategy;
197
-
198
-    /**
199
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
-     * This is particularly useful when you want something between 'none' and 'default'
201
-     *
202
-     * @var EE_Default_Where_Conditions
203
-     */
204
-    protected $_minimum_where_conditions_strategy;
205
-
206
-    /**
207
-     * String describing how to find the "owner" of this model's objects.
208
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
-     * But when there isn't, this indicates which related model, or transiently-related model,
210
-     * has the foreign key to the wp_users table.
211
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
-     * related to events, and events have a foreign key to wp_users.
213
-     * On EEM_Transaction, this would be 'Transaction.Event'
214
-     *
215
-     * @var string
216
-     */
217
-    protected $_model_chain_to_wp_user = '';
218
-
219
-    /**
220
-     * String describing how to find the model with a password controlling access to this model. This property has the
221
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
-     * This value is the path of models to follow to arrive at the model with the password field.
223
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
-     * model with a password that should affect reading this on the front-end.
225
-     * Eg this is an empty string for the Event model because it has a password.
226
-     * This is null for the Registration model, because its event's password has no bearing on whether
227
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
-     * should hide tickets for datetimes for events that have a password set.
230
-     *
231
-     * @var string |null
232
-     */
233
-    protected $model_chain_to_password = null;
234
-
235
-    /**
236
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
-     * don't need it (particularly CPT models)
238
-     *
239
-     * @var bool
240
-     */
241
-    protected $_ignore_where_strategy = false;
242
-
243
-    /**
244
-     * String used in caps relating to this model. Eg, if the caps relating to this
245
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
-     *
247
-     * @var string. If null it hasn't been initialized yet. If false then we
248
-     * have indicated capabilities don't apply to this
249
-     */
250
-    protected $_caps_slug = null;
251
-
252
-    /**
253
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
-     * and next-level keys are capability names, and values are a
255
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
-     * they specify which context to use (ie, frontend, backend, edit or delete)
257
-     * and then each capability in the corresponding sub-array that they're missing
258
-     * adds the where conditions onto the query.
259
-     *
260
-     * @var array
261
-     */
262
-    protected $_cap_restrictions = [
263
-        self::caps_read       => [],
264
-        self::caps_read_admin => [],
265
-        self::caps_edit       => [],
266
-        self::caps_delete     => [],
267
-    ];
268
-
269
-    /**
270
-     * Array defining which cap restriction generators to use to create default
271
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
272
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
-     * automatically set this to false (not just null).
275
-     *
276
-     * @var EE_Restriction_Generator_Base[]
277
-     */
278
-    protected $_cap_restriction_generators = [];
279
-
280
-    /**
281
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
-     * maps to 'read' because when looking for relevant permissions we're going to use
284
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
285
-     *
286
-     * @var array
287
-     */
288
-    protected $_cap_contexts_to_cap_action_map = [
289
-        self::caps_read       => 'read',
290
-        self::caps_read_admin => 'read',
291
-        self::caps_edit       => 'edit',
292
-        self::caps_delete     => 'delete',
293
-    ];
294
-
295
-    /**
296
-     * Timezone
297
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
-     * EE_Datetime_Field data type will have access to it.
301
-     *
302
-     * @var string
303
-     */
304
-    protected $_timezone;
305
-
306
-
307
-    /**
308
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
-     * multisite.
310
-     *
311
-     * @var int
312
-     */
313
-    protected static $_model_query_blog_id;
314
-
315
-    /**
316
-     * A copy of _fields, except the array keys are the model names pointed to by
317
-     * the field
318
-     *
319
-     * @var EE_Model_Field_Base[]
320
-     */
321
-    private $_cache_foreign_key_to_fields = [];
322
-
323
-    /**
324
-     * Cached list of all the fields on the model, indexed by their name
325
-     *
326
-     * @var EE_Model_Field_Base[]
327
-     */
328
-    private $_cached_fields = null;
329
-
330
-    /**
331
-     * Cached list of all the fields on the model, except those that are
332
-     * marked as only pertinent to the database
333
-     *
334
-     * @var EE_Model_Field_Base[]
335
-     */
336
-    private $_cached_fields_non_db_only = null;
337
-
338
-    /**
339
-     * A cached reference to the primary key for quick lookup
340
-     *
341
-     * @var EE_Model_Field_Base
342
-     */
343
-    private $_primary_key_field = null;
344
-
345
-    /**
346
-     * Flag indicating whether this model has a primary key or not
347
-     *
348
-     * @var boolean
349
-     */
350
-    protected $_has_primary_key_field = null;
351
-
352
-    /**
353
-     * array in the format:  [ FK alias => full PK ]
354
-     * where keys are local column name aliases for foreign keys
355
-     * and values are the fully qualified column name for the primary key they represent
356
-     *  ex:
357
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
-     *
359
-     * @var array $foreign_key_aliases
360
-     */
361
-    protected $foreign_key_aliases = [];
362
-
363
-    /**
364
-     * Whether or not this model is based off a table in WP core only (CPTs should set
365
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
-     * This should be true for models that deal with data that should exist independent of EE.
367
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
369
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
371
-     *
372
-     * @var boolean
373
-     */
374
-    protected $_wp_core_model = false;
375
-
376
-    /**
377
-     * @var bool stores whether this model has a password field or not.
378
-     * null until initialized by hasPasswordField()
379
-     */
380
-    protected $has_password_field;
381
-
382
-    /**
383
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
-     */
385
-    protected $password_field;
386
-
387
-    /**
388
-     *    List of valid operators that can be used for querying.
389
-     * The keys are all operators we'll accept, the values are the real SQL
390
-     * operators used
391
-     *
392
-     * @var array
393
-     */
394
-    protected $_valid_operators = [
395
-        '='           => '=',
396
-        '<='          => '<=',
397
-        '<'           => '<',
398
-        '>='          => '>=',
399
-        '>'           => '>',
400
-        '!='          => '!=',
401
-        'LIKE'        => 'LIKE',
402
-        'like'        => 'LIKE',
403
-        'NOT_LIKE'    => 'NOT LIKE',
404
-        'not_like'    => 'NOT LIKE',
405
-        'NOT LIKE'    => 'NOT LIKE',
406
-        'not like'    => 'NOT LIKE',
407
-        'IN'          => 'IN',
408
-        'in'          => 'IN',
409
-        'NOT_IN'      => 'NOT IN',
410
-        'not_in'      => 'NOT IN',
411
-        'NOT IN'      => 'NOT IN',
412
-        'not in'      => 'NOT IN',
413
-        'between'     => 'BETWEEN',
414
-        'BETWEEN'     => 'BETWEEN',
415
-        'IS_NOT_NULL' => 'IS NOT NULL',
416
-        'is_not_null' => 'IS NOT NULL',
417
-        'IS NOT NULL' => 'IS NOT NULL',
418
-        'is not null' => 'IS NOT NULL',
419
-        'IS_NULL'     => 'IS NULL',
420
-        'is_null'     => 'IS NULL',
421
-        'IS NULL'     => 'IS NULL',
422
-        'is null'     => 'IS NULL',
423
-        'REGEXP'      => 'REGEXP',
424
-        'regexp'      => 'REGEXP',
425
-        'NOT_REGEXP'  => 'NOT REGEXP',
426
-        'not_regexp'  => 'NOT REGEXP',
427
-        'NOT REGEXP'  => 'NOT REGEXP',
428
-        'not regexp'  => 'NOT REGEXP',
429
-    ];
430
-
431
-    /**
432
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
-     *
434
-     * @var array
435
-     */
436
-    protected $_in_style_operators = ['IN', 'NOT IN'];
437
-
438
-    /**
439
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
-     * '12-31-2012'"
441
-     *
442
-     * @var array
443
-     */
444
-    protected $_between_style_operators = ['BETWEEN'];
445
-
446
-    /**
447
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
-
453
-    /**
454
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
-     * on a join table.
456
-     *
457
-     * @var array
458
-     */
459
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
-
461
-    /**
462
-     * Allowed values for $query_params['order'] for ordering in queries
463
-     *
464
-     * @var array
465
-     */
466
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
-
468
-    /**
469
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
471
-     *
472
-     * @var array
473
-     */
474
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
-
476
-    /**
477
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
479
-     *
480
-     * @var array
481
-     */
482
-    private $_allowed_query_params = [
483
-        0,
484
-        'limit',
485
-        'order_by',
486
-        'group_by',
487
-        'having',
488
-        'force_join',
489
-        'order',
490
-        'on_join_limit',
491
-        'default_where_conditions',
492
-        'caps',
493
-        'extra_selects',
494
-        'exclude_protected',
495
-    ];
496
-
497
-    /**
498
-     * All the data types that can be used in $wpdb->prepare statements.
499
-     *
500
-     * @var array
501
-     */
502
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
-
504
-    /**
505
-     * @var EE_Registry $EE
506
-     */
507
-    protected $EE = null;
508
-
509
-
510
-    /**
511
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
-     *
513
-     * @var int
514
-     */
515
-    protected $_show_next_x_db_queries = 0;
516
-
517
-    /**
518
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
-     * WHERE, GROUP_BY, etc.
521
-     *
522
-     * @var CustomSelects
523
-     */
524
-    protected $_custom_selections = [];
525
-
526
-    /**
527
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
-     * caches every model object we've fetched from the DB on this request
529
-     *
530
-     * @var array
531
-     */
532
-    protected $_entity_map;
533
-
534
-    /**
535
-     * @var LoaderInterface $loader
536
-     */
537
-    private static $loader;
538
-
539
-    /**
540
-     * indicates whether an EEM_Base child has already re-verified the DB
541
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
542
-     * looking like EEM_Base::db_verified_*
543
-     *
544
-     * @var int - 0 = none, 1 = core, 2 = addons
545
-     */
546
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
547
-
548
-
549
-    /**
550
-     * About all child constructors:
551
-     * they should define the _tables, _fields and _model_relations arrays.
552
-     * Should ALWAYS be called after child constructor.
553
-     * In order to make the child constructors to be as simple as possible, this parent constructor
554
-     * finalizes constructing all the object's attributes.
555
-     * Generally, rather than requiring a child to code
556
-     * $this->_tables = array(
557
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
-     *        ...);
559
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
-     * each EE_Table has a function to set the table's alias after the constructor, using
561
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
-     * do something similar.
563
-     *
564
-     * @param string $timezone
565
-     * @throws EE_Error
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blog id for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                /** @var $table_obj EE_Secondary_Table */
599
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
-            }
601
-        }
602
-        /**
603
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
-         * EE_Register_Model_Extension
605
-         *
606
-         * @param EE_Model_Field_Base[] $_fields
607
-         */
608
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
-        $this->_invalidate_field_caches();
610
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
612
-                throw new EE_Error(
613
-                    sprintf(
614
-                        esc_html__(
615
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
-                            'event_espresso'
617
-                        ),
618
-                        $table_alias,
619
-                        implode(",", $this->_fields)
620
-                    )
621
-                );
622
-            }
623
-            foreach ($fields_for_table as $field_name => $field_obj) {
624
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
-                // primary key field base has a slightly different _construct_finalize
626
-                /** @var $field_obj EE_Model_Field_Base */
627
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
-            }
629
-        }
630
-        // everything is related to Extra_Meta
631
-        if (get_class($this) !== 'EEM_Extra_Meta') {
632
-            // make extra meta related to everything, but don't block deleting things just
633
-            // because they have related extra meta info. For now just orphan those extra meta
634
-            // in the future we should automatically delete them
635
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
-        }
637
-        // and change logs
638
-        if (get_class($this) !== 'EEM_Change_Log') {
639
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
-        }
641
-        /**
642
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
-         * EE_Register_Model_Extension
644
-         *
645
-         * @param EE_Model_Relation_Base[] $_model_relations
646
-         */
647
-        $this->_model_relations = (array)apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
649
-            $this->_model_relations
650
-        );
651
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
652
-            /** @var $relation_obj EE_Model_Relation_Base */
653
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
-        }
655
-        foreach ($this->_indexes as $index_name => $index_obj) {
656
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
-        }
658
-        $this->set_timezone($timezone);
659
-        // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
661
-            // nothing was set during child constructor, so set default
662
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
-        }
664
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
666
-            // nothing was set during child constructor, so set default
667
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
-        }
669
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
671
-        // to indicate to NOT set it, set it to the logical default
672
-        if ($this->_caps_slug === null) {
673
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
-        }
675
-        // initialize the standard cap restriction generators if none were specified by the child constructor
676
-        if (! empty($this->_cap_restriction_generators)) {
677
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
-                        new EE_Restriction_Generator_Protected(),
682
-                        $cap_context,
683
-                        $this
684
-                    );
685
-                }
686
-            }
687
-        // }
688
-        // if ($this->_cap_restriction_generators !== false) {
689
-        // if there are cap restriction generators, use them to make the default cap restrictions
690
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
692
-                    continue;
693
-                }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
-                    throw new EE_Error(
696
-                        sprintf(
697
-                            esc_html__(
698
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
699
-                                'event_espresso'
700
-                            ),
701
-                            $context,
702
-                            $this->get_this_model_name()
703
-                        )
704
-                    );
705
-                }
706
-                $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
708
-                    $generator_object->_construct_finalize($this, $action);
709
-                }
710
-            }
711
-        }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
713
-    }
714
-
715
-
716
-    /**
717
-     * Used to set the $_model_query_blog_id static property.
718
-     *
719
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
-     *                      value for get_current_blog_id() will be used.
721
-     */
722
-    public static function set_model_query_blog_id($blog_id = 0)
723
-    {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
725
-    }
726
-
727
-
728
-    /**
729
-     * Returns whatever is set as the internal $model_query_blog_id.
730
-     *
731
-     * @return int
732
-     */
733
-    public static function get_model_query_blog_id()
734
-    {
735
-        return EEM_Base::$_model_query_blog_id;
736
-    }
737
-
738
-
739
-    /**
740
-     * This function is a singleton method used to instantiate the Espresso_model object
741
-     *
742
-     * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
-     *                                (and any incoming timezone data that gets saved).
744
-     *                                Note this just sends the timezone info to the date time model field objects.
745
-     *                                Default is NULL
746
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
-     * @return static (as in the concrete child class)
748
-     * @throws EE_Error
749
-     * @throws InvalidArgumentException
750
-     * @throws InvalidDataTypeException
751
-     * @throws InvalidInterfaceException
752
-     */
753
-    public static function instance($timezone = '')
754
-    {
755
-        // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
757
-            // instantiate Espresso_model
758
-            static::$_instance = new static(
759
-                $timezone,
760
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
-            );
762
-        }
763
-        // Espresso model object
764
-        return static::$_instance;
765
-    }
766
-
767
-
768
-    /**
769
-     * resets the model and returns it
770
-     *
771
-     * @param string $timezone
772
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
-     * all its properties reset; if it wasn't instantiated, returns null)
774
-     * @throws EE_Error
775
-     * @throws ReflectionException
776
-     * @throws InvalidArgumentException
777
-     * @throws InvalidDataTypeException
778
-     * @throws InvalidInterfaceException
779
-     */
780
-    public static function reset($timezone = '')
781
-    {
782
-        if (static::$_instance instanceof EEM_Base) {
783
-            // let's try to NOT swap out the current instance for a new one
784
-            // because if someone has a reference to it, we can't remove their reference
785
-            // so it's best to keep using the same reference, but change the original object
786
-            // reset all its properties to their original values as defined in the class
787
-            $r                 = new ReflectionClass(get_class(static::$_instance));
788
-            $static_properties = $r->getStaticProperties();
789
-            foreach ($r->getDefaultProperties() as $property => $value) {
790
-                // don't set instance to null like it was originally,
791
-                // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
793
-                    static::$_instance->{$property} = $value;
794
-                }
795
-            }
796
-            EEH_DTT_Helper::resetDefaultTimezoneString();
797
-            // and then directly call its constructor again, like we would if we were creating a new one
798
-            static::$_instance->__construct(
799
-                $timezone,
800
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
-            );
802
-            return static::instance();
803
-        }
804
-        return null;
805
-    }
806
-
807
-
808
-    /**
809
-     * @return LoaderInterface
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     */
814
-    private static function getLoader()
815
-    {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
817
-            EEM_Base::$loader = LoaderFactory::getLoader();
818
-        }
819
-        return EEM_Base::$loader;
820
-    }
821
-
822
-
823
-    /**
824
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
-     *
826
-     * @param boolean $translated return localized strings or JUST the array.
827
-     * @return array
828
-     * @throws EE_Error
829
-     * @throws InvalidArgumentException
830
-     * @throws InvalidDataTypeException
831
-     * @throws InvalidInterfaceException
832
-     * @throws ReflectionException
833
-     */
834
-    public function status_array($translated = false)
835
-    {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
837
-            return [];
838
-        }
839
-        $model_name   = $this->get_this_model_name();
840
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
-        $statuses      = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
-        $status_array = [];
843
-        foreach ($statuses as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
845
-        }
846
-        return $translated
847
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
-            : $status_array;
849
-    }
850
-
851
-
852
-    /**
853
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
-     *
855
-     * @param array $query_params             see github link below for more info
856
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
-     *                                        EEM_Transaction::instance()->get_all( array( array(
861
-     *                                        'OR'=>array(
862
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
-     *                                        )
865
-     *                                        ),
866
-     *                                        'limit'=>10,
867
-     *                                        'group_by'=>'TXN_ID'
868
-     *                                        ));
869
-     *                                        get all the answers to the question titled "shirt size" for event with id
870
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
-     *                                        'Question.QST_display_text'=>'shirt size',
872
-     *                                        'Registration.Event.EVT_ID'=>12
873
-     *                                        ),
874
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
875
-     *                                        ));
876
-     * @throws EE_Error
877
-     * @throws ReflectionException
878
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
-     *                                        or if you have the development copy of EE you can view this at the path:
880
-     *                                        /docs/G--Model-System/model-query-params.md
881
-     */
882
-    public function get_all($query_params = [])
883
-    {
884
-        if (
885
-            isset($query_params['limit'])
886
-            && ! isset($query_params['group_by'])
887
-        ) {
888
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
-        }
890
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
-    }
892
-
893
-
894
-    /**
895
-     * Modifies the query parameters so we only get back model objects
896
-     * that "belong" to the current user
897
-     *
898
-     * @param array $query_params see github link below for more info
899
-     * @return array
900
-     * @throws ReflectionException
901
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     */
903
-    public function alter_query_params_to_only_include_mine($query_params = [])
904
-    {
905
-        $wp_user_field_name = $this->wp_user_field_name();
906
-        if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
-        }
909
-        return $query_params;
910
-    }
911
-
912
-
913
-    /**
914
-     * Returns the name of the field's name that points to the WP_User table
915
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
-     * foreign key to the WP_User table)
917
-     *
918
-     * @return string|boolean string on success, boolean false when there is no
919
-     * foreign key to the WP_User table
920
-     * @throws ReflectionException
921
-     */
922
-    public function wp_user_field_name()
923
-    {
924
-        try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
926
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
-                $last_model_name              = end($models_to_follow_to_wp_users);
928
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
-            } else {
931
-                $model_with_fk_to_wp_users = $this;
932
-                $model_chain_to_wp_user    = '';
933
-            }
934
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
936
-        } catch (EE_Error $e) {
937
-            return false;
938
-        }
939
-    }
940
-
941
-
942
-    /**
943
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
944
-     * (or transiently-related model) has a foreign key to the wp_users table;
945
-     * useful for finding if model objects of this type are 'owned' by the current user.
946
-     * This is an empty string when the foreign key is on this model and when it isn't,
947
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
948
-     * (or transiently-related model)
949
-     *
950
-     * @return string
951
-     */
952
-    public function model_chain_to_wp_user()
953
-    {
954
-        return $this->_model_chain_to_wp_user;
955
-    }
956
-
957
-
958
-    /**
959
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
-     * like how registrations don't have a foreign key to wp_users, but the
961
-     * events they are for are), or is unrelated to wp users.
962
-     * generally available
963
-     *
964
-     * @return boolean
965
-     */
966
-    public function is_owned()
967
-    {
968
-        if ($this->model_chain_to_wp_user()) {
969
-            return true;
970
-        }
971
-        try {
972
-            $this->get_foreign_key_to('WP_User');
973
-            return true;
974
-        } catch (EE_Error $e) {
975
-            return false;
976
-        }
977
-    }
978
-
979
-
980
-    /**
981
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
-     * the model)
984
-     *
985
-     * @param array  $query_params
986
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
-     *                                  fields on the model, and the models we joined to in the query. However, you can
989
-     *                                  override this and set the select to "*", or a specific column name, like
990
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
-     *                                  the aliases used to refer to this selection, and values are to be
993
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws ReflectionException
999
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
-     */
1001
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
-    {
1003
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
-        $select_expressions       = $columns_to_select === null
1006
-            ? $this->_construct_default_select_sql($model_query_info)
1007
-            : '';
1008
-        if ($this->_custom_selections instanceof CustomSelects) {
1009
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
-            $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1012
-                : $custom_expressions;
1013
-        }
1014
-
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
-     * method of including extra select information.
1024
-     *
1025
-     * @param array             $query_params
1026
-     * @param null|array|string $columns_to_select
1027
-     * @return null|CustomSelects
1028
-     * @throws InvalidArgumentException
1029
-     */
1030
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
-    {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
-            return null;
1034
-        }
1035
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
-        return new CustomSelects($selects);
1038
-    }
1039
-
1040
-
1041
-    /**
1042
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1043
-     * but you can use the model query params to more easily
1044
-     * take care of joins, field preparation etc.
1045
-     *
1046
-     * @param array  $query_params
1047
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1050
-     *                                  override this and set the select to "*", or a specific column name, like
1051
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
-     *                                  the aliases used to refer to this selection, and values are to be
1054
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
-     * @throws EE_Error
1058
-     * @throws ReflectionException
1059
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
-     */
1061
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
-    {
1063
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * For creating a custom select statement
1069
-     *
1070
-     * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
-     *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
-     *                                        selection SQL, and 1=>is the datatype
1073
-     * @return string
1074
-     * @throws EE_Error
1075
-     */
1076
-    private function _construct_select_from_input($columns_to_select)
1077
-    {
1078
-        if (is_array($columns_to_select)) {
1079
-            $select_sql_array = [];
1080
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype,
1089
-                            $alias
1090
-                        )
1091
-                    );
1092
-                }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
-                    throw new EE_Error(
1095
-                        sprintf(
1096
-                            esc_html__(
1097
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
-                                'event_espresso'
1099
-                            ),
1100
-                            $selection_and_datatype[1],
1101
-                            $selection_and_datatype[0],
1102
-                            $alias,
1103
-                            implode(', ', $this->_valid_wpdb_data_types)
1104
-                        )
1105
-                    );
1106
-                }
1107
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
-            }
1109
-            $columns_to_select_string = implode(', ', $select_sql_array);
1110
-        } else {
1111
-            $columns_to_select_string = $columns_to_select;
1112
-        }
1113
-        return $columns_to_select_string;
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
-     *
1120
-     * @return string
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function primary_key_name()
1124
-    {
1125
-        return $this->get_primary_key_field()->get_name();
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
-     * If there is no primary key on this model, $id is treated as primary key string
1132
-     *
1133
-     * @param mixed $id int or string, depending on the type of the model's primary key
1134
-     * @return EE_Base_Class
1135
-     * @throws EE_Error
1136
-     * @throws ReflectionException
1137
-     */
1138
-    public function get_one_by_ID($id)
1139
-    {
1140
-        if ($this->get_from_entity_map($id)) {
1141
-            return $this->get_from_entity_map($id);
1142
-        }
1143
-        $model_object = $this->get_one(
1144
-            $this->alter_query_params_to_restrict_by_ID(
1145
-                $id,
1146
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
-            )
1148
-        );
1149
-        $className = $this->_get_class_name();
1150
-        if ($model_object instanceof $className) {
1151
-            // make sure valid objects get added to the entity map
1152
-            // so that the next call to this method doesn't trigger another trip to the db
1153
-            $this->add_to_entity_map($model_object);
1154
-        }
1155
-        return $model_object;
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * Alters query parameters to only get items with this ID are returned.
1161
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1162
-     * or could just be a simple primary key ID
1163
-     *
1164
-     * @param int   $id
1165
-     * @param array $query_params see github link below for more info
1166
-     * @return array of normal query params,
1167
-     * @throws EE_Error
1168
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1169
-     */
1170
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1171
-    {
1172
-        if (! isset($query_params[0])) {
1173
-            $query_params[0] = [];
1174
-        }
1175
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1176
-        if ($conditions_from_id === null) {
1177
-            $query_params[0][ $this->primary_key_name() ] = $id;
1178
-        } else {
1179
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1180
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1181
-        }
1182
-        return $query_params;
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1188
-     * array. If no item is found, null is returned.
1189
-     *
1190
-     * @param array $query_params like EEM_Base's $query_params variable.
1191
-     * @return EE_Base_Class|null
1192
-     * @throws EE_Error
1193
-     * @throws ReflectionException
1194
-     */
1195
-    public function get_one(array $query_params = [])
1196
-    {
1197
-        if (! is_array($query_params)) {
1198
-            EE_Error::doing_it_wrong(
1199
-                'EEM_Base::get_one',
1200
-                sprintf(
1201
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1202
-                    gettype($query_params)
1203
-                ),
1204
-                '4.6.0'
1205
-            );
1206
-            $query_params = [];
1207
-        }
1208
-        $query_params['limit'] = 1;
1209
-        $items                 = $this->get_all($query_params);
1210
-        if (empty($items)) {
1211
-            return null;
1212
-        }
1213
-        return array_shift($items);
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * Returns the next x number of items in sequence from the given value as
1219
-     * found in the database matching the given query conditions.
1220
-     *
1221
-     * @param mixed $current_field_value    Value used for the reference point.
1222
-     * @param null  $field_to_order_by      What field is used for the
1223
-     *                                      reference point.
1224
-     * @param int   $limit                  How many to return.
1225
-     * @param array $query_params           Extra conditions on the query.
1226
-     * @param null  $columns_to_select      If left null, then an array of
1227
-     *                                      EE_Base_Class objects is returned,
1228
-     *                                      otherwise you can indicate just the
1229
-     *                                      columns you want returned.
1230
-     * @return EE_Base_Class[]|array
1231
-     * @throws EE_Error
1232
-     * @throws ReflectionException
1233
-     */
1234
-    public function next_x(
1235
-        $current_field_value,
1236
-        $field_to_order_by = null,
1237
-        $limit = 1,
1238
-        $query_params = [],
1239
-        $columns_to_select = null
1240
-    ) {
1241
-        return $this->_get_consecutive(
1242
-            $current_field_value,
1243
-            '>',
1244
-            $field_to_order_by,
1245
-            $limit,
1246
-            $query_params,
1247
-            $columns_to_select
1248
-        );
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Returns the previous x number of items in sequence from the given value
1254
-     * as found in the database matching the given query conditions.
1255
-     *
1256
-     * @param mixed $current_field_value    Value used for the reference point.
1257
-     * @param null  $field_to_order_by      What field is used for the
1258
-     *                                      reference point.
1259
-     * @param int   $limit                  How many to return.
1260
-     * @param array $query_params           Extra conditions on the query.
1261
-     * @param null  $columns_to_select      If left null, then an array of
1262
-     *                                      EE_Base_Class objects is returned,
1263
-     *                                      otherwise you can indicate just the
1264
-     *                                      columns you want returned.
1265
-     * @return EE_Base_Class[]|array
1266
-     * @throws EE_Error
1267
-     * @throws ReflectionException
1268
-     */
1269
-    public function previous_x(
1270
-        $current_field_value,
1271
-        $field_to_order_by = null,
1272
-        $limit = 1,
1273
-        $query_params = [],
1274
-        $columns_to_select = null
1275
-    ) {
1276
-        return $this->_get_consecutive(
1277
-            $current_field_value,
1278
-            '<',
1279
-            $field_to_order_by,
1280
-            $limit,
1281
-            $query_params,
1282
-            $columns_to_select
1283
-        );
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * Returns the next item in sequence from the given value as found in the
1289
-     * database matching the given query conditions.
1290
-     *
1291
-     * @param mixed $current_field_value    Value used for the reference point.
1292
-     * @param null  $field_to_order_by      What field is used for the
1293
-     *                                      reference point.
1294
-     * @param array $query_params           Extra conditions on the query.
1295
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1296
-     *                                      object is returned, otherwise you
1297
-     *                                      can indicate just the columns you
1298
-     *                                      want and a single array indexed by
1299
-     *                                      the columns will be returned.
1300
-     * @return EE_Base_Class|null|array()
1301
-     * @throws EE_Error
1302
-     * @throws ReflectionException
1303
-     */
1304
-    public function next(
1305
-        $current_field_value,
1306
-        $field_to_order_by = null,
1307
-        $query_params = [],
1308
-        $columns_to_select = null
1309
-    ) {
1310
-        $results = $this->_get_consecutive(
1311
-            $current_field_value,
1312
-            '>',
1313
-            $field_to_order_by,
1314
-            1,
1315
-            $query_params,
1316
-            $columns_to_select
1317
-        );
1318
-        return empty($results) ? null : reset($results);
1319
-    }
1320
-
1321
-
1322
-    /**
1323
-     * Returns the previous item in sequence from the given value as found in
1324
-     * the database matching the given query conditions.
1325
-     *
1326
-     * @param mixed $current_field_value    Value used for the reference point.
1327
-     * @param null  $field_to_order_by      What field is used for the
1328
-     *                                      reference point.
1329
-     * @param array $query_params           Extra conditions on the query.
1330
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1331
-     *                                      object is returned, otherwise you
1332
-     *                                      can indicate just the columns you
1333
-     *                                      want and a single array indexed by
1334
-     *                                      the columns will be returned.
1335
-     * @return EE_Base_Class|null|array()
1336
-     * @throws EE_Error
1337
-     * @throws ReflectionException
1338
-     */
1339
-    public function previous(
1340
-        $current_field_value,
1341
-        $field_to_order_by = null,
1342
-        $query_params = [],
1343
-        $columns_to_select = null
1344
-    ) {
1345
-        $results = $this->_get_consecutive(
1346
-            $current_field_value,
1347
-            '<',
1348
-            $field_to_order_by,
1349
-            1,
1350
-            $query_params,
1351
-            $columns_to_select
1352
-        );
1353
-        return empty($results) ? null : reset($results);
1354
-    }
1355
-
1356
-
1357
-    /**
1358
-     * Returns the a consecutive number of items in sequence from the given
1359
-     * value as found in the database matching the given query conditions.
1360
-     *
1361
-     * @param mixed  $current_field_value   Value used for the reference point.
1362
-     * @param string $operand               What operand is used for the sequence.
1363
-     * @param string $field_to_order_by     What field is used for the reference point.
1364
-     * @param int    $limit                 How many to return.
1365
-     * @param array  $query_params          Extra conditions on the query.
1366
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1367
-     *                                      otherwise you can indicate just the columns you want returned.
1368
-     * @return EE_Base_Class[]|array
1369
-     * @throws EE_Error
1370
-     * @throws ReflectionException
1371
-     */
1372
-    protected function _get_consecutive(
1373
-        $current_field_value,
1374
-        $operand = '>',
1375
-        $field_to_order_by = null,
1376
-        $limit = 1,
1377
-        $query_params = [],
1378
-        $columns_to_select = null
1379
-    ) {
1380
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1381
-        if (empty($field_to_order_by)) {
1382
-            if ($this->has_primary_key_field()) {
1383
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1384
-            } else {
1385
-                if (WP_DEBUG) {
1386
-                    throw new EE_Error(
1387
-                        esc_html__(
1388
-                            'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1389
-                            'event_espresso'
1390
-                        )
1391
-                    );
1392
-                }
1393
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1394
-                return [];
1395
-            }
1396
-        }
1397
-        if (! is_array($query_params)) {
1398
-            EE_Error::doing_it_wrong(
1399
-                'EEM_Base::_get_consecutive',
1400
-                sprintf(
1401
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1402
-                    gettype($query_params)
1403
-                ),
1404
-                '4.6.0'
1405
-            );
1406
-            $query_params = [];
1407
-        }
1408
-        // let's add the where query param for consecutive look up.
1409
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1410
-        $query_params['limit']                 = $limit;
1411
-        // set direction
1412
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1413
-        $query_params['order_by'] = $operand === '>'
1414
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1415
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1416
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1417
-        if (empty($columns_to_select)) {
1418
-            return $this->get_all($query_params);
1419
-        }
1420
-        // getting just the fields
1421
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * This sets the _timezone property after model object has been instantiated.
1427
-     *
1428
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1429
-     */
1430
-    public function set_timezone($timezone = '')
1431
-    {
1432
-        static $set_in_progress = false;
1433
-        // if incoming timezone string is empty, then use the existing
1434
-        $valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1435
-            ? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1436
-            : $this->_timezone;
1437
-        // do NOT set the timezone if we are already in the process of setting the timezone
1438
-        // OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1439
-        // OR the existing timezone is already set and the validated value is the same as the existing timezone
1440
-        if (
1441
-            $set_in_progress
1442
-            || (
1443
-                ! empty($this->_timezone)
1444
-                && (
1445
-                    empty($timezone) || $valid_timezone === $this->_timezone
1446
-                )
1447
-            )
1448
-        ) {
1449
-            return;
1450
-        }
1451
-        $set_in_progress = true;
1452
-        $this->_timezone = $valid_timezone ?: EEH_DTT_Helper::get_valid_timezone_string();
1453
-        // note we need to loop through relations and set the timezone on those objects as well.
1454
-        foreach ($this->_model_relations as $relation) {
1455
-            $relation->set_timezone($this->_timezone);
1456
-        }
1457
-        // and finally we do the same for any datetime fields
1458
-        foreach ($this->_fields as $field) {
1459
-            if ($field instanceof EE_Datetime_Field) {
1460
-                $field->set_timezone($this->_timezone);
1461
-            }
1462
-        }
1463
-        $set_in_progress = false;
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This just returns whatever is set for the current timezone.
1469
-     *
1470
-     * @access public
1471
-     * @return string
1472
-     */
1473
-    public function get_timezone()
1474
-    {
1475
-        if (empty($this->_timezone)) {
1476
-            $this->set_timezone();
1477
-        }
1478
-        return $this->_timezone;
1479
-    }
1480
-
1481
-
1482
-    /**
1483
-     * This returns the date formats set for the given field name and also ensures that
1484
-     * $this->_timezone property is set correctly.
1485
-     *
1486
-     * @param string $field_name The name of the field the formats are being retrieved for.
1487
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488
-     * @return array formats in an array with the date format first, and the time format last.
1489
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1490
-     * @since 4.6.x
1491
-     */
1492
-    public function get_formats_for($field_name, $pretty = false)
1493
-    {
1494
-        $field_settings = $this->field_settings_for($field_name);
1495
-        // if not a valid EE_Datetime_Field then throw error
1496
-        if (! $field_settings instanceof EE_Datetime_Field) {
1497
-            throw new EE_Error(
1498
-                sprintf(
1499
-                    esc_html__(
1500
-                        'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1501
-                        'event_espresso'
1502
-                    ),
1503
-                    $field_name
1504
-                )
1505
-            );
1506
-        }
1507
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1508
-        $field_timezone = $field_settings->get_timezone();
1509
-        if (empty($this->_timezone && $field_timezone)) {
1510
-            $this->set_timezone();
1511
-        } else {
1512
-            // or vice versa if the field TZ isn't set
1513
-            $model_timezone = $this->get_timezone();
1514
-            $field_settings->set_timezone($model_timezone);
1515
-        }
1516
-
1517
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1518
-    }
1519
-
1520
-
1521
-    /**
1522
-     * This returns the current time in a format setup for a query on this model.
1523
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
-     * it will return:
1525
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field
1526
-     *    for the given field for NOW
1527
-     *  - or a unix timestamp (equivalent to time())
1528
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
-     *
1532
-     * @param string $field_name    The field the current time is needed for.
1533
-     * @param bool $timestamp       True means to return a unix timestamp.
1534
-     *                              Otherwise a formatted string matching the set format for the field
1535
-     *                              in the set timezone will be returned.
1536
-     * @param string $what          Whether to return the string in just the time format, the date format, or both.
1537
-     * @return string               If the given field_name is not of the EE_Datetime_Field type,
1538
-     *                              then an EE_Error exception is triggered.
1539
-     * @throws EE_Error             If the given field_name is not of the EE_Datetime_Field type.
1540
-     * @throws Exception
1541
-     * @since 4.6.x
1542
-     */
1543
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1544
-    {
1545
-        $formats  = $this->get_formats_for($field_name);
1546
-        $DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1547
-        if ($timestamp) {
1548
-            return $DateTime->format('U');
1549
-        }
1550
-        // not returning timestamp, so return formatted string in timezone.
1551
-        switch ($what) {
1552
-            case 'time':
1553
-                return $DateTime->format($formats[1]);
1554
-            case 'date':
1555
-                return $DateTime->format($formats[0]);
1556
-            default:
1557
-                return $DateTime->format(implode(' ', $formats));
1558
-        }
1559
-    }
1560
-
1561
-
1562
-    /**
1563
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1564
-     * for the model are.  Returns a DateTime object.
1565
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1566
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1567
-     * ignored.
1568
-     *
1569
-     * @param string $field_name    The field being setup.
1570
-     * @param string $timestring    The date time string being used.
1571
-     * @param string $format        The format for the time string.
1572
-     * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1573
-     *                              the blog.  If this is not the case, then it can be specified here.
1574
-     *                              If incoming format is 'U', this is ignored.
1575
-     * @return DbSafeDateTime
1576
-     * @throws EE_Error
1577
-     * @throws Exception
1578
-     */
1579
-    public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1580
-    {
1581
-        // just using this to ensure the timezone is set correctly internally
1582
-        $this->get_formats_for($field_name);
1583
-        $timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1584
-        $db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1585
-        EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1586
-        return $db_safe_datetime;
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
-     *
1593
-     * @return EE_Table_Base[]
1594
-     */
1595
-    public function get_tables()
1596
-    {
1597
-        return $this->_tables;
1598
-    }
1599
-
1600
-
1601
-    /**
1602
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1603
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1604
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1605
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1606
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1607
-     * model object with EVT_ID = 1
1608
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1609
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1610
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1611
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1612
-     * are not specified)
1613
-     *
1614
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1615
-     *                                         columns!), values are strings, integers, floats, and maybe arrays if
1616
-     *                                         they
1617
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1620
-     *                                         ID=34, we'd use this method as follows:
1621
-     *                                         EEM_Transaction::instance()->update(
1622
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
-     *                                         array(array('TXN_ID'=>34)));
1624
-     * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1625
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1626
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1627
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1628
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1629
-     *                                         TRUE, it is assumed that you've already called
1630
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1631
-     *                                         malicious javascript. However, if
1632
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1633
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1634
-     *                                         and every other field, before insertion. We provide this parameter
1635
-     *                                         because model objects perform their prepare_for_set function on all
1636
-     *                                         their values, and so don't need to be called again (and in many cases,
1637
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1638
-     *                                         prepare_for_set method...)
1639
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1640
-     *                                         in this model's entity map according to $fields_n_values that match
1641
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1642
-     *                                         by setting this to FALSE, but be aware that model objects being used
1643
-     *                                         could get out-of-sync with the database
1644
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1645
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1646
-     *                                         bad)
1647
-     * @throws EE_Error
1648
-     * @throws ReflectionException
1649
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
-     */
1651
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
-    {
1653
-        if (! is_array($query_params)) {
1654
-            EE_Error::doing_it_wrong(
1655
-                'EEM_Base::update',
1656
-                sprintf(
1657
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1658
-                    gettype($query_params)
1659
-                ),
1660
-                '4.6.0'
1661
-            );
1662
-            $query_params = [];
1663
-        }
1664
-        /**
1665
-         * Action called before a model update call has been made.
1666
-         *
1667
-         * @param EEM_Base $model
1668
-         * @param array    $fields_n_values the updated fields and their new values
1669
-         * @param array    $query_params
1670
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1671
-         */
1672
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1673
-        /**
1674
-         * Filters the fields about to be updated given the query parameters. You can provide the
1675
-         * $query_params to $this->get_all() to find exactly which records will be updated
1676
-         *
1677
-         * @param array    $fields_n_values fields and their new values
1678
-         * @param EEM_Base $model           the model being queried
1679
-         * @param array    $query_params
1680
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1681
-         */
1682
-        $fields_n_values = (array)apply_filters(
1683
-            'FHEE__EEM_Base__update__fields_n_values',
1684
-            $fields_n_values,
1685
-            $this,
1686
-            $query_params
1687
-        );
1688
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1689
-        // to do that, for each table, verify that it's PK isn't null.
1690
-        $tables = $this->get_tables();
1691
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1692
-        // NOTE: we should make this code more efficient by NOT querying twice
1693
-        // before the real update, but that needs to first go through ALPHA testing
1694
-        // as it's dangerous. says Mike August 8 2014
1695
-        // we want to make sure the default_where strategy is ignored
1696
-        $this->_ignore_where_strategy = true;
1697
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1698
-        foreach ($wpdb_select_results as $wpdb_result) {
1699
-            // type cast stdClass as array
1700
-            $wpdb_result = (array)$wpdb_result;
1701
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1702
-            if ($this->has_primary_key_field()) {
1703
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1704
-            } else {
1705
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1706
-                $main_table_pk_value = null;
1707
-            }
1708
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1709
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1710
-            if (count($tables) > 1) {
1711
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1712
-                // in that table, and so we'll want to insert one
1713
-                foreach ($tables as $table_obj) {
1714
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1715
-                    // if there is no private key for this table on the results, it means there's no entry
1716
-                    // in this table, right? so insert a row in the current table, using any fields available
1717
-                    if (
1718
-                    ! (array_key_exists($this_table_pk_column, $wpdb_result)
1719
-                       && $wpdb_result[ $this_table_pk_column ])
1720
-                    ) {
1721
-                        $success = $this->_insert_into_specific_table(
1722
-                            $table_obj,
1723
-                            $fields_n_values,
1724
-                            $main_table_pk_value
1725
-                        );
1726
-                        // if we died here, report the error
1727
-                        if (! $success) {
1728
-                            return false;
1729
-                        }
1730
-                    }
1731
-                }
1732
-            }
1733
-            // let's make sure default_where strategy is followed now
1734
-            $this->_ignore_where_strategy = false;
1735
-        }
1736
-        // if we want to keep model objects in sync, AND
1737
-        // if this wasn't called from a model object (to update itself)
1738
-        // then we want to make sure we keep all the existing
1739
-        // model objects in sync with the db
1740
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1741
-            if ($this->has_primary_key_field()) {
1742
-                $model_objs_affected_ids = $this->get_col($query_params);
1743
-            } else {
1744
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1745
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1746
-                $model_objs_affected_ids     = [];
1747
-                foreach ($models_affected_key_columns as $row) {
1748
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1749
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1750
-                }
1751
-            }
1752
-            if (! $model_objs_affected_ids) {
1753
-                // wait wait wait- if nothing was affected let's stop here
1754
-                return 0;
1755
-            }
1756
-            foreach ($model_objs_affected_ids as $id) {
1757
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1758
-                if ($model_obj_in_entity_map) {
1759
-                    foreach ($fields_n_values as $field => $new_value) {
1760
-                        $model_obj_in_entity_map->set($field, $new_value);
1761
-                    }
1762
-                }
1763
-            }
1764
-            // if there is a primary key on this model, we can now do a slight optimization
1765
-            if ($this->has_primary_key_field()) {
1766
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1767
-                $query_params = [
1768
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1769
-                    'limit'                    => count($model_objs_affected_ids),
1770
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1771
-                ];
1772
-            }
1773
-        }
1774
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1776
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1777
-                            . $model_query_info->get_where_sql();
1778
-        // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1779
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1780
-        /**
1781
-         * Action called after a model update call has been made.
1782
-         *
1783
-         * @param EEM_Base $model
1784
-         * @param array    $fields_n_values the updated fields and their new values
1785
-         * @param array    $query_params
1786
-         * @param int      $rows_affected
1787
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1788
-         */
1789
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1790
-        return $rows_affected;// how many supposedly got updated
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1796
-     * are teh values of the field specified (or by default the primary key field)
1797
-     * that matched the query params. Note that you should pass the name of the
1798
-     * model FIELD, not the database table's column name.
1799
-     *
1800
-     * @param array  $query_params
1801
-     * @param string $field_to_select
1802
-     * @return array just like $wpdb->get_col()
1803
-     * @throws EE_Error
1804
-     * @throws ReflectionException
1805
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1806
-     */
1807
-    public function get_col($query_params = [], $field_to_select = null)
1808
-    {
1809
-        if ($field_to_select) {
1810
-            $field = $this->field_settings_for($field_to_select);
1811
-        } elseif ($this->has_primary_key_field()) {
1812
-            $field = $this->get_primary_key_field();
1813
-        } else {
1814
-            $field_settings = $this->field_settings();
1815
-            // no primary key, just grab the first column
1816
-            $field = reset($field_settings);
1817
-        }
1818
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1819
-        $select_expressions = $field->get_qualified_column();
1820
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1821
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1822
-    }
1823
-
1824
-
1825
-    /**
1826
-     * Returns a single column value for a single row from the database
1827
-     *
1828
-     * @param array  $query_params
1829
-     * @param string $field_to_select
1830
-     * @return string
1831
-     * @throws EE_Error
1832
-     * @throws ReflectionException
1833
-     * @see EEM_Base::get_col()
1834
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1835
-     */
1836
-    public function get_var($query_params = [], $field_to_select = null)
1837
-    {
1838
-        $query_params['limit'] = 1;
1839
-        $col                   = $this->get_col($query_params, $field_to_select);
1840
-        if (! empty($col)) {
1841
-            return reset($col);
1842
-        }
1843
-        return null;
1844
-    }
1845
-
1846
-
1847
-    /**
1848
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1849
-     * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1850
-     * injection, but currently no further filtering is done
1851
-     *
1852
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1853
-     *                               be updated to in the DB
1854
-     * @return string of SQL
1855
-     * @throws EE_Error
1856
-     * @global      $wpdb
1857
-     */
1858
-    public function _construct_update_sql($fields_n_values)
1859
-    {
1860
-        global $wpdb;
1861
-        $cols_n_values = [];
1862
-        foreach ($fields_n_values as $field_name => $value) {
1863
-            $field_obj = $this->field_settings_for($field_name);
1864
-            // if the value is NULL, we want to assign the value to that.
1865
-            // wpdb->prepare doesn't really handle that properly
1866
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1867
-            $value_sql       = $prepared_value === null
1868
-                ? 'NULL'
1869
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1870
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1871
-        }
1872
-        return implode(",", $cols_n_values);
1873
-    }
1874
-
1875
-
1876
-    /**
1877
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1878
-     * Performs a HARD delete, meaning the database row should always be removed,
1879
-     * not just have a flag field on it switched
1880
-     * Wrapper for EEM_Base::delete_permanently()
1881
-     *
1882
-     * @param mixed   $id
1883
-     * @param boolean $allow_blocking
1884
-     * @return int the number of rows deleted
1885
-     * @throws EE_Error
1886
-     * @throws ReflectionException
1887
-     */
1888
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1889
-    {
1890
-        return $this->delete_permanently(
1891
-            [
1892
-                [$this->get_primary_key_field()->get_name() => $id],
1893
-                'limit' => 1,
1894
-            ],
1895
-            $allow_blocking
1896
-        );
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
-     * Wrapper for EEM_Base::delete()
1903
-     *
1904
-     * @param mixed   $id
1905
-     * @param boolean $allow_blocking
1906
-     * @return int the number of rows deleted
1907
-     * @throws EE_Error
1908
-     * @throws ReflectionException
1909
-     */
1910
-    public function delete_by_ID($id, $allow_blocking = true)
1911
-    {
1912
-        return $this->delete(
1913
-            [
1914
-                [$this->get_primary_key_field()->get_name() => $id],
1915
-                'limit' => 1,
1916
-            ],
1917
-            $allow_blocking
1918
-        );
1919
-    }
1920
-
1921
-
1922
-    /**
1923
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1924
-     * meaning if the model has a field that indicates its been "trashed" or
1925
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1926
-     *
1927
-     * @param array   $query_params
1928
-     * @param boolean $allow_blocking
1929
-     * @return int how many rows got deleted
1930
-     * @throws EE_Error
1931
-     * @throws ReflectionException
1932
-     * @see EEM_Base::delete_permanently
1933
-     */
1934
-    public function delete($query_params, $allow_blocking = true)
1935
-    {
1936
-        return $this->delete_permanently($query_params, $allow_blocking);
1937
-    }
1938
-
1939
-
1940
-    /**
1941
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1942
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1943
-     * as archived, not actually deleted
1944
-     *
1945
-     * @param array   $query_params
1946
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1947
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1948
-     *                                deletes regardless of other objects which may depend on it. Its generally
1949
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1950
-     *                                DB
1951
-     * @return int how many rows got deleted
1952
-     * @throws EE_Error
1953
-     * @throws ReflectionException
1954
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1955
-     */
1956
-    public function delete_permanently($query_params, $allow_blocking = true)
1957
-    {
1958
-        /**
1959
-         * Action called just before performing a real deletion query. You can use the
1960
-         * model and its $query_params to find exactly which items will be deleted
1961
-         *
1962
-         * @param EEM_Base $model
1963
-         * @param array    $query_params
1964
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1965
-         *                                 to block (prevent) this deletion
1966
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1967
-         */
1968
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1969
-        // some MySQL databases may be running safe mode, which may restrict
1970
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1971
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1972
-        // to delete them
1973
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1974
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1975
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1976
-            $columns_and_ids_for_deleting
1977
-        );
1978
-        /**
1979
-         * Allows client code to act on the items being deleted before the query is actually executed.
1980
-         *
1981
-         * @param EEM_Base $this                            The model instance being acted on.
1982
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1983
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1984
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1985
-         *                                                  derived from the incoming query parameters.
1986
-         * @see details on the structure of this array in the phpdocs
1987
-         *                                                  for the `_get_ids_for_delete_method`
1988
-         *
1989
-         */
1990
-        do_action(
1991
-            'AHEE__EEM_Base__delete__before_query',
1992
-            $this,
1993
-            $query_params,
1994
-            $allow_blocking,
1995
-            $columns_and_ids_for_deleting
1996
-        );
1997
-        if ($deletion_where_query_part) {
1998
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1999
-            $table_aliases    = implode(', ', array_keys($this->_tables));
2000
-            $SQL              = "DELETE " . $table_aliases
2001
-                                . " FROM " . $model_query_info->get_full_join_sql()
2002
-                                . " WHERE " . $deletion_where_query_part;
2003
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2004
-        } else {
2005
-            $rows_deleted = 0;
2006
-        }
2007
-
2008
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2009
-        // there was no error with the delete query.
2010
-        if (
2011
-            $this->has_primary_key_field()
2012
-            && $rows_deleted !== false
2013
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2014
-        ) {
2015
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2016
-            foreach ($ids_for_removal as $id) {
2017
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2018
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2019
-                }
2020
-            }
2021
-
2022
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2023
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2024
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2025
-            // (although it is possible).
2026
-            // Note this can be skipped by using the provided filter and returning false.
2027
-            if (
2028
-            apply_filters(
2029
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2030
-                ! $this instanceof EEM_Extra_Meta,
2031
-                $this
2032
-            )
2033
-            ) {
2034
-                EEM_Extra_Meta::instance()->delete_permanently(
2035
-                    [
2036
-                        0 => [
2037
-                            'EXM_type' => $this->get_this_model_name(),
2038
-                            'OBJ_ID'   => [
2039
-                                'IN',
2040
-                                $ids_for_removal,
2041
-                            ],
2042
-                        ],
2043
-                    ]
2044
-                );
2045
-            }
2046
-        }
2047
-
2048
-        /**
2049
-         * Action called just after performing a real deletion query. Although at this point the
2050
-         * items should have been deleted
2051
-         *
2052
-         * @param EEM_Base $model
2053
-         * @param array    $query_params
2054
-         * @param int      $rows_deleted
2055
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2056
-         */
2057
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;// how many supposedly got deleted
2059
-    }
2060
-
2061
-
2062
-    /**
2063
-     * Checks all the relations that throw error messages when there are blocking related objects
2064
-     * for related model objects. If there are any related model objects on those relations,
2065
-     * adds an EE_Error, and return true
2066
-     *
2067
-     * @param EE_Base_Class|int $this_model_obj_or_id
2068
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2069
-     *                                                 should be ignored when determining whether there are related
2070
-     *                                                 model objects which block this model object's deletion. Useful
2071
-     *                                                 if you know A is related to B and are considering deleting A,
2072
-     *                                                 but want to see if A has any other objects blocking its deletion
2073
-     *                                                 before removing the relation between A and B
2074
-     * @return boolean
2075
-     * @throws EE_Error
2076
-     * @throws ReflectionException
2077
-     */
2078
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
-    {
2080
-        // first, if $ignore_this_model_obj was supplied, get its model
2081
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
-            $ignored_model = $ignore_this_model_obj->get_model();
2083
-        } else {
2084
-            $ignored_model = null;
2085
-        }
2086
-        // now check all the relations of $this_model_obj_or_id and see if there
2087
-        // are any related model objects blocking it?
2088
-        $is_blocked = false;
2089
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2091
-                // if $ignore_this_model_obj was supplied, then for the query
2092
-                // on that model needs to be told to ignore $ignore_this_model_obj
2093
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
-                    $related_model_objects = $relation_obj->get_all_related(
2095
-                        $this_model_obj_or_id,
2096
-                        [
2097
-                            [
2098
-                                $ignored_model->get_primary_key_field()->get_name() => [
2099
-                                    '!=',
2100
-                                    $ignore_this_model_obj->ID(),
2101
-                                ],
2102
-                            ],
2103
-                        ]
2104
-                    );
2105
-                } else {
2106
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2107
-                }
2108
-                if ($related_model_objects) {
2109
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2110
-                    $is_blocked = true;
2111
-                }
2112
-            }
2113
-        }
2114
-        return $is_blocked;
2115
-    }
2116
-
2117
-
2118
-    /**
2119
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2120
-     *
2121
-     * @param array $row_results_for_deleting
2122
-     * @param bool  $allow_blocking
2123
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2124
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2125
-     *                              dimension array where the key is the fully qualified primary key column and the
2126
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2127
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2128
-     *                              be a two dimensional array where each element is a group of columns and values that
2129
-     *                              get deleted. Example: array(
2130
-     *                              0 => array(
2131
-     *                              'Term_Relationship.object_id' => 1
2132
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2133
-     *                              ),
2134
-     *                              1 => array(
2135
-     *                              'Term_Relationship.object_id' => 1
2136
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2137
-     *                              )
2138
-     *                              )
2139
-     * @throws EE_Error
2140
-     * @throws ReflectionException
2141
-     */
2142
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2143
-    {
2144
-        $ids_to_delete_indexed_by_column = [];
2145
-        if ($this->has_primary_key_field()) {
2146
-            $primary_table                   = $this->_get_main_table();
2147
-            $ids_to_delete_indexed_by_column = [];
2148
-            foreach ($row_results_for_deleting as $item_to_delete) {
2149
-                // before we mark this item for deletion,
2150
-                // make sure there's no related entities blocking its deletion (if we're checking)
2151
-                if (
2152
-                    $allow_blocking
2153
-                    && $this->delete_is_blocked_by_related_models(
2154
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2155
-                    )
2156
-                ) {
2157
-                    continue;
2158
-                }
2159
-                // primary table deletes
2160
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2161
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2162
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2163
-                }
2164
-            }
2165
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2166
-            $fields = $this->get_combined_primary_key_fields();
2167
-            foreach ($row_results_for_deleting as $item_to_delete) {
2168
-                $ids_to_delete_indexed_by_column_for_row = [];
2169
-                foreach ($fields as $cpk_field) {
2170
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2171
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2172
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2173
-                    }
2174
-                }
2175
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2176
-            }
2177
-        } else {
2178
-            // so there's no primary key and no combined key...
2179
-            // sorry, can't help you
2180
-            throw new EE_Error(
2181
-                sprintf(
2182
-                    esc_html__(
2183
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2184
-                        "event_espresso"
2185
-                    ),
2186
-                    get_class($this)
2187
-                )
2188
-            );
2189
-        }
2190
-        return $ids_to_delete_indexed_by_column;
2191
-    }
2192
-
2193
-
2194
-    /**
2195
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2196
-     * the corresponding query_part for the query performing the delete.
2197
-     *
2198
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2199
-     * @return string
2200
-     * @throws EE_Error
2201
-     */
2202
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2203
-    {
2204
-        $query_part = '';
2205
-        if (empty($ids_to_delete_indexed_by_column)) {
2206
-            return $query_part;
2207
-        } elseif ($this->has_primary_key_field()) {
2208
-            $query = [];
2209
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210
-                // make sure we have unique $ids
2211
-                $ids     = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2213
-            }
2214
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2216
-            $ways_to_identify_a_row = [];
2217
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218
-                $values_for_each_combined_primary_key_for_a_row = [];
2219
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2221
-                }
2222
-                $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2223
-                $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2224
-            }
2225
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2226
-        }
2227
-        return $query_part;
2228
-    }
2229
-
2230
-
2231
-    /**
2232
-     * Gets the model field by the fully qualified name
2233
-     *
2234
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2235
-     * @return EE_Model_Field_Base
2236
-     * @throws EE_Error
2237
-     */
2238
-    public function get_field_by_column($qualified_column_name)
2239
-    {
2240
-        foreach ($this->field_settings(true) as $field_obj) {
2241
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242
-                return $field_obj;
2243
-            }
2244
-        }
2245
-        throw new EE_Error(
2246
-            sprintf(
2247
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2248
-                $this->get_this_model_name(),
2249
-                $qualified_column_name
2250
-            )
2251
-        );
2252
-    }
2253
-
2254
-
2255
-    /**
2256
-     * Count all the rows that match criteria the model query params.
2257
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2258
-     * column
2259
-     *
2260
-     * @param array  $query_params
2261
-     * @param string $field_to_count field on model to count by (not column name)
2262
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2263
-     *                               that by the setting $distinct to TRUE;
2264
-     * @return int
2265
-     * @throws EE_Error
2266
-     * @throws ReflectionException
2267
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2268
-     */
2269
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2270
-    {
2271
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
-        if ($field_to_count) {
2273
-            $field_obj       = $this->field_settings_for($field_to_count);
2274
-            $column_to_count = $field_obj->get_qualified_column();
2275
-        } elseif ($this->has_primary_key_field()) {
2276
-            $pk_field_obj    = $this->get_primary_key_field();
2277
-            $column_to_count = $pk_field_obj->get_qualified_column();
2278
-        } else {
2279
-            // there's no primary key
2280
-            // if we're counting distinct items, and there's no primary key,
2281
-            // we need to list out the columns for distinction;
2282
-            // otherwise we can just use star
2283
-            if ($distinct) {
2284
-                $columns_to_use = [];
2285
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2286
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2287
-                }
2288
-                $column_to_count = implode(',', $columns_to_use);
2289
-            } else {
2290
-                $column_to_count = '*';
2291
-            }
2292
-        }
2293
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2294
-        $SQL             =
2295
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2297
-    }
2298
-
2299
-
2300
-    /**
2301
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2302
-     *
2303
-     * @param array  $query_params
2304
-     * @param string $field_to_sum name of field (array key in $_fields array)
2305
-     * @return float
2306
-     * @throws EE_Error
2307
-     * @throws ReflectionException
2308
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2309
-     */
2310
-    public function sum($query_params, $field_to_sum = null)
2311
-    {
2312
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2313
-        if ($field_to_sum) {
2314
-            $field_obj = $this->field_settings_for($field_to_sum);
2315
-        } else {
2316
-            $field_obj = $this->get_primary_key_field();
2317
-        }
2318
-        $column_to_count = $field_obj->get_qualified_column();
2319
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2320
-                           . $this->_construct_2nd_half_of_select_query($model_query_info);
2321
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2322
-        // $data_type       = $field_obj->get_wpdb_data_type();
2323
-        // if ($data_type === '%d' || $data_type === '%s') {
2324
-        //     return (float)$return_value;
2325
-        // }
2326
-        // must be %f
2327
-        return (float)$return_value;
2328
-    }
2329
-
2330
-
2331
-    /**
2332
-     * Just calls the specified method on $wpdb with the given arguments
2333
-     * Consolidates a little extra error handling code
2334
-     *
2335
-     * @param string $wpdb_method
2336
-     * @param array  $arguments_to_provide
2337
-     * @return mixed
2338
-     * @throws EE_Error
2339
-     * @throws ReflectionException
2340
-     * @global wpdb  $wpdb
2341
-     */
2342
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2343
-    {
2344
-        // if we're in maintenance mode level 2, DON'T run any queries
2345
-        // because level 2 indicates the database needs updating and
2346
-        // is probably out of sync with the code
2347
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2348
-            throw new EE_Error(
2349
-                esc_html__(
2350
-                    'Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.',
2351
-                    'event_espresso'
2352
-                )
2353
-            );
2354
-        }
2355
-        global $wpdb;
2356
-        if (! method_exists($wpdb, $wpdb_method)) {
2357
-            throw new EE_Error(
2358
-                sprintf(
2359
-                    esc_html__(
2360
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2361
-                        'event_espresso'
2362
-                    ),
2363
-                    $wpdb_method
2364
-                )
2365
-            );
2366
-        }
2367
-        $old_show_errors_value = $wpdb->show_errors;
2368
-        if (WP_DEBUG) {
2369
-            $wpdb->show_errors(false);
2370
-        }
2371
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2372
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2373
-        if (WP_DEBUG) {
2374
-            $wpdb->show_errors($old_show_errors_value);
2375
-            if (! empty($wpdb->last_error)) {
2376
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2377
-            }
2378
-            if ($result === false) {
2379
-                throw new EE_Error(
2380
-                    sprintf(
2381
-                        esc_html__(
2382
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2383
-                            'event_espresso'
2384
-                        ),
2385
-                        $wpdb_method,
2386
-                        var_export($arguments_to_provide, true)
2387
-                    )
2388
-                );
2389
-            }
2390
-        } elseif ($result === false) {
2391
-            EE_Error::add_error(
2392
-                sprintf(
2393
-                    esc_html__(
2394
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2395
-                        'event_espresso'
2396
-                    ),
2397
-                    $wpdb_method,
2398
-                    var_export($arguments_to_provide, true),
2399
-                    $wpdb->last_error
2400
-                ),
2401
-                __FILE__,
2402
-                __FUNCTION__,
2403
-                __LINE__
2404
-            );
2405
-        }
2406
-        return $result;
2407
-    }
2408
-
2409
-
2410
-    /**
2411
-     * Attempts to run the indicated WPDB method with the provided arguments,
2412
-     * and if there's an error tries to verify the DB is correct. Uses
2413
-     * the static property EEM_Base::$_db_verification_level to determine whether
2414
-     * we should try to fix the EE core db, the addons, or just give up
2415
-     *
2416
-     * @param string $wpdb_method
2417
-     * @param array  $arguments_to_provide
2418
-     * @return mixed
2419
-     * @throws EE_Error
2420
-     * @throws ReflectionException
2421
-     */
2422
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2423
-    {
2424
-        global $wpdb;
2425
-        $wpdb->last_error = null;
2426
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2427
-        // was there an error running the query? but we don't care on new activations
2428
-        // (we're going to setup the DB anyway on new activations)
2429
-        if (
2430
-            ($result === false || ! empty($wpdb->last_error))
2431
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2432
-        ) {
2433
-            switch (EEM_Base::$_db_verification_level) {
2434
-                case EEM_Base::db_verified_none:
2435
-                    // let's double-check core's DB
2436
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2437
-                    break;
2438
-                case EEM_Base::db_verified_core:
2439
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2440
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2441
-                    break;
2442
-                case EEM_Base::db_verified_addons:
2443
-                    // ummmm... you in trouble
2444
-                    return $result;
2445
-            }
2446
-            if (! empty($error_message)) {
2447
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2448
-                trigger_error($error_message);
2449
-            }
2450
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2451
-        }
2452
-        return $result;
2453
-    }
2454
-
2455
-
2456
-    /**
2457
-     * Verifies the EE core database is up-to-date and records that we've done it on
2458
-     * EEM_Base::$_db_verification_level
2459
-     *
2460
-     * @param string $wpdb_method
2461
-     * @param array  $arguments_to_provide
2462
-     * @return string
2463
-     * @throws EE_Error
2464
-     * @throws ReflectionException
2465
-     */
2466
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2467
-    {
2468
-        global $wpdb;
2469
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2470
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2471
-        $error_message                    = sprintf(
2472
-            esc_html__(
2473
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2474
-                'event_espresso'
2475
-            ),
2476
-            $wpdb->last_error,
2477
-            $wpdb_method,
2478
-            wp_json_encode($arguments_to_provide)
2479
-        );
2480
-        EE_System::instance()->initialize_db_if_no_migrations_required();
2481
-        return $error_message;
2482
-    }
2483
-
2484
-
2485
-    /**
2486
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2487
-     * EEM_Base::$_db_verification_level
2488
-     *
2489
-     * @param $wpdb_method
2490
-     * @param $arguments_to_provide
2491
-     * @return string
2492
-     * @throws EE_Error
2493
-     * @throws ReflectionException
2494
-     */
2495
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2496
-    {
2497
-        global $wpdb;
2498
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2499
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2500
-        $error_message                    = sprintf(
2501
-            esc_html__(
2502
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2503
-                'event_espresso'
2504
-            ),
2505
-            $wpdb->last_error,
2506
-            $wpdb_method,
2507
-            wp_json_encode($arguments_to_provide)
2508
-        );
2509
-        EE_System::instance()->initialize_addons();
2510
-        return $error_message;
2511
-    }
2512
-
2513
-
2514
-    /**
2515
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2516
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2517
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2518
-     * ..."
2519
-     *
2520
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2521
-     * @return string
2522
-     */
2523
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2524
-    {
2525
-        return " FROM " . $model_query_info->get_full_join_sql() .
2526
-               $model_query_info->get_where_sql() .
2527
-               $model_query_info->get_group_by_sql() .
2528
-               $model_query_info->get_having_sql() .
2529
-               $model_query_info->get_order_by_sql() .
2530
-               $model_query_info->get_limit_sql();
2531
-    }
2532
-
2533
-
2534
-    /**
2535
-     * Set to easily debug the next X queries ran from this model.
2536
-     *
2537
-     * @param int $count
2538
-     */
2539
-    public function show_next_x_db_queries($count = 1)
2540
-    {
2541
-        $this->_show_next_x_db_queries = $count;
2542
-    }
2543
-
2544
-
2545
-    /**
2546
-     * @param $sql_query
2547
-     */
2548
-    public function show_db_query_if_previously_requested($sql_query)
2549
-    {
2550
-        if ($this->_show_next_x_db_queries > 0) {
2551
-            echo $sql_query;
2552
-            $this->_show_next_x_db_queries--;
2553
-        }
2554
-    }
2555
-
2556
-
2557
-    /**
2558
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2559
-     * There are the 3 cases:
2560
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2561
-     * $otherModelObject has no ID, it is first saved.
2562
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2563
-     * has no ID, it is first saved.
2564
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2565
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2566
-     * join table
2567
-     *
2568
-     * @param EE_Base_Class                     /int $thisModelObject
2569
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2570
-     * @param string $relationName                     , key in EEM_Base::_relations
2571
-     *                                                 an attendee to a group, you also want to specify which role they
2572
-     *                                                 will have in that group. So you would use this parameter to
2573
-     *                                                 specify array('role-column-name'=>'role-id')
2574
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2575
-     *                                                 to for relation to methods that allow you to further specify
2576
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2577
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2578
-     *                                                 because these will be inserted in any new rows created as well.
2579
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2580
-     * @throws EE_Error
2581
-     */
2582
-    public function add_relationship_to(
2583
-        $id_or_obj,
2584
-        $other_model_id_or_obj,
2585
-        $relationName,
2586
-        $extra_join_model_fields_n_values = []
2587
-    ) {
2588
-        $relation_obj = $this->related_settings_for($relationName);
2589
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2590
-    }
2591
-
2592
-
2593
-    /**
2594
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2595
-     * There are the 3 cases:
2596
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2597
-     * error
2598
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2599
-     * an error
2600
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2601
-     *
2602
-     * @param EE_Base_Class /int $id_or_obj
2603
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2604
-     * @param string $relationName key in EEM_Base::_relations
2605
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2606
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2607
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2608
-     *                             because these will be inserted in any new rows created as well.
2609
-     * @return boolean of success
2610
-     * @throws EE_Error
2611
-     */
2612
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2613
-    {
2614
-        $relation_obj = $this->related_settings_for($relationName);
2615
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2616
-    }
2617
-
2618
-
2619
-    /**
2620
-     * @param mixed  $id_or_obj
2621
-     * @param string $relationName
2622
-     * @param array  $where_query_params
2623
-     * @param EE_Base_Class[] objects to which relations were removed
2624
-     * @return EE_Base_Class[]
2625
-     * @throws EE_Error
2626
-     */
2627
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2628
-    {
2629
-        $relation_obj = $this->related_settings_for($relationName);
2630
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2631
-    }
2632
-
2633
-
2634
-    /**
2635
-     * Gets all the related items of the specified $model_name, using $query_params.
2636
-     * Note: by default, we remove the "default query params"
2637
-     * because we want to get even deleted items etc.
2638
-     *
2639
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2640
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2641
-     * @param array  $query_params see github link below for more info
2642
-     * @return EE_Base_Class[]
2643
-     * @throws EE_Error
2644
-     * @throws ReflectionException
2645
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2646
-     */
2647
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2648
-    {
2649
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2650
-        $relation_settings = $this->related_settings_for($model_name);
2651
-        return $relation_settings->get_all_related($model_obj, $query_params);
2652
-    }
2653
-
2654
-
2655
-    /**
2656
-     * Deletes all the model objects across the relation indicated by $model_name
2657
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2658
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2659
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2660
-     *
2661
-     * @param EE_Base_Class|int|string $id_or_obj
2662
-     * @param string                   $model_name
2663
-     * @param array                    $query_params
2664
-     * @return int how many deleted
2665
-     * @throws EE_Error
2666
-     * @throws ReflectionException
2667
-     */
2668
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2669
-    {
2670
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2671
-        $relation_settings = $this->related_settings_for($model_name);
2672
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2673
-    }
2674
-
2675
-
2676
-    /**
2677
-     * Hard deletes all the model objects across the relation indicated by $model_name
2678
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2679
-     * the model objects can't be hard deleted because of blocking related model objects,
2680
-     * just does a soft-delete on them instead.
2681
-     *
2682
-     * @param EE_Base_Class|int|string $id_or_obj
2683
-     * @param string                   $model_name
2684
-     * @param array                    $query_params
2685
-     * @return int how many deleted
2686
-     * @throws EE_Error
2687
-     * @throws ReflectionException
2688
-     */
2689
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2690
-    {
2691
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2692
-        $relation_settings = $this->related_settings_for($model_name);
2693
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2694
-    }
2695
-
2696
-
2697
-    /**
2698
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2699
-     * unless otherwise specified in the $query_params
2700
-     *
2701
-     * @param int             /EE_Base_Class $id_or_obj
2702
-     * @param string $model_name     like 'Event', or 'Registration'
2703
-     * @param array  $query_params
2704
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2705
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2706
-     *                               that by the setting $distinct to TRUE;
2707
-     * @return int
2708
-     * @throws EE_Error
2709
-     * @throws ReflectionException
2710
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2711
-     */
2712
-    public function count_related(
2713
-        $id_or_obj,
2714
-        $model_name,
2715
-        $query_params = [],
2716
-        $field_to_count = null,
2717
-        $distinct = false
2718
-    ) {
2719
-        $related_model = $this->get_related_model_obj($model_name);
2720
-        // we're just going to use the query params on the related model's normal get_all query,
2721
-        // except add a condition to say to match the current mod
2722
-        if (! isset($query_params['default_where_conditions'])) {
2723
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2724
-        }
2725
-        $this_model_name                                                 = $this->get_this_model_name();
2726
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2727
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2728
-        return $related_model->count($query_params, $field_to_count, $distinct);
2729
-    }
2730
-
2731
-
2732
-    /**
2733
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2734
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2735
-     *
2736
-     * @param int           /EE_Base_Class $id_or_obj
2737
-     * @param string $model_name   like 'Event', or 'Registration'
2738
-     * @param array  $query_params
2739
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2740
-     * @return float
2741
-     * @throws EE_Error
2742
-     * @throws ReflectionException
2743
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2744
-     */
2745
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2746
-    {
2747
-        $related_model = $this->get_related_model_obj($model_name);
2748
-        if (! is_array($query_params)) {
2749
-            EE_Error::doing_it_wrong(
2750
-                'EEM_Base::sum_related',
2751
-                sprintf(
2752
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2753
-                    gettype($query_params)
2754
-                ),
2755
-                '4.6.0'
2756
-            );
2757
-            $query_params = [];
2758
-        }
2759
-        // we're just going to use the query params on the related model's normal get_all query,
2760
-        // except add a condition to say to match the current mod
2761
-        if (! isset($query_params['default_where_conditions'])) {
2762
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2763
-        }
2764
-        $this_model_name                                                 = $this->get_this_model_name();
2765
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2766
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2767
-        return $related_model->sum($query_params, $field_to_sum);
2768
-    }
2769
-
2770
-
2771
-    /**
2772
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2773
-     * $modelObject
2774
-     *
2775
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2776
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2777
-     * @param array               $query_params     see github link below for more info
2778
-     * @return EE_Base_Class
2779
-     * @throws EE_Error
2780
-     * @throws ReflectionException
2781
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2782
-     */
2783
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2784
-    {
2785
-        $query_params['limit'] = 1;
2786
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2787
-        if ($results) {
2788
-            return array_shift($results);
2789
-        }
2790
-        return null;
2791
-    }
2792
-
2793
-
2794
-    /**
2795
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2796
-     *
2797
-     * @return string
2798
-     */
2799
-    public function get_this_model_name()
2800
-    {
2801
-        return str_replace("EEM_", "", get_class($this));
2802
-    }
2803
-
2804
-
2805
-    /**
2806
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2807
-     *
2808
-     * @return EE_Any_Foreign_Model_Name_Field
2809
-     * @throws EE_Error
2810
-     */
2811
-    public function get_field_containing_related_model_name()
2812
-    {
2813
-        foreach ($this->field_settings(true) as $field) {
2814
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2815
-                $field_with_model_name = $field;
2816
-            }
2817
-        }
2818
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2819
-            throw new EE_Error(
2820
-                sprintf(
2821
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2822
-                    $this->get_this_model_name()
2823
-                )
2824
-            );
2825
-        }
2826
-        return $field_with_model_name;
2827
-    }
2828
-
2829
-
2830
-    /**
2831
-     * Inserts a new entry into the database, for each table.
2832
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2833
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2834
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2835
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2836
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2837
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2838
-     *
2839
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2840
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2841
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2842
-     *                              of EEM_Base)
2843
-     * @return int|string new primary key on main table that got inserted
2844
-     * @throws EE_Error
2845
-     * @throws ReflectionException
2846
-     */
2847
-    public function insert($field_n_values)
2848
-    {
2849
-        /**
2850
-         * Filters the fields and their values before inserting an item using the models
2851
-         *
2852
-         * @param array    $fields_n_values keys are the fields and values are their new values
2853
-         * @param EEM_Base $model           the model used
2854
-         */
2855
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2856
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2857
-            $main_table = $this->_get_main_table();
2858
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2859
-            if ($new_id !== false) {
2860
-                foreach ($this->_get_other_tables() as $other_table) {
2861
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2862
-                }
2863
-            }
2864
-            /**
2865
-             * Done just after attempting to insert a new model object
2866
-             *
2867
-             * @param EEM_Base $model           used
2868
-             * @param array    $fields_n_values fields and their values
2869
-             * @param int|string the              ID of the newly-inserted model object
2870
-             */
2871
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2872
-            return $new_id;
2873
-        }
2874
-        return false;
2875
-    }
2876
-
2877
-
2878
-    /**
2879
-     * Checks that the result would satisfy the unique indexes on this model
2880
-     *
2881
-     * @param array  $field_n_values
2882
-     * @param string $action
2883
-     * @return boolean
2884
-     * @throws EE_Error
2885
-     * @throws ReflectionException
2886
-     */
2887
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2888
-    {
2889
-        foreach ($this->unique_indexes() as $index_name => $index) {
2890
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2891
-            if ($this->exists([$uniqueness_where_params])) {
2892
-                EE_Error::add_error(
2893
-                    sprintf(
2894
-                        esc_html__(
2895
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2896
-                            "event_espresso"
2897
-                        ),
2898
-                        $action,
2899
-                        $this->_get_class_name(),
2900
-                        $index_name,
2901
-                        implode(",", $index->field_names()),
2902
-                        http_build_query($uniqueness_where_params)
2903
-                    ),
2904
-                    __FILE__,
2905
-                    __FUNCTION__,
2906
-                    __LINE__
2907
-                );
2908
-                return false;
2909
-            }
2910
-        }
2911
-        return true;
2912
-    }
2913
-
2914
-
2915
-    /**
2916
-     * Checks the database for an item that conflicts (ie, if this item were
2917
-     * saved to the DB would break some uniqueness requirement, like a primary key
2918
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2919
-     * can be either an EE_Base_Class or an array of fields n values
2920
-     *
2921
-     * @param EE_Base_Class|array $obj_or_fields_array
2922
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2923
-     *                                                 when looking for conflicts
2924
-     *                                                 (ie, if false, we ignore the model object's primary key
2925
-     *                                                 when finding "conflicts". If true, it's also considered).
2926
-     *                                                 Only works for INT primary key,
2927
-     *                                                 STRING primary keys cannot be ignored
2928
-     * @return EE_Base_Class|array
2929
-     * @throws EE_Error
2930
-     * @throws ReflectionException
2931
-     */
2932
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2933
-    {
2934
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2935
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2936
-        } elseif (is_array($obj_or_fields_array)) {
2937
-            $fields_n_values = $obj_or_fields_array;
2938
-        } else {
2939
-            throw new EE_Error(
2940
-                sprintf(
2941
-                    esc_html__(
2942
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2943
-                        "event_espresso"
2944
-                    ),
2945
-                    get_class($this),
2946
-                    $obj_or_fields_array
2947
-                )
2948
-            );
2949
-        }
2950
-        $query_params = [];
2951
-        if (
2952
-            $this->has_primary_key_field()
2953
-            && ($include_primary_key
2954
-                || $this->get_primary_key_field()
2955
-                   instanceof
2956
-                   EE_Primary_Key_String_Field)
2957
-            && isset($fields_n_values[ $this->primary_key_name() ])
2958
-        ) {
2959
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2960
-        }
2961
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2962
-            $uniqueness_where_params                              =
2963
-                array_intersect_key($fields_n_values, $unique_index->fields());
2964
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2965
-        }
2966
-        // if there is nothing to base this search on, then we shouldn't find anything
2967
-        if (empty($query_params)) {
2968
-            return [];
2969
-        }
2970
-        return $this->get_one($query_params);
2971
-    }
2972
-
2973
-
2974
-    /**
2975
-     * Like count, but is optimized and returns a boolean instead of an int
2976
-     *
2977
-     * @param array $query_params
2978
-     * @return boolean
2979
-     * @throws EE_Error
2980
-     * @throws ReflectionException
2981
-     */
2982
-    public function exists($query_params)
2983
-    {
2984
-        $query_params['limit'] = 1;
2985
-        return $this->count($query_params) > 0;
2986
-    }
2987
-
2988
-
2989
-    /**
2990
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2991
-     *
2992
-     * @param int|string $id
2993
-     * @return boolean
2994
-     * @throws EE_Error
2995
-     * @throws ReflectionException
2996
-     */
2997
-    public function exists_by_ID($id)
2998
-    {
2999
-        return $this->exists(
3000
-            [
3001
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3002
-                [
3003
-                    $this->primary_key_name() => $id,
3004
-                ],
3005
-            ]
3006
-        );
3007
-    }
3008
-
3009
-
3010
-    /**
3011
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3012
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3013
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3014
-     * on the main table)
3015
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3016
-     * cases where we want to call it directly rather than via insert().
3017
-     *
3018
-     * @access   protected
3019
-     * @param EE_Table_Base $table
3020
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3021
-     *                                       float
3022
-     * @param int           $new_id          for now we assume only int keys
3023
-     * @return int ID of new row inserted, or FALSE on failure
3024
-     * @throws EE_Error
3025
-     * @throws ReflectionException
3026
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3027
-     */
3028
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3029
-    {
3030
-        global $wpdb;
3031
-        $insertion_col_n_values = [];
3032
-        $format_for_insertion   = [];
3033
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3034
-        foreach ($fields_on_table as $field_obj) {
3035
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3036
-            if ($field_obj->is_auto_increment()) {
3037
-                continue;
3038
-            }
3039
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3040
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3041
-            if ($prepared_value !== null) {
3042
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3043
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3044
-            }
3045
-        }
3046
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3047
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3048
-            // so add the fk to the main table as a column
3049
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3050
-            $format_for_insertion[]                              =
3051
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3052
-        }
3053
-        // insert the new entry
3054
-        $result = $this->_do_wpdb_query(
3055
-            'insert',
3056
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3057
-        );
3058
-        if ($result === false) {
3059
-            return false;
3060
-        }
3061
-        // ok, now what do we return for the ID of the newly-inserted thing?
3062
-        if ($this->has_primary_key_field()) {
3063
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3064
-                return $wpdb->insert_id;
3065
-            }
3066
-            // it's not an auto-increment primary key, so
3067
-            // it must have been supplied
3068
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3069
-        }
3070
-        // we can't return a  primary key because there is none. instead return
3071
-        // a unique string indicating this model
3072
-        return $this->get_index_primary_key_string($fields_n_values);
3073
-    }
3074
-
3075
-
3076
-    /**
3077
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3078
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3079
-     * and there is no default, we pass it along. WPDB will take care of it)
3080
-     *
3081
-     * @param EE_Model_Field_Base $field_obj
3082
-     * @param array               $fields_n_values
3083
-     * @return mixed string|int|float depending on what the table column will be expecting
3084
-     * @throws EE_Error
3085
-     */
3086
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3087
-    {
3088
-        // if this field doesn't allow nullable, don't allow it
3089
-        if (
3090
-            ! $field_obj->is_nullable()
3091
-            && (
3092
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3093
-                || $fields_n_values[ $field_obj->get_name() ] === null
3094
-            )
3095
-        ) {
3096
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3097
-        }
3098
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3099
-            ? $fields_n_values[ $field_obj->get_name() ]
3100
-            : null;
3101
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3102
-    }
3103
-
3104
-
3105
-    /**
3106
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3107
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3108
-     * the field's prepare_for_set() method.
3109
-     *
3110
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3111
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3112
-     *                                   top of file)
3113
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3114
-     *                                   $value is a custom selection
3115
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3116
-     */
3117
-    private function _prepare_value_for_use_in_db($value, $field)
3118
-    {
3119
-        if ($field && $field instanceof EE_Model_Field_Base) {
3120
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3121
-            switch ($this->_values_already_prepared_by_model_object) {
3122
-                /** @noinspection PhpMissingBreakStatementInspection */
3123
-                case self::not_prepared_by_model_object:
3124
-                    $value = $field->prepare_for_set($value);
3125
-                // purposefully left out "return"
3126
-                case self::prepared_by_model_object:
3127
-                    /** @noinspection SuspiciousAssignmentsInspection */
3128
-                    $value = $field->prepare_for_use_in_db($value);
3129
-                case self::prepared_for_use_in_db:
3130
-                    // leave the value alone
3131
-            }
3132
-            return $value;
3133
-            // phpcs:enable
3134
-        }
3135
-        return $value;
3136
-    }
3137
-
3138
-
3139
-    /**
3140
-     * Returns the main table on this model
3141
-     *
3142
-     * @return EE_Primary_Table
3143
-     * @throws EE_Error
3144
-     */
3145
-    protected function _get_main_table()
3146
-    {
3147
-        foreach ($this->_tables as $table) {
3148
-            if ($table instanceof EE_Primary_Table) {
3149
-                return $table;
3150
-            }
3151
-        }
3152
-        throw new EE_Error(
3153
-            sprintf(
3154
-                esc_html__(
3155
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3156
-                    'event_espresso'
3157
-                ),
3158
-                get_class($this)
3159
-            )
3160
-        );
3161
-    }
3162
-
3163
-
3164
-    /**
3165
-     * table
3166
-     * returns EE_Primary_Table table name
3167
-     *
3168
-     * @return string
3169
-     * @throws EE_Error
3170
-     */
3171
-    public function table()
3172
-    {
3173
-        return $this->_get_main_table()->get_table_name();
3174
-    }
3175
-
3176
-
3177
-    /**
3178
-     * table
3179
-     * returns first EE_Secondary_Table table name
3180
-     *
3181
-     * @return string
3182
-     */
3183
-    public function second_table()
3184
-    {
3185
-        // grab second table from tables array
3186
-        $second_table = end($this->_tables);
3187
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * get_table_obj_by_alias
3193
-     * returns table name given it's alias
3194
-     *
3195
-     * @param string $table_alias
3196
-     * @return EE_Primary_Table | EE_Secondary_Table
3197
-     */
3198
-    public function get_table_obj_by_alias($table_alias = '')
3199
-    {
3200
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3201
-    }
3202
-
3203
-
3204
-    /**
3205
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3206
-     *
3207
-     * @return EE_Secondary_Table[]
3208
-     */
3209
-    protected function _get_other_tables()
3210
-    {
3211
-        $other_tables = [];
3212
-        foreach ($this->_tables as $table_alias => $table) {
3213
-            if ($table instanceof EE_Secondary_Table) {
3214
-                $other_tables[ $table_alias ] = $table;
3215
-            }
3216
-        }
3217
-        return $other_tables;
3218
-    }
3219
-
3220
-
3221
-    /**
3222
-     * Finds all the fields that correspond to the given table
3223
-     *
3224
-     * @param string $table_alias , array key in EEM_Base::_tables
3225
-     * @return EE_Model_Field_Base[]
3226
-     */
3227
-    public function _get_fields_for_table($table_alias)
3228
-    {
3229
-        return $this->_fields[ $table_alias ];
3230
-    }
3231
-
3232
-
3233
-    /**
3234
-     * Recurses through all the where parameters, and finds all the related models we'll need
3235
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3236
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3237
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3238
-     * related Registration, Transaction, and Payment models.
3239
-     *
3240
-     * @param array $query_params see github link below for more info
3241
-     * @return EE_Model_Query_Info_Carrier
3242
-     * @throws EE_Error
3243
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3244
-     */
3245
-    public function _extract_related_models_from_query($query_params)
3246
-    {
3247
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3248
-        if (array_key_exists(0, $query_params)) {
3249
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3250
-        }
3251
-        if (array_key_exists('group_by', $query_params)) {
3252
-            if (is_array($query_params['group_by'])) {
3253
-                $this->_extract_related_models_from_sub_params_array_values(
3254
-                    $query_params['group_by'],
3255
-                    $query_info_carrier,
3256
-                    'group_by'
3257
-                );
3258
-            } elseif (! empty($query_params['group_by'])) {
3259
-                $this->_extract_related_model_info_from_query_param(
3260
-                    $query_params['group_by'],
3261
-                    $query_info_carrier,
3262
-                    'group_by'
3263
-                );
3264
-            }
3265
-        }
3266
-        if (array_key_exists('having', $query_params)) {
3267
-            $this->_extract_related_models_from_sub_params_array_keys(
3268
-                $query_params[0],
3269
-                $query_info_carrier,
3270
-                'having'
3271
-            );
3272
-        }
3273
-        if (array_key_exists('order_by', $query_params)) {
3274
-            if (is_array($query_params['order_by'])) {
3275
-                $this->_extract_related_models_from_sub_params_array_keys(
3276
-                    $query_params['order_by'],
3277
-                    $query_info_carrier,
3278
-                    'order_by'
3279
-                );
3280
-            } elseif (! empty($query_params['order_by'])) {
3281
-                $this->_extract_related_model_info_from_query_param(
3282
-                    $query_params['order_by'],
3283
-                    $query_info_carrier,
3284
-                    'order_by'
3285
-                );
3286
-            }
3287
-        }
3288
-        if (array_key_exists('force_join', $query_params)) {
3289
-            $this->_extract_related_models_from_sub_params_array_values(
3290
-                $query_params['force_join'],
3291
-                $query_info_carrier,
3292
-                'force_join'
3293
-            );
3294
-        }
3295
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3296
-        return $query_info_carrier;
3297
-    }
3298
-
3299
-
3300
-    /**
3301
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3302
-     *
3303
-     * @param array                       $sub_query_params
3304
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3306
-     * @throws EE_Error
3307
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3308
-     */
3309
-    private function _extract_related_models_from_sub_params_array_keys(
3310
-        $sub_query_params,
3311
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
-        $query_param_type
3313
-    ) {
3314
-        if (! empty($sub_query_params)) {
3315
-            $sub_query_params = (array)$sub_query_params;
3316
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3317
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3318
-                $this->_extract_related_model_info_from_query_param(
3319
-                    $param,
3320
-                    $model_query_info_carrier,
3321
-                    $query_param_type
3322
-                );
3323
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3324
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3325
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3326
-                // of array('Registration.TXN_ID'=>23)
3327
-                $query_param_sans_stars =
3328
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3329
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3330
-                    if (! is_array($possibly_array_of_params)) {
3331
-                        throw new EE_Error(
3332
-                            sprintf(
3333
-                                esc_html__(
3334
-                                    "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3335
-                                    "event_espresso"
3336
-                                ),
3337
-                                $param,
3338
-                                $possibly_array_of_params
3339
-                            )
3340
-                        );
3341
-                    }
3342
-                    $this->_extract_related_models_from_sub_params_array_keys(
3343
-                        $possibly_array_of_params,
3344
-                        $model_query_info_carrier,
3345
-                        $query_param_type
3346
-                    );
3347
-                } elseif (
3348
-                    $query_param_type === 0 // ie WHERE
3349
-                    && is_array($possibly_array_of_params)
3350
-                    && isset($possibly_array_of_params[2])
3351
-                    && $possibly_array_of_params[2] == true
3352
-                ) {
3353
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3354
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3355
-                    // from which we should extract query parameters!
3356
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3357
-                        throw new EE_Error(
3358
-                            sprintf(
3359
-                                esc_html__(
3360
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3361
-                                    "event_espresso"
3362
-                                ),
3363
-                                $query_param_type,
3364
-                                implode(",", $possibly_array_of_params)
3365
-                            )
3366
-                        );
3367
-                    }
3368
-                    $this->_extract_related_model_info_from_query_param(
3369
-                        $possibly_array_of_params[1],
3370
-                        $model_query_info_carrier,
3371
-                        $query_param_type
3372
-                    );
3373
-                }
3374
-            }
3375
-        }
3376
-    }
3377
-
3378
-
3379
-    /**
3380
-     * For extracting related models from forced_joins, where the array values contain the info about what
3381
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3382
-     *
3383
-     * @param array                       $sub_query_params
3384
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3385
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3386
-     * @throws EE_Error
3387
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3388
-     */
3389
-    private function _extract_related_models_from_sub_params_array_values(
3390
-        $sub_query_params,
3391
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392
-        $query_param_type
3393
-    ) {
3394
-        if (! empty($sub_query_params)) {
3395
-            if (! is_array($sub_query_params)) {
3396
-                throw new EE_Error(
3397
-                    sprintf(
3398
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
-                        $sub_query_params
3400
-                    )
3401
-                );
3402
-            }
3403
-            foreach ($sub_query_params as $param) {
3404
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3405
-                $this->_extract_related_model_info_from_query_param(
3406
-                    $param,
3407
-                    $model_query_info_carrier,
3408
-                    $query_param_type
3409
-                );
3410
-            }
3411
-        }
3412
-    }
3413
-
3414
-
3415
-    /**
3416
-     * Extract all the query parts from  model query params
3417
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
-     * but use them in a different order. Eg, we need to know what models we are querying
3420
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
-     * other models before we can finalize the where clause SQL.
3422
-     *
3423
-     * @param array $query_params see github link below for more info
3424
-     * @return EE_Model_Query_Info_Carrier
3425
-     * @throws EE_Error
3426
-     * @throws ModelConfigurationException
3427
-     * @throws ReflectionException
3428
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3429
-     */
3430
-    public function _create_model_query_info_carrier($query_params)
3431
-    {
3432
-        if (! is_array($query_params)) {
3433
-            EE_Error::doing_it_wrong(
3434
-                'EEM_Base::_create_model_query_info_carrier',
3435
-                sprintf(
3436
-                    esc_html__(
3437
-                        '$query_params should be an array, you passed a variable of type %s',
3438
-                        'event_espresso'
3439
-                    ),
3440
-                    gettype($query_params)
3441
-                ),
3442
-                '4.6.0'
3443
-            );
3444
-            $query_params = [];
3445
-        }
3446
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3447
-        // first check if we should alter the query to account for caps or not
3448
-        // because the caps might require us to do extra joins
3449
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3450
-            $query_params[0] = array_replace_recursive(
3451
-                $query_params[0],
3452
-                $this->caps_where_conditions(
3453
-                    $query_params['caps']
3454
-                )
3455
-            );
3456
-        }
3457
-
3458
-        // check if we should alter the query to remove data related to protected
3459
-        // custom post types
3460
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3461
-            $where_param_key_for_password = $this->modelChainAndPassword();
3462
-            // only include if related to a cpt where no password has been set
3463
-            $query_params[0]['OR*nopassword'] = [
3464
-                $where_param_key_for_password       => '',
3465
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3466
-            ];
3467
-        }
3468
-        $query_object = $this->_extract_related_models_from_query($query_params);
3469
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
-        foreach ($query_params[0] as $key => $value) {
3471
-            if (is_int($key)) {
3472
-                throw new EE_Error(
3473
-                    sprintf(
3474
-                        esc_html__(
3475
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3476
-                            "event_espresso"
3477
-                        ),
3478
-                        $key,
3479
-                        var_export($value, true),
3480
-                        var_export($query_params, true),
3481
-                        get_class($this)
3482
-                    )
3483
-                );
3484
-            }
3485
-        }
3486
-        if (
3487
-            array_key_exists('default_where_conditions', $query_params)
3488
-            && ! empty($query_params['default_where_conditions'])
3489
-        ) {
3490
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3491
-        } else {
3492
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3493
-        }
3494
-        $query_params[0] = array_merge(
3495
-            $this->_get_default_where_conditions_for_models_in_query(
3496
-                $query_object,
3497
-                $use_default_where_conditions,
3498
-                $query_params[0]
3499
-            ),
3500
-            $query_params[0]
3501
-        );
3502
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3503
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3504
-        // So we need to setup a subquery and use that for the main join.
3505
-        // Note for now this only works on the primary table for the model.
3506
-        // So for instance, you could set the limit array like this:
3507
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3508
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3509
-            $query_object->set_main_model_join_sql(
3510
-                $this->_construct_limit_join_select(
3511
-                    $query_params['on_join_limit'][0],
3512
-                    $query_params['on_join_limit'][1]
3513
-                )
3514
-            );
3515
-        }
3516
-        // set limit
3517
-        if (array_key_exists('limit', $query_params)) {
3518
-            if (is_array($query_params['limit'])) {
3519
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3520
-                    $e = sprintf(
3521
-                        esc_html__(
3522
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3523
-                            "event_espresso"
3524
-                        ),
3525
-                        http_build_query($query_params['limit'])
3526
-                    );
3527
-                    throw new EE_Error($e . "|" . $e);
3528
-                }
3529
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3531
-            } elseif (! empty($query_params['limit'])) {
3532
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3533
-            }
3534
-        }
3535
-        // set order by
3536
-        if (array_key_exists('order_by', $query_params)) {
3537
-            if (is_array($query_params['order_by'])) {
3538
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3539
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3540
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3541
-                if (array_key_exists('order', $query_params)) {
3542
-                    throw new EE_Error(
3543
-                        sprintf(
3544
-                            esc_html__(
3545
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3546
-                                "event_espresso"
3547
-                            ),
3548
-                            get_class($this),
3549
-                            implode(", ", array_keys($query_params['order_by'])),
3550
-                            implode(", ", $query_params['order_by']),
3551
-                            $query_params['order']
3552
-                        )
3553
-                    );
3554
-                }
3555
-                $this->_extract_related_models_from_sub_params_array_keys(
3556
-                    $query_params['order_by'],
3557
-                    $query_object,
3558
-                    'order_by'
3559
-                );
3560
-                // assume it's an array of fields to order by
3561
-                $order_array = [];
3562
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3563
-                    $order         = $this->_extract_order($order);
3564
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3565
-                }
3566
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3567
-            } elseif (! empty($query_params['order_by'])) {
3568
-                $this->_extract_related_model_info_from_query_param(
3569
-                    $query_params['order_by'],
3570
-                    $query_object,
3571
-                    'order',
3572
-                    $query_params['order_by']
3573
-                );
3574
-                $order = isset($query_params['order'])
3575
-                    ? $this->_extract_order($query_params['order'])
3576
-                    : 'DESC';
3577
-                $query_object->set_order_by_sql(
3578
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3579
-                );
3580
-            }
3581
-        }
3582
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3583
-        if (
3584
-            ! array_key_exists('order_by', $query_params)
3585
-            && array_key_exists('order', $query_params)
3586
-            && ! empty($query_params['order'])
3587
-        ) {
3588
-            $pk_field = $this->get_primary_key_field();
3589
-            $order    = $this->_extract_order($query_params['order']);
3590
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3591
-        }
3592
-        // set group by
3593
-        if (array_key_exists('group_by', $query_params)) {
3594
-            if (is_array($query_params['group_by'])) {
3595
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3596
-                $group_by_array = [];
3597
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3598
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3599
-                }
3600
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3601
-            } elseif (! empty($query_params['group_by'])) {
3602
-                $query_object->set_group_by_sql(
3603
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3604
-                );
3605
-            }
3606
-        }
3607
-        // set having
3608
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3609
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3610
-        }
3611
-        // now, just verify they didn't pass anything wack
3612
-        foreach ($query_params as $query_key => $query_value) {
3613
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3614
-                throw new EE_Error(
3615
-                    sprintf(
3616
-                        esc_html__(
3617
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3618
-                            'event_espresso'
3619
-                        ),
3620
-                        $query_key,
3621
-                        get_class($this),
3622
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3623
-                        implode(',', $this->_allowed_query_params)
3624
-                    )
3625
-                );
3626
-            }
3627
-        }
3628
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3629
-        if (empty($main_model_join_sql)) {
3630
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3631
-        }
3632
-        return $query_object;
3633
-    }
3634
-
3635
-
3636
-    /**
3637
-     * Gets the where conditions that should be imposed on the query based on the
3638
-     * context (eg reading frontend, backend, edit or delete).
3639
-     *
3640
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3641
-     * @return array
3642
-     * @throws EE_Error
3643
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3644
-     */
3645
-    public function caps_where_conditions($context = self::caps_read)
3646
-    {
3647
-        EEM_Base::verify_is_valid_cap_context($context);
3648
-        $cap_where_conditions = [];
3649
-        $cap_restrictions     = $this->caps_missing($context);
3650
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3651
-            $cap_where_conditions = array_replace_recursive(
3652
-                $cap_where_conditions,
3653
-                $restriction_if_no_cap->get_default_where_conditions()
3654
-            );
3655
-        }
3656
-        return apply_filters(
3657
-            'FHEE__EEM_Base__caps_where_conditions__return',
3658
-            $cap_where_conditions,
3659
-            $this,
3660
-            $context,
3661
-            $cap_restrictions
3662
-        );
3663
-    }
3664
-
3665
-
3666
-    /**
3667
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3668
-     * otherwise throws an exception
3669
-     *
3670
-     * @param string $should_be_order_string
3671
-     * @return string either ASC, asc, DESC or desc
3672
-     * @throws EE_Error
3673
-     */
3674
-    private function _extract_order($should_be_order_string)
3675
-    {
3676
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3677
-            return $should_be_order_string;
3678
-        }
3679
-        throw new EE_Error(
3680
-            sprintf(
3681
-                esc_html__(
3682
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3683
-                    "event_espresso"
3684
-                ),
3685
-                get_class($this),
3686
-                $should_be_order_string
3687
-            )
3688
-        );
3689
-    }
3690
-
3691
-
3692
-    /**
3693
-     * Looks at all the models which are included in this query, and asks each
3694
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3695
-     * so they can be merged
3696
-     *
3697
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3698
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3699
-     *                                                                  'none' means NO default where conditions will
3700
-     *                                                                  be used AT ALL during this query.
3701
-     *                                                                  'other_models_only' means default where
3702
-     *                                                                  conditions from other models will be used, but
3703
-     *                                                                  not for this primary model. 'all', the default,
3704
-     *                                                                  means default where conditions will apply as
3705
-     *                                                                  normal
3706
-     * @param array                       $where_query_params
3707
-     * @return array
3708
-     * @throws EE_Error
3709
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3710
-     */
3711
-    private function _get_default_where_conditions_for_models_in_query(
3712
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3713
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3714
-        $where_query_params = []
3715
-    ) {
3716
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3717
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3718
-            throw new EE_Error(
3719
-                sprintf(
3720
-                    esc_html__(
3721
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3722
-                        "event_espresso"
3723
-                    ),
3724
-                    $use_default_where_conditions,
3725
-                    implode(", ", $allowed_used_default_where_conditions_values)
3726
-                )
3727
-            );
3728
-        }
3729
-        $universal_query_params = [];
3730
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3731
-            $universal_query_params = $this->_get_default_where_conditions();
3732
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3733
-            $universal_query_params = $this->_get_minimum_where_conditions();
3734
-        }
3735
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
-            $related_model = $this->get_related_model_obj($model_name);
3737
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
-                $related_model_universal_where_params =
3739
-                    $related_model->_get_default_where_conditions($model_relation_path);
3740
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3741
-                $related_model_universal_where_params =
3742
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3743
-            } else {
3744
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3745
-                continue;
3746
-            }
3747
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3748
-                $related_model_universal_where_params,
3749
-                $where_query_params,
3750
-                $related_model,
3751
-                $model_relation_path
3752
-            );
3753
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3754
-                $universal_query_params,
3755
-                $overrides
3756
-            );
3757
-        }
3758
-        return $universal_query_params;
3759
-    }
3760
-
3761
-
3762
-    /**
3763
-     * Determines whether or not we should use default where conditions for the model in question
3764
-     * (this model, or other related models).
3765
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3766
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3767
-     * We should use default where conditions on related models when they requested to use default where conditions
3768
-     * on all models, or specifically just on other related models
3769
-     *
3770
-     * @param      $default_where_conditions_value
3771
-     * @param bool $for_this_model false means this is for OTHER related models
3772
-     * @return bool
3773
-     */
3774
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3775
-    {
3776
-        return (
3777
-                   $for_this_model
3778
-                   && in_array(
3779
-                       $default_where_conditions_value,
3780
-                       [
3781
-                           EEM_Base::default_where_conditions_all,
3782
-                           EEM_Base::default_where_conditions_this_only,
3783
-                           EEM_Base::default_where_conditions_minimum_others,
3784
-                       ],
3785
-                       true
3786
-                   )
3787
-               )
3788
-               || (
3789
-                   ! $for_this_model
3790
-                   && in_array(
3791
-                       $default_where_conditions_value,
3792
-                       [
3793
-                           EEM_Base::default_where_conditions_all,
3794
-                           EEM_Base::default_where_conditions_others_only,
3795
-                       ],
3796
-                       true
3797
-                   )
3798
-               );
3799
-    }
3800
-
3801
-
3802
-    /**
3803
-     * Determines whether or not we should use default minimum conditions for the model in question
3804
-     * (this model, or other related models).
3805
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3806
-     * where conditions.
3807
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3808
-     * on this model or others
3809
-     *
3810
-     * @param      $default_where_conditions_value
3811
-     * @param bool $for_this_model false means this is for OTHER related models
3812
-     * @return bool
3813
-     */
3814
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3815
-    {
3816
-        return (
3817
-                   $for_this_model
3818
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3819
-               )
3820
-               || (
3821
-                   ! $for_this_model
3822
-                   && in_array(
3823
-                       $default_where_conditions_value,
3824
-                       [
3825
-                           EEM_Base::default_where_conditions_minimum_others,
3826
-                           EEM_Base::default_where_conditions_minimum_all,
3827
-                       ],
3828
-                       true
3829
-                   )
3830
-               );
3831
-    }
3832
-
3833
-
3834
-    /**
3835
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3836
-     * then we also add a special where condition which allows for that model's primary key
3837
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3838
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3839
-     *
3840
-     * @param array    $default_where_conditions
3841
-     * @param array    $provided_where_conditions
3842
-     * @param EEM_Base $model
3843
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3844
-     * @return array
3845
-     * @throws EE_Error
3846
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3847
-     */
3848
-    private function _override_defaults_or_make_null_friendly(
3849
-        $default_where_conditions,
3850
-        $provided_where_conditions,
3851
-        $model,
3852
-        $model_relation_path
3853
-    ) {
3854
-        $null_friendly_where_conditions = [];
3855
-        $none_overridden                = true;
3856
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3857
-        foreach ($default_where_conditions as $key => $val) {
3858
-            if (isset($provided_where_conditions[ $key ])) {
3859
-                $none_overridden = false;
3860
-            } else {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3862
-            }
3863
-        }
3864
-        if ($none_overridden && $default_where_conditions) {
3865
-            if ($model->has_primary_key_field()) {
3866
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3867
-                                                                                   . "."
3868
-                                                                                   . $model->primary_key_name() ] =
3869
-                    ['IS NULL'];
3870
-            }/*else{
40
+	/**
41
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
42
+	 */
43
+	const caps_read       = 'read';
44
+
45
+	const caps_read_admin = 'read_admin';
46
+
47
+	const caps_edit       = 'edit';
48
+
49
+	const caps_delete     = 'delete';
50
+
51
+
52
+	/**
53
+	 * constant used to show EEM_Base has not yet verified the db on this http request
54
+	 */
55
+	const db_verified_none = 0;
56
+
57
+	/**
58
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
59
+	 * but not the addons' dbs
60
+	 */
61
+	const db_verified_core = 1;
62
+
63
+	/**
64
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
65
+	 * the EE core db too)
66
+	 */
67
+	const db_verified_addons = 2;
68
+
69
+	/**
70
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
71
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
72
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
73
+	 */
74
+	const default_where_conditions_all = 'all';
75
+
76
+	/**
77
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
78
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
79
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
80
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
81
+	 *        models which share tables with other models, this can return data for the wrong model.
82
+	 */
83
+	const default_where_conditions_this_only = 'this_model_only';
84
+
85
+	/**
86
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
87
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
88
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
89
+	 */
90
+	const default_where_conditions_others_only = 'other_models_only';
91
+
92
+	/**
93
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
94
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
95
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
96
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
97
+	 *        (regardless of whether those events and venues are trashed)
98
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
99
+	 *        events.
100
+	 */
101
+	const default_where_conditions_minimum_all = 'minimum';
102
+
103
+	/**
104
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
105
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
106
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
107
+	 *        not)
108
+	 */
109
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
110
+
111
+	/**
112
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
113
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
114
+	 *        it's possible it will return table entries for other models. You should use
115
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
116
+	 */
117
+	const default_where_conditions_none = 'none';
118
+
119
+	/**
120
+	 * when $_values_already_prepared_by_model_object equals this, we assume
121
+	 * the data is just like form input that needs to have the model fields'
122
+	 * prepare_for_set and prepare_for_use_in_db called on it
123
+	 */
124
+	const not_prepared_by_model_object = 0;
125
+
126
+	/**
127
+	 * when $_values_already_prepared_by_model_object equals this, we
128
+	 * assume this value is coming from a model object and doesn't need to have
129
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
130
+	 */
131
+	const prepared_by_model_object = 1;
132
+
133
+	/**
134
+	 * when $_values_already_prepared_by_model_object equals this, we assume
135
+	 * the values are already to be used in the database (ie no processing is done
136
+	 * on them by the model's fields)
137
+	 */
138
+	const prepared_for_use_in_db = 2;
139
+
140
+	/**
141
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
142
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
143
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
144
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
145
+	 *
146
+	 * @var boolean
147
+	 */
148
+	private $_values_already_prepared_by_model_object = 0;
149
+
150
+
151
+	/**
152
+	 * @var string
153
+	 */
154
+	protected $singular_item = 'Item';
155
+
156
+	/**
157
+	 * @var string
158
+	 */
159
+	protected $plural_item = 'Items';
160
+
161
+	/**
162
+	 * array of EE_Table objects for defining which tables comprise this model.
163
+	 *
164
+	 * @type EE_Table_Base[] $_tables
165
+	 */
166
+	protected $_tables;
167
+
168
+	/**
169
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
170
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
171
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
172
+	 *
173
+	 * @var EE_Model_Field_Base[][] $_fields
174
+	 */
175
+	protected $_fields;
176
+
177
+	/**
178
+	 * array of different kinds of relations
179
+	 *
180
+	 * @var EE_Model_Relation_Base[] $_model_relations
181
+	 */
182
+	protected $_model_relations;
183
+
184
+	/**
185
+	 * @var EE_Index[] $_indexes
186
+	 */
187
+	protected $_indexes = [];
188
+
189
+	/**
190
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
191
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
192
+	 * by setting the same columns as used in these queries in the query yourself.
193
+	 *
194
+	 * @var EE_Default_Where_Conditions
195
+	 */
196
+	protected $_default_where_conditions_strategy;
197
+
198
+	/**
199
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
200
+	 * This is particularly useful when you want something between 'none' and 'default'
201
+	 *
202
+	 * @var EE_Default_Where_Conditions
203
+	 */
204
+	protected $_minimum_where_conditions_strategy;
205
+
206
+	/**
207
+	 * String describing how to find the "owner" of this model's objects.
208
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
209
+	 * But when there isn't, this indicates which related model, or transiently-related model,
210
+	 * has the foreign key to the wp_users table.
211
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
212
+	 * related to events, and events have a foreign key to wp_users.
213
+	 * On EEM_Transaction, this would be 'Transaction.Event'
214
+	 *
215
+	 * @var string
216
+	 */
217
+	protected $_model_chain_to_wp_user = '';
218
+
219
+	/**
220
+	 * String describing how to find the model with a password controlling access to this model. This property has the
221
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
222
+	 * This value is the path of models to follow to arrive at the model with the password field.
223
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
224
+	 * model with a password that should affect reading this on the front-end.
225
+	 * Eg this is an empty string for the Event model because it has a password.
226
+	 * This is null for the Registration model, because its event's password has no bearing on whether
227
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
228
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
229
+	 * should hide tickets for datetimes for events that have a password set.
230
+	 *
231
+	 * @var string |null
232
+	 */
233
+	protected $model_chain_to_password = null;
234
+
235
+	/**
236
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
237
+	 * don't need it (particularly CPT models)
238
+	 *
239
+	 * @var bool
240
+	 */
241
+	protected $_ignore_where_strategy = false;
242
+
243
+	/**
244
+	 * String used in caps relating to this model. Eg, if the caps relating to this
245
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
246
+	 *
247
+	 * @var string. If null it hasn't been initialized yet. If false then we
248
+	 * have indicated capabilities don't apply to this
249
+	 */
250
+	protected $_caps_slug = null;
251
+
252
+	/**
253
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
254
+	 * and next-level keys are capability names, and values are a
255
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
256
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
257
+	 * and then each capability in the corresponding sub-array that they're missing
258
+	 * adds the where conditions onto the query.
259
+	 *
260
+	 * @var array
261
+	 */
262
+	protected $_cap_restrictions = [
263
+		self::caps_read       => [],
264
+		self::caps_read_admin => [],
265
+		self::caps_edit       => [],
266
+		self::caps_delete     => [],
267
+	];
268
+
269
+	/**
270
+	 * Array defining which cap restriction generators to use to create default
271
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
272
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
273
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
274
+	 * automatically set this to false (not just null).
275
+	 *
276
+	 * @var EE_Restriction_Generator_Base[]
277
+	 */
278
+	protected $_cap_restriction_generators = [];
279
+
280
+	/**
281
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
282
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
283
+	 * maps to 'read' because when looking for relevant permissions we're going to use
284
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
285
+	 *
286
+	 * @var array
287
+	 */
288
+	protected $_cap_contexts_to_cap_action_map = [
289
+		self::caps_read       => 'read',
290
+		self::caps_read_admin => 'read',
291
+		self::caps_edit       => 'edit',
292
+		self::caps_delete     => 'delete',
293
+	];
294
+
295
+	/**
296
+	 * Timezone
297
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
298
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
299
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
300
+	 * EE_Datetime_Field data type will have access to it.
301
+	 *
302
+	 * @var string
303
+	 */
304
+	protected $_timezone;
305
+
306
+
307
+	/**
308
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
309
+	 * multisite.
310
+	 *
311
+	 * @var int
312
+	 */
313
+	protected static $_model_query_blog_id;
314
+
315
+	/**
316
+	 * A copy of _fields, except the array keys are the model names pointed to by
317
+	 * the field
318
+	 *
319
+	 * @var EE_Model_Field_Base[]
320
+	 */
321
+	private $_cache_foreign_key_to_fields = [];
322
+
323
+	/**
324
+	 * Cached list of all the fields on the model, indexed by their name
325
+	 *
326
+	 * @var EE_Model_Field_Base[]
327
+	 */
328
+	private $_cached_fields = null;
329
+
330
+	/**
331
+	 * Cached list of all the fields on the model, except those that are
332
+	 * marked as only pertinent to the database
333
+	 *
334
+	 * @var EE_Model_Field_Base[]
335
+	 */
336
+	private $_cached_fields_non_db_only = null;
337
+
338
+	/**
339
+	 * A cached reference to the primary key for quick lookup
340
+	 *
341
+	 * @var EE_Model_Field_Base
342
+	 */
343
+	private $_primary_key_field = null;
344
+
345
+	/**
346
+	 * Flag indicating whether this model has a primary key or not
347
+	 *
348
+	 * @var boolean
349
+	 */
350
+	protected $_has_primary_key_field = null;
351
+
352
+	/**
353
+	 * array in the format:  [ FK alias => full PK ]
354
+	 * where keys are local column name aliases for foreign keys
355
+	 * and values are the fully qualified column name for the primary key they represent
356
+	 *  ex:
357
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
358
+	 *
359
+	 * @var array $foreign_key_aliases
360
+	 */
361
+	protected $foreign_key_aliases = [];
362
+
363
+	/**
364
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
365
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
366
+	 * This should be true for models that deal with data that should exist independent of EE.
367
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
368
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
369
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
370
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
371
+	 *
372
+	 * @var boolean
373
+	 */
374
+	protected $_wp_core_model = false;
375
+
376
+	/**
377
+	 * @var bool stores whether this model has a password field or not.
378
+	 * null until initialized by hasPasswordField()
379
+	 */
380
+	protected $has_password_field;
381
+
382
+	/**
383
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
384
+	 */
385
+	protected $password_field;
386
+
387
+	/**
388
+	 *    List of valid operators that can be used for querying.
389
+	 * The keys are all operators we'll accept, the values are the real SQL
390
+	 * operators used
391
+	 *
392
+	 * @var array
393
+	 */
394
+	protected $_valid_operators = [
395
+		'='           => '=',
396
+		'<='          => '<=',
397
+		'<'           => '<',
398
+		'>='          => '>=',
399
+		'>'           => '>',
400
+		'!='          => '!=',
401
+		'LIKE'        => 'LIKE',
402
+		'like'        => 'LIKE',
403
+		'NOT_LIKE'    => 'NOT LIKE',
404
+		'not_like'    => 'NOT LIKE',
405
+		'NOT LIKE'    => 'NOT LIKE',
406
+		'not like'    => 'NOT LIKE',
407
+		'IN'          => 'IN',
408
+		'in'          => 'IN',
409
+		'NOT_IN'      => 'NOT IN',
410
+		'not_in'      => 'NOT IN',
411
+		'NOT IN'      => 'NOT IN',
412
+		'not in'      => 'NOT IN',
413
+		'between'     => 'BETWEEN',
414
+		'BETWEEN'     => 'BETWEEN',
415
+		'IS_NOT_NULL' => 'IS NOT NULL',
416
+		'is_not_null' => 'IS NOT NULL',
417
+		'IS NOT NULL' => 'IS NOT NULL',
418
+		'is not null' => 'IS NOT NULL',
419
+		'IS_NULL'     => 'IS NULL',
420
+		'is_null'     => 'IS NULL',
421
+		'IS NULL'     => 'IS NULL',
422
+		'is null'     => 'IS NULL',
423
+		'REGEXP'      => 'REGEXP',
424
+		'regexp'      => 'REGEXP',
425
+		'NOT_REGEXP'  => 'NOT REGEXP',
426
+		'not_regexp'  => 'NOT REGEXP',
427
+		'NOT REGEXP'  => 'NOT REGEXP',
428
+		'not regexp'  => 'NOT REGEXP',
429
+	];
430
+
431
+	/**
432
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
433
+	 *
434
+	 * @var array
435
+	 */
436
+	protected $_in_style_operators = ['IN', 'NOT IN'];
437
+
438
+	/**
439
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
440
+	 * '12-31-2012'"
441
+	 *
442
+	 * @var array
443
+	 */
444
+	protected $_between_style_operators = ['BETWEEN'];
445
+
446
+	/**
447
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
452
+
453
+	/**
454
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
455
+	 * on a join table.
456
+	 *
457
+	 * @var array
458
+	 */
459
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
460
+
461
+	/**
462
+	 * Allowed values for $query_params['order'] for ordering in queries
463
+	 *
464
+	 * @var array
465
+	 */
466
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
467
+
468
+	/**
469
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
470
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
471
+	 *
472
+	 * @var array
473
+	 */
474
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
475
+
476
+	/**
477
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
478
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
479
+	 *
480
+	 * @var array
481
+	 */
482
+	private $_allowed_query_params = [
483
+		0,
484
+		'limit',
485
+		'order_by',
486
+		'group_by',
487
+		'having',
488
+		'force_join',
489
+		'order',
490
+		'on_join_limit',
491
+		'default_where_conditions',
492
+		'caps',
493
+		'extra_selects',
494
+		'exclude_protected',
495
+	];
496
+
497
+	/**
498
+	 * All the data types that can be used in $wpdb->prepare statements.
499
+	 *
500
+	 * @var array
501
+	 */
502
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
503
+
504
+	/**
505
+	 * @var EE_Registry $EE
506
+	 */
507
+	protected $EE = null;
508
+
509
+
510
+	/**
511
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
512
+	 *
513
+	 * @var int
514
+	 */
515
+	protected $_show_next_x_db_queries = 0;
516
+
517
+	/**
518
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
519
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
520
+	 * WHERE, GROUP_BY, etc.
521
+	 *
522
+	 * @var CustomSelects
523
+	 */
524
+	protected $_custom_selections = [];
525
+
526
+	/**
527
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
528
+	 * caches every model object we've fetched from the DB on this request
529
+	 *
530
+	 * @var array
531
+	 */
532
+	protected $_entity_map;
533
+
534
+	/**
535
+	 * @var LoaderInterface $loader
536
+	 */
537
+	private static $loader;
538
+
539
+	/**
540
+	 * indicates whether an EEM_Base child has already re-verified the DB
541
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
542
+	 * looking like EEM_Base::db_verified_*
543
+	 *
544
+	 * @var int - 0 = none, 1 = core, 2 = addons
545
+	 */
546
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
547
+
548
+
549
+	/**
550
+	 * About all child constructors:
551
+	 * they should define the _tables, _fields and _model_relations arrays.
552
+	 * Should ALWAYS be called after child constructor.
553
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
554
+	 * finalizes constructing all the object's attributes.
555
+	 * Generally, rather than requiring a child to code
556
+	 * $this->_tables = array(
557
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
558
+	 *        ...);
559
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
560
+	 * each EE_Table has a function to set the table's alias after the constructor, using
561
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
562
+	 * do something similar.
563
+	 *
564
+	 * @param string $timezone
565
+	 * @throws EE_Error
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blog id for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				/** @var $table_obj EE_Secondary_Table */
599
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
600
+			}
601
+		}
602
+		/**
603
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
604
+		 * EE_Register_Model_Extension
605
+		 *
606
+		 * @param EE_Model_Field_Base[] $_fields
607
+		 */
608
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
609
+		$this->_invalidate_field_caches();
610
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
611
+			if (! array_key_exists($table_alias, $this->_tables)) {
612
+				throw new EE_Error(
613
+					sprintf(
614
+						esc_html__(
615
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
616
+							'event_espresso'
617
+						),
618
+						$table_alias,
619
+						implode(",", $this->_fields)
620
+					)
621
+				);
622
+			}
623
+			foreach ($fields_for_table as $field_name => $field_obj) {
624
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
625
+				// primary key field base has a slightly different _construct_finalize
626
+				/** @var $field_obj EE_Model_Field_Base */
627
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
628
+			}
629
+		}
630
+		// everything is related to Extra_Meta
631
+		if (get_class($this) !== 'EEM_Extra_Meta') {
632
+			// make extra meta related to everything, but don't block deleting things just
633
+			// because they have related extra meta info. For now just orphan those extra meta
634
+			// in the future we should automatically delete them
635
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
636
+		}
637
+		// and change logs
638
+		if (get_class($this) !== 'EEM_Change_Log') {
639
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
640
+		}
641
+		/**
642
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
643
+		 * EE_Register_Model_Extension
644
+		 *
645
+		 * @param EE_Model_Relation_Base[] $_model_relations
646
+		 */
647
+		$this->_model_relations = (array)apply_filters(
648
+			'FHEE__' . get_class($this) . '__construct__model_relations',
649
+			$this->_model_relations
650
+		);
651
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
652
+			/** @var $relation_obj EE_Model_Relation_Base */
653
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
654
+		}
655
+		foreach ($this->_indexes as $index_name => $index_obj) {
656
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
657
+		}
658
+		$this->set_timezone($timezone);
659
+		// finalize default where condition strategy, or set default
660
+		if (! $this->_default_where_conditions_strategy) {
661
+			// nothing was set during child constructor, so set default
662
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663
+		}
664
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
665
+		if (! $this->_minimum_where_conditions_strategy) {
666
+			// nothing was set during child constructor, so set default
667
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668
+		}
669
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
670
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
671
+		// to indicate to NOT set it, set it to the logical default
672
+		if ($this->_caps_slug === null) {
673
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674
+		}
675
+		// initialize the standard cap restriction generators if none were specified by the child constructor
676
+		if (! empty($this->_cap_restriction_generators)) {
677
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
680
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681
+						new EE_Restriction_Generator_Protected(),
682
+						$cap_context,
683
+						$this
684
+					);
685
+				}
686
+			}
687
+		// }
688
+		// if ($this->_cap_restriction_generators !== false) {
689
+		// if there are cap restriction generators, use them to make the default cap restrictions
690
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
+				if (! $generator_object) {
692
+					continue;
693
+				}
694
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
695
+					throw new EE_Error(
696
+						sprintf(
697
+							esc_html__(
698
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
699
+								'event_espresso'
700
+							),
701
+							$context,
702
+							$this->get_this_model_name()
703
+						)
704
+					);
705
+				}
706
+				$action = $this->cap_action_for_context($context);
707
+				if (! $generator_object->construction_finalized()) {
708
+					$generator_object->_construct_finalize($this, $action);
709
+				}
710
+			}
711
+		}
712
+		do_action('AHEE__' . get_class($this) . '__construct__end');
713
+	}
714
+
715
+
716
+	/**
717
+	 * Used to set the $_model_query_blog_id static property.
718
+	 *
719
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
720
+	 *                      value for get_current_blog_id() will be used.
721
+	 */
722
+	public static function set_model_query_blog_id($blog_id = 0)
723
+	{
724
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
725
+	}
726
+
727
+
728
+	/**
729
+	 * Returns whatever is set as the internal $model_query_blog_id.
730
+	 *
731
+	 * @return int
732
+	 */
733
+	public static function get_model_query_blog_id()
734
+	{
735
+		return EEM_Base::$_model_query_blog_id;
736
+	}
737
+
738
+
739
+	/**
740
+	 * This function is a singleton method used to instantiate the Espresso_model object
741
+	 *
742
+	 * @param string $timezone        string representing the timezone we want to set for returned Date Time Strings
743
+	 *                                (and any incoming timezone data that gets saved).
744
+	 *                                Note this just sends the timezone info to the date time model field objects.
745
+	 *                                Default is NULL
746
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
747
+	 * @return static (as in the concrete child class)
748
+	 * @throws EE_Error
749
+	 * @throws InvalidArgumentException
750
+	 * @throws InvalidDataTypeException
751
+	 * @throws InvalidInterfaceException
752
+	 */
753
+	public static function instance($timezone = '')
754
+	{
755
+		// check if instance of Espresso_model already exists
756
+		if (! static::$_instance instanceof static) {
757
+			// instantiate Espresso_model
758
+			static::$_instance = new static(
759
+				$timezone,
760
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
761
+			);
762
+		}
763
+		// Espresso model object
764
+		return static::$_instance;
765
+	}
766
+
767
+
768
+	/**
769
+	 * resets the model and returns it
770
+	 *
771
+	 * @param string $timezone
772
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
773
+	 * all its properties reset; if it wasn't instantiated, returns null)
774
+	 * @throws EE_Error
775
+	 * @throws ReflectionException
776
+	 * @throws InvalidArgumentException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws InvalidInterfaceException
779
+	 */
780
+	public static function reset($timezone = '')
781
+	{
782
+		if (static::$_instance instanceof EEM_Base) {
783
+			// let's try to NOT swap out the current instance for a new one
784
+			// because if someone has a reference to it, we can't remove their reference
785
+			// so it's best to keep using the same reference, but change the original object
786
+			// reset all its properties to their original values as defined in the class
787
+			$r                 = new ReflectionClass(get_class(static::$_instance));
788
+			$static_properties = $r->getStaticProperties();
789
+			foreach ($r->getDefaultProperties() as $property => $value) {
790
+				// don't set instance to null like it was originally,
791
+				// but it's static anyways, and we're ignoring static properties (for now at least)
792
+				if (! isset($static_properties[ $property ])) {
793
+					static::$_instance->{$property} = $value;
794
+				}
795
+			}
796
+			EEH_DTT_Helper::resetDefaultTimezoneString();
797
+			// and then directly call its constructor again, like we would if we were creating a new one
798
+			static::$_instance->__construct(
799
+				$timezone,
800
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
801
+			);
802
+			return static::instance();
803
+		}
804
+		return null;
805
+	}
806
+
807
+
808
+	/**
809
+	 * @return LoaderInterface
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 */
814
+	private static function getLoader()
815
+	{
816
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
817
+			EEM_Base::$loader = LoaderFactory::getLoader();
818
+		}
819
+		return EEM_Base::$loader;
820
+	}
821
+
822
+
823
+	/**
824
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
825
+	 *
826
+	 * @param boolean $translated return localized strings or JUST the array.
827
+	 * @return array
828
+	 * @throws EE_Error
829
+	 * @throws InvalidArgumentException
830
+	 * @throws InvalidDataTypeException
831
+	 * @throws InvalidInterfaceException
832
+	 * @throws ReflectionException
833
+	 */
834
+	public function status_array($translated = false)
835
+	{
836
+		if (! array_key_exists('Status', $this->_model_relations)) {
837
+			return [];
838
+		}
839
+		$model_name   = $this->get_this_model_name();
840
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
+		$statuses      = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842
+		$status_array = [];
843
+		foreach ($statuses as $status) {
844
+			$status_array[ $status->ID() ] = $status->get('STS_code');
845
+		}
846
+		return $translated
847
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
848
+			: $status_array;
849
+	}
850
+
851
+
852
+	/**
853
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
854
+	 *
855
+	 * @param array $query_params             see github link below for more info
856
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
857
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
858
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
859
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
860
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
861
+	 *                                        'OR'=>array(
862
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
863
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
864
+	 *                                        )
865
+	 *                                        ),
866
+	 *                                        'limit'=>10,
867
+	 *                                        'group_by'=>'TXN_ID'
868
+	 *                                        ));
869
+	 *                                        get all the answers to the question titled "shirt size" for event with id
870
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
871
+	 *                                        'Question.QST_display_text'=>'shirt size',
872
+	 *                                        'Registration.Event.EVT_ID'=>12
873
+	 *                                        ),
874
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
875
+	 *                                        ));
876
+	 * @throws EE_Error
877
+	 * @throws ReflectionException
878
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
879
+	 *                                        or if you have the development copy of EE you can view this at the path:
880
+	 *                                        /docs/G--Model-System/model-query-params.md
881
+	 */
882
+	public function get_all($query_params = [])
883
+	{
884
+		if (
885
+			isset($query_params['limit'])
886
+			&& ! isset($query_params['group_by'])
887
+		) {
888
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
889
+		}
890
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
891
+	}
892
+
893
+
894
+	/**
895
+	 * Modifies the query parameters so we only get back model objects
896
+	 * that "belong" to the current user
897
+	 *
898
+	 * @param array $query_params see github link below for more info
899
+	 * @return array
900
+	 * @throws ReflectionException
901
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 */
903
+	public function alter_query_params_to_only_include_mine($query_params = [])
904
+	{
905
+		$wp_user_field_name = $this->wp_user_field_name();
906
+		if ($wp_user_field_name) {
907
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
+		}
909
+		return $query_params;
910
+	}
911
+
912
+
913
+	/**
914
+	 * Returns the name of the field's name that points to the WP_User table
915
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
916
+	 * foreign key to the WP_User table)
917
+	 *
918
+	 * @return string|boolean string on success, boolean false when there is no
919
+	 * foreign key to the WP_User table
920
+	 * @throws ReflectionException
921
+	 */
922
+	public function wp_user_field_name()
923
+	{
924
+		try {
925
+			if (! empty($this->_model_chain_to_wp_user)) {
926
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927
+				$last_model_name              = end($models_to_follow_to_wp_users);
928
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
+			} else {
931
+				$model_with_fk_to_wp_users = $this;
932
+				$model_chain_to_wp_user    = '';
933
+			}
934
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
936
+		} catch (EE_Error $e) {
937
+			return false;
938
+		}
939
+	}
940
+
941
+
942
+	/**
943
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
944
+	 * (or transiently-related model) has a foreign key to the wp_users table;
945
+	 * useful for finding if model objects of this type are 'owned' by the current user.
946
+	 * This is an empty string when the foreign key is on this model and when it isn't,
947
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
948
+	 * (or transiently-related model)
949
+	 *
950
+	 * @return string
951
+	 */
952
+	public function model_chain_to_wp_user()
953
+	{
954
+		return $this->_model_chain_to_wp_user;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
960
+	 * like how registrations don't have a foreign key to wp_users, but the
961
+	 * events they are for are), or is unrelated to wp users.
962
+	 * generally available
963
+	 *
964
+	 * @return boolean
965
+	 */
966
+	public function is_owned()
967
+	{
968
+		if ($this->model_chain_to_wp_user()) {
969
+			return true;
970
+		}
971
+		try {
972
+			$this->get_foreign_key_to('WP_User');
973
+			return true;
974
+		} catch (EE_Error $e) {
975
+			return false;
976
+		}
977
+	}
978
+
979
+
980
+	/**
981
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
982
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
983
+	 * the model)
984
+	 *
985
+	 * @param array  $query_params
986
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
987
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
988
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
989
+	 *                                  override this and set the select to "*", or a specific column name, like
990
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
991
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
992
+	 *                                  the aliases used to refer to this selection, and values are to be
993
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
994
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
995
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws ReflectionException
999
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1000
+	 */
1001
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1002
+	{
1003
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1004
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1005
+		$select_expressions       = $columns_to_select === null
1006
+			? $this->_construct_default_select_sql($model_query_info)
1007
+			: '';
1008
+		if ($this->_custom_selections instanceof CustomSelects) {
1009
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010
+			$select_expressions .= $select_expressions
1011
+				? ', ' . $custom_expressions
1012
+				: $custom_expressions;
1013
+		}
1014
+
1015
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1022
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1023
+	 * method of including extra select information.
1024
+	 *
1025
+	 * @param array             $query_params
1026
+	 * @param null|array|string $columns_to_select
1027
+	 * @return null|CustomSelects
1028
+	 * @throws InvalidArgumentException
1029
+	 */
1030
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031
+	{
1032
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
+			return null;
1034
+		}
1035
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1036
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1037
+		return new CustomSelects($selects);
1038
+	}
1039
+
1040
+
1041
+	/**
1042
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1043
+	 * but you can use the model query params to more easily
1044
+	 * take care of joins, field preparation etc.
1045
+	 *
1046
+	 * @param array  $query_params
1047
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1048
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1050
+	 *                                  override this and set the select to "*", or a specific column name, like
1051
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1052
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1053
+	 *                                  the aliases used to refer to this selection, and values are to be
1054
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1055
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1056
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1057
+	 * @throws EE_Error
1058
+	 * @throws ReflectionException
1059
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1060
+	 */
1061
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1062
+	{
1063
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * For creating a custom select statement
1069
+	 *
1070
+	 * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1071
+	 *                                        or an array where keys are aliases, and values are arrays where 0=>the
1072
+	 *                                        selection SQL, and 1=>is the datatype
1073
+	 * @return string
1074
+	 * @throws EE_Error
1075
+	 */
1076
+	private function _construct_select_from_input($columns_to_select)
1077
+	{
1078
+		if (is_array($columns_to_select)) {
1079
+			$select_sql_array = [];
1080
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype,
1089
+							$alias
1090
+						)
1091
+					);
1092
+				}
1093
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
+					throw new EE_Error(
1095
+						sprintf(
1096
+							esc_html__(
1097
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1098
+								'event_espresso'
1099
+							),
1100
+							$selection_and_datatype[1],
1101
+							$selection_and_datatype[0],
1102
+							$alias,
1103
+							implode(', ', $this->_valid_wpdb_data_types)
1104
+						)
1105
+					);
1106
+				}
1107
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1108
+			}
1109
+			$columns_to_select_string = implode(', ', $select_sql_array);
1110
+		} else {
1111
+			$columns_to_select_string = $columns_to_select;
1112
+		}
1113
+		return $columns_to_select_string;
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1119
+	 *
1120
+	 * @return string
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function primary_key_name()
1124
+	{
1125
+		return $this->get_primary_key_field()->get_name();
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1131
+	 * If there is no primary key on this model, $id is treated as primary key string
1132
+	 *
1133
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1134
+	 * @return EE_Base_Class
1135
+	 * @throws EE_Error
1136
+	 * @throws ReflectionException
1137
+	 */
1138
+	public function get_one_by_ID($id)
1139
+	{
1140
+		if ($this->get_from_entity_map($id)) {
1141
+			return $this->get_from_entity_map($id);
1142
+		}
1143
+		$model_object = $this->get_one(
1144
+			$this->alter_query_params_to_restrict_by_ID(
1145
+				$id,
1146
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1147
+			)
1148
+		);
1149
+		$className = $this->_get_class_name();
1150
+		if ($model_object instanceof $className) {
1151
+			// make sure valid objects get added to the entity map
1152
+			// so that the next call to this method doesn't trigger another trip to the db
1153
+			$this->add_to_entity_map($model_object);
1154
+		}
1155
+		return $model_object;
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * Alters query parameters to only get items with this ID are returned.
1161
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1162
+	 * or could just be a simple primary key ID
1163
+	 *
1164
+	 * @param int   $id
1165
+	 * @param array $query_params see github link below for more info
1166
+	 * @return array of normal query params,
1167
+	 * @throws EE_Error
1168
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1169
+	 */
1170
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1171
+	{
1172
+		if (! isset($query_params[0])) {
1173
+			$query_params[0] = [];
1174
+		}
1175
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1176
+		if ($conditions_from_id === null) {
1177
+			$query_params[0][ $this->primary_key_name() ] = $id;
1178
+		} else {
1179
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1180
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1181
+		}
1182
+		return $query_params;
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1188
+	 * array. If no item is found, null is returned.
1189
+	 *
1190
+	 * @param array $query_params like EEM_Base's $query_params variable.
1191
+	 * @return EE_Base_Class|null
1192
+	 * @throws EE_Error
1193
+	 * @throws ReflectionException
1194
+	 */
1195
+	public function get_one(array $query_params = [])
1196
+	{
1197
+		if (! is_array($query_params)) {
1198
+			EE_Error::doing_it_wrong(
1199
+				'EEM_Base::get_one',
1200
+				sprintf(
1201
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1202
+					gettype($query_params)
1203
+				),
1204
+				'4.6.0'
1205
+			);
1206
+			$query_params = [];
1207
+		}
1208
+		$query_params['limit'] = 1;
1209
+		$items                 = $this->get_all($query_params);
1210
+		if (empty($items)) {
1211
+			return null;
1212
+		}
1213
+		return array_shift($items);
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * Returns the next x number of items in sequence from the given value as
1219
+	 * found in the database matching the given query conditions.
1220
+	 *
1221
+	 * @param mixed $current_field_value    Value used for the reference point.
1222
+	 * @param null  $field_to_order_by      What field is used for the
1223
+	 *                                      reference point.
1224
+	 * @param int   $limit                  How many to return.
1225
+	 * @param array $query_params           Extra conditions on the query.
1226
+	 * @param null  $columns_to_select      If left null, then an array of
1227
+	 *                                      EE_Base_Class objects is returned,
1228
+	 *                                      otherwise you can indicate just the
1229
+	 *                                      columns you want returned.
1230
+	 * @return EE_Base_Class[]|array
1231
+	 * @throws EE_Error
1232
+	 * @throws ReflectionException
1233
+	 */
1234
+	public function next_x(
1235
+		$current_field_value,
1236
+		$field_to_order_by = null,
1237
+		$limit = 1,
1238
+		$query_params = [],
1239
+		$columns_to_select = null
1240
+	) {
1241
+		return $this->_get_consecutive(
1242
+			$current_field_value,
1243
+			'>',
1244
+			$field_to_order_by,
1245
+			$limit,
1246
+			$query_params,
1247
+			$columns_to_select
1248
+		);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Returns the previous x number of items in sequence from the given value
1254
+	 * as found in the database matching the given query conditions.
1255
+	 *
1256
+	 * @param mixed $current_field_value    Value used for the reference point.
1257
+	 * @param null  $field_to_order_by      What field is used for the
1258
+	 *                                      reference point.
1259
+	 * @param int   $limit                  How many to return.
1260
+	 * @param array $query_params           Extra conditions on the query.
1261
+	 * @param null  $columns_to_select      If left null, then an array of
1262
+	 *                                      EE_Base_Class objects is returned,
1263
+	 *                                      otherwise you can indicate just the
1264
+	 *                                      columns you want returned.
1265
+	 * @return EE_Base_Class[]|array
1266
+	 * @throws EE_Error
1267
+	 * @throws ReflectionException
1268
+	 */
1269
+	public function previous_x(
1270
+		$current_field_value,
1271
+		$field_to_order_by = null,
1272
+		$limit = 1,
1273
+		$query_params = [],
1274
+		$columns_to_select = null
1275
+	) {
1276
+		return $this->_get_consecutive(
1277
+			$current_field_value,
1278
+			'<',
1279
+			$field_to_order_by,
1280
+			$limit,
1281
+			$query_params,
1282
+			$columns_to_select
1283
+		);
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * Returns the next item in sequence from the given value as found in the
1289
+	 * database matching the given query conditions.
1290
+	 *
1291
+	 * @param mixed $current_field_value    Value used for the reference point.
1292
+	 * @param null  $field_to_order_by      What field is used for the
1293
+	 *                                      reference point.
1294
+	 * @param array $query_params           Extra conditions on the query.
1295
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1296
+	 *                                      object is returned, otherwise you
1297
+	 *                                      can indicate just the columns you
1298
+	 *                                      want and a single array indexed by
1299
+	 *                                      the columns will be returned.
1300
+	 * @return EE_Base_Class|null|array()
1301
+	 * @throws EE_Error
1302
+	 * @throws ReflectionException
1303
+	 */
1304
+	public function next(
1305
+		$current_field_value,
1306
+		$field_to_order_by = null,
1307
+		$query_params = [],
1308
+		$columns_to_select = null
1309
+	) {
1310
+		$results = $this->_get_consecutive(
1311
+			$current_field_value,
1312
+			'>',
1313
+			$field_to_order_by,
1314
+			1,
1315
+			$query_params,
1316
+			$columns_to_select
1317
+		);
1318
+		return empty($results) ? null : reset($results);
1319
+	}
1320
+
1321
+
1322
+	/**
1323
+	 * Returns the previous item in sequence from the given value as found in
1324
+	 * the database matching the given query conditions.
1325
+	 *
1326
+	 * @param mixed $current_field_value    Value used for the reference point.
1327
+	 * @param null  $field_to_order_by      What field is used for the
1328
+	 *                                      reference point.
1329
+	 * @param array $query_params           Extra conditions on the query.
1330
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1331
+	 *                                      object is returned, otherwise you
1332
+	 *                                      can indicate just the columns you
1333
+	 *                                      want and a single array indexed by
1334
+	 *                                      the columns will be returned.
1335
+	 * @return EE_Base_Class|null|array()
1336
+	 * @throws EE_Error
1337
+	 * @throws ReflectionException
1338
+	 */
1339
+	public function previous(
1340
+		$current_field_value,
1341
+		$field_to_order_by = null,
1342
+		$query_params = [],
1343
+		$columns_to_select = null
1344
+	) {
1345
+		$results = $this->_get_consecutive(
1346
+			$current_field_value,
1347
+			'<',
1348
+			$field_to_order_by,
1349
+			1,
1350
+			$query_params,
1351
+			$columns_to_select
1352
+		);
1353
+		return empty($results) ? null : reset($results);
1354
+	}
1355
+
1356
+
1357
+	/**
1358
+	 * Returns the a consecutive number of items in sequence from the given
1359
+	 * value as found in the database matching the given query conditions.
1360
+	 *
1361
+	 * @param mixed  $current_field_value   Value used for the reference point.
1362
+	 * @param string $operand               What operand is used for the sequence.
1363
+	 * @param string $field_to_order_by     What field is used for the reference point.
1364
+	 * @param int    $limit                 How many to return.
1365
+	 * @param array  $query_params          Extra conditions on the query.
1366
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1367
+	 *                                      otherwise you can indicate just the columns you want returned.
1368
+	 * @return EE_Base_Class[]|array
1369
+	 * @throws EE_Error
1370
+	 * @throws ReflectionException
1371
+	 */
1372
+	protected function _get_consecutive(
1373
+		$current_field_value,
1374
+		$operand = '>',
1375
+		$field_to_order_by = null,
1376
+		$limit = 1,
1377
+		$query_params = [],
1378
+		$columns_to_select = null
1379
+	) {
1380
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1381
+		if (empty($field_to_order_by)) {
1382
+			if ($this->has_primary_key_field()) {
1383
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1384
+			} else {
1385
+				if (WP_DEBUG) {
1386
+					throw new EE_Error(
1387
+						esc_html__(
1388
+							'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1389
+							'event_espresso'
1390
+						)
1391
+					);
1392
+				}
1393
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1394
+				return [];
1395
+			}
1396
+		}
1397
+		if (! is_array($query_params)) {
1398
+			EE_Error::doing_it_wrong(
1399
+				'EEM_Base::_get_consecutive',
1400
+				sprintf(
1401
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1402
+					gettype($query_params)
1403
+				),
1404
+				'4.6.0'
1405
+			);
1406
+			$query_params = [];
1407
+		}
1408
+		// let's add the where query param for consecutive look up.
1409
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1410
+		$query_params['limit']                 = $limit;
1411
+		// set direction
1412
+		$incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1413
+		$query_params['order_by'] = $operand === '>'
1414
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1415
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1416
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1417
+		if (empty($columns_to_select)) {
1418
+			return $this->get_all($query_params);
1419
+		}
1420
+		// getting just the fields
1421
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * This sets the _timezone property after model object has been instantiated.
1427
+	 *
1428
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1429
+	 */
1430
+	public function set_timezone($timezone = '')
1431
+	{
1432
+		static $set_in_progress = false;
1433
+		// if incoming timezone string is empty, then use the existing
1434
+		$valid_timezone = ! empty($timezone) && $timezone !== $this->_timezone
1435
+			? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1436
+			: $this->_timezone;
1437
+		// do NOT set the timezone if we are already in the process of setting the timezone
1438
+		// OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1439
+		// OR the existing timezone is already set and the validated value is the same as the existing timezone
1440
+		if (
1441
+			$set_in_progress
1442
+			|| (
1443
+				! empty($this->_timezone)
1444
+				&& (
1445
+					empty($timezone) || $valid_timezone === $this->_timezone
1446
+				)
1447
+			)
1448
+		) {
1449
+			return;
1450
+		}
1451
+		$set_in_progress = true;
1452
+		$this->_timezone = $valid_timezone ?: EEH_DTT_Helper::get_valid_timezone_string();
1453
+		// note we need to loop through relations and set the timezone on those objects as well.
1454
+		foreach ($this->_model_relations as $relation) {
1455
+			$relation->set_timezone($this->_timezone);
1456
+		}
1457
+		// and finally we do the same for any datetime fields
1458
+		foreach ($this->_fields as $field) {
1459
+			if ($field instanceof EE_Datetime_Field) {
1460
+				$field->set_timezone($this->_timezone);
1461
+			}
1462
+		}
1463
+		$set_in_progress = false;
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This just returns whatever is set for the current timezone.
1469
+	 *
1470
+	 * @access public
1471
+	 * @return string
1472
+	 */
1473
+	public function get_timezone()
1474
+	{
1475
+		if (empty($this->_timezone)) {
1476
+			$this->set_timezone();
1477
+		}
1478
+		return $this->_timezone;
1479
+	}
1480
+
1481
+
1482
+	/**
1483
+	 * This returns the date formats set for the given field name and also ensures that
1484
+	 * $this->_timezone property is set correctly.
1485
+	 *
1486
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1487
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488
+	 * @return array formats in an array with the date format first, and the time format last.
1489
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1490
+	 * @since 4.6.x
1491
+	 */
1492
+	public function get_formats_for($field_name, $pretty = false)
1493
+	{
1494
+		$field_settings = $this->field_settings_for($field_name);
1495
+		// if not a valid EE_Datetime_Field then throw error
1496
+		if (! $field_settings instanceof EE_Datetime_Field) {
1497
+			throw new EE_Error(
1498
+				sprintf(
1499
+					esc_html__(
1500
+						'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1501
+						'event_espresso'
1502
+					),
1503
+					$field_name
1504
+				)
1505
+			);
1506
+		}
1507
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on the field.
1508
+		$field_timezone = $field_settings->get_timezone();
1509
+		if (empty($this->_timezone && $field_timezone)) {
1510
+			$this->set_timezone();
1511
+		} else {
1512
+			// or vice versa if the field TZ isn't set
1513
+			$model_timezone = $this->get_timezone();
1514
+			$field_settings->set_timezone($model_timezone);
1515
+		}
1516
+
1517
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1518
+	}
1519
+
1520
+
1521
+	/**
1522
+	 * This returns the current time in a format setup for a query on this model.
1523
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
+	 * it will return:
1525
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field
1526
+	 *    for the given field for NOW
1527
+	 *  - or a unix timestamp (equivalent to time())
1528
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
+	 *
1532
+	 * @param string $field_name    The field the current time is needed for.
1533
+	 * @param bool $timestamp       True means to return a unix timestamp.
1534
+	 *                              Otherwise a formatted string matching the set format for the field
1535
+	 *                              in the set timezone will be returned.
1536
+	 * @param string $what          Whether to return the string in just the time format, the date format, or both.
1537
+	 * @return string               If the given field_name is not of the EE_Datetime_Field type,
1538
+	 *                              then an EE_Error exception is triggered.
1539
+	 * @throws EE_Error             If the given field_name is not of the EE_Datetime_Field type.
1540
+	 * @throws Exception
1541
+	 * @since 4.6.x
1542
+	 */
1543
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1544
+	{
1545
+		$formats  = $this->get_formats_for($field_name);
1546
+		$DateTime = new DateTime("now", new DateTimeZone($this->get_timezone()));
1547
+		if ($timestamp) {
1548
+			return $DateTime->format('U');
1549
+		}
1550
+		// not returning timestamp, so return formatted string in timezone.
1551
+		switch ($what) {
1552
+			case 'time':
1553
+				return $DateTime->format($formats[1]);
1554
+			case 'date':
1555
+				return $DateTime->format($formats[0]);
1556
+			default:
1557
+				return $DateTime->format(implode(' ', $formats));
1558
+		}
1559
+	}
1560
+
1561
+
1562
+	/**
1563
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1564
+	 * for the model are.  Returns a DateTime object.
1565
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1566
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1567
+	 * ignored.
1568
+	 *
1569
+	 * @param string $field_name    The field being setup.
1570
+	 * @param string $timestring    The date time string being used.
1571
+	 * @param string $format        The format for the time string.
1572
+	 * @param string $timezone      By default, it is assumed the incoming time string is in timezone for
1573
+	 *                              the blog.  If this is not the case, then it can be specified here.
1574
+	 *                              If incoming format is 'U', this is ignored.
1575
+	 * @return DbSafeDateTime
1576
+	 * @throws EE_Error
1577
+	 * @throws Exception
1578
+	 */
1579
+	public function convert_datetime_for_query($field_name, $timestring, $format, $timezone = '')
1580
+	{
1581
+		// just using this to ensure the timezone is set correctly internally
1582
+		$this->get_formats_for($field_name);
1583
+		$timezone         = ! empty($timezone) ? $timezone : EEH_DTT_Helper::get_timezone();
1584
+		$db_safe_datetime = DbSafeDateTime::createFromFormat($format, $timestring, new DateTimeZone($timezone));
1585
+		EEH_DTT_Helper::setTimezone($db_safe_datetime, new DateTimeZone($this->get_timezone()));
1586
+		return $db_safe_datetime;
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
+	 *
1593
+	 * @return EE_Table_Base[]
1594
+	 */
1595
+	public function get_tables()
1596
+	{
1597
+		return $this->_tables;
1598
+	}
1599
+
1600
+
1601
+	/**
1602
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1603
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1604
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1605
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1606
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1607
+	 * model object with EVT_ID = 1
1608
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1609
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1610
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1611
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1612
+	 * are not specified)
1613
+	 *
1614
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1615
+	 *                                         columns!), values are strings, integers, floats, and maybe arrays if
1616
+	 *                                         they
1617
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1620
+	 *                                         ID=34, we'd use this method as follows:
1621
+	 *                                         EEM_Transaction::instance()->update(
1622
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
+	 *                                         array(array('TXN_ID'=>34)));
1624
+	 * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1625
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1626
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1627
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1628
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1629
+	 *                                         TRUE, it is assumed that you've already called
1630
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1631
+	 *                                         malicious javascript. However, if
1632
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1633
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1634
+	 *                                         and every other field, before insertion. We provide this parameter
1635
+	 *                                         because model objects perform their prepare_for_set function on all
1636
+	 *                                         their values, and so don't need to be called again (and in many cases,
1637
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1638
+	 *                                         prepare_for_set method...)
1639
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1640
+	 *                                         in this model's entity map according to $fields_n_values that match
1641
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1642
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1643
+	 *                                         could get out-of-sync with the database
1644
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1645
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1646
+	 *                                         bad)
1647
+	 * @throws EE_Error
1648
+	 * @throws ReflectionException
1649
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
+	 */
1651
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
+	{
1653
+		if (! is_array($query_params)) {
1654
+			EE_Error::doing_it_wrong(
1655
+				'EEM_Base::update',
1656
+				sprintf(
1657
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1658
+					gettype($query_params)
1659
+				),
1660
+				'4.6.0'
1661
+			);
1662
+			$query_params = [];
1663
+		}
1664
+		/**
1665
+		 * Action called before a model update call has been made.
1666
+		 *
1667
+		 * @param EEM_Base $model
1668
+		 * @param array    $fields_n_values the updated fields and their new values
1669
+		 * @param array    $query_params
1670
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1671
+		 */
1672
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1673
+		/**
1674
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1675
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1676
+		 *
1677
+		 * @param array    $fields_n_values fields and their new values
1678
+		 * @param EEM_Base $model           the model being queried
1679
+		 * @param array    $query_params
1680
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1681
+		 */
1682
+		$fields_n_values = (array)apply_filters(
1683
+			'FHEE__EEM_Base__update__fields_n_values',
1684
+			$fields_n_values,
1685
+			$this,
1686
+			$query_params
1687
+		);
1688
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1689
+		// to do that, for each table, verify that it's PK isn't null.
1690
+		$tables = $this->get_tables();
1691
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1692
+		// NOTE: we should make this code more efficient by NOT querying twice
1693
+		// before the real update, but that needs to first go through ALPHA testing
1694
+		// as it's dangerous. says Mike August 8 2014
1695
+		// we want to make sure the default_where strategy is ignored
1696
+		$this->_ignore_where_strategy = true;
1697
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1698
+		foreach ($wpdb_select_results as $wpdb_result) {
1699
+			// type cast stdClass as array
1700
+			$wpdb_result = (array)$wpdb_result;
1701
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1702
+			if ($this->has_primary_key_field()) {
1703
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1704
+			} else {
1705
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1706
+				$main_table_pk_value = null;
1707
+			}
1708
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1709
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1710
+			if (count($tables) > 1) {
1711
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1712
+				// in that table, and so we'll want to insert one
1713
+				foreach ($tables as $table_obj) {
1714
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1715
+					// if there is no private key for this table on the results, it means there's no entry
1716
+					// in this table, right? so insert a row in the current table, using any fields available
1717
+					if (
1718
+					! (array_key_exists($this_table_pk_column, $wpdb_result)
1719
+					   && $wpdb_result[ $this_table_pk_column ])
1720
+					) {
1721
+						$success = $this->_insert_into_specific_table(
1722
+							$table_obj,
1723
+							$fields_n_values,
1724
+							$main_table_pk_value
1725
+						);
1726
+						// if we died here, report the error
1727
+						if (! $success) {
1728
+							return false;
1729
+						}
1730
+					}
1731
+				}
1732
+			}
1733
+			// let's make sure default_where strategy is followed now
1734
+			$this->_ignore_where_strategy = false;
1735
+		}
1736
+		// if we want to keep model objects in sync, AND
1737
+		// if this wasn't called from a model object (to update itself)
1738
+		// then we want to make sure we keep all the existing
1739
+		// model objects in sync with the db
1740
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1741
+			if ($this->has_primary_key_field()) {
1742
+				$model_objs_affected_ids = $this->get_col($query_params);
1743
+			} else {
1744
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1745
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1746
+				$model_objs_affected_ids     = [];
1747
+				foreach ($models_affected_key_columns as $row) {
1748
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1749
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1750
+				}
1751
+			}
1752
+			if (! $model_objs_affected_ids) {
1753
+				// wait wait wait- if nothing was affected let's stop here
1754
+				return 0;
1755
+			}
1756
+			foreach ($model_objs_affected_ids as $id) {
1757
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1758
+				if ($model_obj_in_entity_map) {
1759
+					foreach ($fields_n_values as $field => $new_value) {
1760
+						$model_obj_in_entity_map->set($field, $new_value);
1761
+					}
1762
+				}
1763
+			}
1764
+			// if there is a primary key on this model, we can now do a slight optimization
1765
+			if ($this->has_primary_key_field()) {
1766
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1767
+				$query_params = [
1768
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1769
+					'limit'                    => count($model_objs_affected_ids),
1770
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1771
+				];
1772
+			}
1773
+		}
1774
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
+		$SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1776
+							. " SET " . $this->_construct_update_sql($fields_n_values)
1777
+							. $model_query_info->get_where_sql();
1778
+		// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1779
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1780
+		/**
1781
+		 * Action called after a model update call has been made.
1782
+		 *
1783
+		 * @param EEM_Base $model
1784
+		 * @param array    $fields_n_values the updated fields and their new values
1785
+		 * @param array    $query_params
1786
+		 * @param int      $rows_affected
1787
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1788
+		 */
1789
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1790
+		return $rows_affected;// how many supposedly got updated
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1796
+	 * are teh values of the field specified (or by default the primary key field)
1797
+	 * that matched the query params. Note that you should pass the name of the
1798
+	 * model FIELD, not the database table's column name.
1799
+	 *
1800
+	 * @param array  $query_params
1801
+	 * @param string $field_to_select
1802
+	 * @return array just like $wpdb->get_col()
1803
+	 * @throws EE_Error
1804
+	 * @throws ReflectionException
1805
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1806
+	 */
1807
+	public function get_col($query_params = [], $field_to_select = null)
1808
+	{
1809
+		if ($field_to_select) {
1810
+			$field = $this->field_settings_for($field_to_select);
1811
+		} elseif ($this->has_primary_key_field()) {
1812
+			$field = $this->get_primary_key_field();
1813
+		} else {
1814
+			$field_settings = $this->field_settings();
1815
+			// no primary key, just grab the first column
1816
+			$field = reset($field_settings);
1817
+		}
1818
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1819
+		$select_expressions = $field->get_qualified_column();
1820
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1821
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1822
+	}
1823
+
1824
+
1825
+	/**
1826
+	 * Returns a single column value for a single row from the database
1827
+	 *
1828
+	 * @param array  $query_params
1829
+	 * @param string $field_to_select
1830
+	 * @return string
1831
+	 * @throws EE_Error
1832
+	 * @throws ReflectionException
1833
+	 * @see EEM_Base::get_col()
1834
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1835
+	 */
1836
+	public function get_var($query_params = [], $field_to_select = null)
1837
+	{
1838
+		$query_params['limit'] = 1;
1839
+		$col                   = $this->get_col($query_params, $field_to_select);
1840
+		if (! empty($col)) {
1841
+			return reset($col);
1842
+		}
1843
+		return null;
1844
+	}
1845
+
1846
+
1847
+	/**
1848
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1849
+	 * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1850
+	 * injection, but currently no further filtering is done
1851
+	 *
1852
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1853
+	 *                               be updated to in the DB
1854
+	 * @return string of SQL
1855
+	 * @throws EE_Error
1856
+	 * @global      $wpdb
1857
+	 */
1858
+	public function _construct_update_sql($fields_n_values)
1859
+	{
1860
+		global $wpdb;
1861
+		$cols_n_values = [];
1862
+		foreach ($fields_n_values as $field_name => $value) {
1863
+			$field_obj = $this->field_settings_for($field_name);
1864
+			// if the value is NULL, we want to assign the value to that.
1865
+			// wpdb->prepare doesn't really handle that properly
1866
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1867
+			$value_sql       = $prepared_value === null
1868
+				? 'NULL'
1869
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1870
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1871
+		}
1872
+		return implode(",", $cols_n_values);
1873
+	}
1874
+
1875
+
1876
+	/**
1877
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1878
+	 * Performs a HARD delete, meaning the database row should always be removed,
1879
+	 * not just have a flag field on it switched
1880
+	 * Wrapper for EEM_Base::delete_permanently()
1881
+	 *
1882
+	 * @param mixed   $id
1883
+	 * @param boolean $allow_blocking
1884
+	 * @return int the number of rows deleted
1885
+	 * @throws EE_Error
1886
+	 * @throws ReflectionException
1887
+	 */
1888
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1889
+	{
1890
+		return $this->delete_permanently(
1891
+			[
1892
+				[$this->get_primary_key_field()->get_name() => $id],
1893
+				'limit' => 1,
1894
+			],
1895
+			$allow_blocking
1896
+		);
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
+	 * Wrapper for EEM_Base::delete()
1903
+	 *
1904
+	 * @param mixed   $id
1905
+	 * @param boolean $allow_blocking
1906
+	 * @return int the number of rows deleted
1907
+	 * @throws EE_Error
1908
+	 * @throws ReflectionException
1909
+	 */
1910
+	public function delete_by_ID($id, $allow_blocking = true)
1911
+	{
1912
+		return $this->delete(
1913
+			[
1914
+				[$this->get_primary_key_field()->get_name() => $id],
1915
+				'limit' => 1,
1916
+			],
1917
+			$allow_blocking
1918
+		);
1919
+	}
1920
+
1921
+
1922
+	/**
1923
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1924
+	 * meaning if the model has a field that indicates its been "trashed" or
1925
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1926
+	 *
1927
+	 * @param array   $query_params
1928
+	 * @param boolean $allow_blocking
1929
+	 * @return int how many rows got deleted
1930
+	 * @throws EE_Error
1931
+	 * @throws ReflectionException
1932
+	 * @see EEM_Base::delete_permanently
1933
+	 */
1934
+	public function delete($query_params, $allow_blocking = true)
1935
+	{
1936
+		return $this->delete_permanently($query_params, $allow_blocking);
1937
+	}
1938
+
1939
+
1940
+	/**
1941
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1942
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1943
+	 * as archived, not actually deleted
1944
+	 *
1945
+	 * @param array   $query_params
1946
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1947
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1948
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1949
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1950
+	 *                                DB
1951
+	 * @return int how many rows got deleted
1952
+	 * @throws EE_Error
1953
+	 * @throws ReflectionException
1954
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1955
+	 */
1956
+	public function delete_permanently($query_params, $allow_blocking = true)
1957
+	{
1958
+		/**
1959
+		 * Action called just before performing a real deletion query. You can use the
1960
+		 * model and its $query_params to find exactly which items will be deleted
1961
+		 *
1962
+		 * @param EEM_Base $model
1963
+		 * @param array    $query_params
1964
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1965
+		 *                                 to block (prevent) this deletion
1966
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1967
+		 */
1968
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1969
+		// some MySQL databases may be running safe mode, which may restrict
1970
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1971
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1972
+		// to delete them
1973
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1974
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1975
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1976
+			$columns_and_ids_for_deleting
1977
+		);
1978
+		/**
1979
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1980
+		 *
1981
+		 * @param EEM_Base $this                            The model instance being acted on.
1982
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1983
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1984
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1985
+		 *                                                  derived from the incoming query parameters.
1986
+		 * @see details on the structure of this array in the phpdocs
1987
+		 *                                                  for the `_get_ids_for_delete_method`
1988
+		 *
1989
+		 */
1990
+		do_action(
1991
+			'AHEE__EEM_Base__delete__before_query',
1992
+			$this,
1993
+			$query_params,
1994
+			$allow_blocking,
1995
+			$columns_and_ids_for_deleting
1996
+		);
1997
+		if ($deletion_where_query_part) {
1998
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1999
+			$table_aliases    = implode(', ', array_keys($this->_tables));
2000
+			$SQL              = "DELETE " . $table_aliases
2001
+								. " FROM " . $model_query_info->get_full_join_sql()
2002
+								. " WHERE " . $deletion_where_query_part;
2003
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2004
+		} else {
2005
+			$rows_deleted = 0;
2006
+		}
2007
+
2008
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2009
+		// there was no error with the delete query.
2010
+		if (
2011
+			$this->has_primary_key_field()
2012
+			&& $rows_deleted !== false
2013
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2014
+		) {
2015
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2016
+			foreach ($ids_for_removal as $id) {
2017
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2018
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2019
+				}
2020
+			}
2021
+
2022
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2023
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2024
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2025
+			// (although it is possible).
2026
+			// Note this can be skipped by using the provided filter and returning false.
2027
+			if (
2028
+			apply_filters(
2029
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2030
+				! $this instanceof EEM_Extra_Meta,
2031
+				$this
2032
+			)
2033
+			) {
2034
+				EEM_Extra_Meta::instance()->delete_permanently(
2035
+					[
2036
+						0 => [
2037
+							'EXM_type' => $this->get_this_model_name(),
2038
+							'OBJ_ID'   => [
2039
+								'IN',
2040
+								$ids_for_removal,
2041
+							],
2042
+						],
2043
+					]
2044
+				);
2045
+			}
2046
+		}
2047
+
2048
+		/**
2049
+		 * Action called just after performing a real deletion query. Although at this point the
2050
+		 * items should have been deleted
2051
+		 *
2052
+		 * @param EEM_Base $model
2053
+		 * @param array    $query_params
2054
+		 * @param int      $rows_deleted
2055
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2056
+		 */
2057
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
+		return $rows_deleted;// how many supposedly got deleted
2059
+	}
2060
+
2061
+
2062
+	/**
2063
+	 * Checks all the relations that throw error messages when there are blocking related objects
2064
+	 * for related model objects. If there are any related model objects on those relations,
2065
+	 * adds an EE_Error, and return true
2066
+	 *
2067
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2068
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2069
+	 *                                                 should be ignored when determining whether there are related
2070
+	 *                                                 model objects which block this model object's deletion. Useful
2071
+	 *                                                 if you know A is related to B and are considering deleting A,
2072
+	 *                                                 but want to see if A has any other objects blocking its deletion
2073
+	 *                                                 before removing the relation between A and B
2074
+	 * @return boolean
2075
+	 * @throws EE_Error
2076
+	 * @throws ReflectionException
2077
+	 */
2078
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
+	{
2080
+		// first, if $ignore_this_model_obj was supplied, get its model
2081
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
+			$ignored_model = $ignore_this_model_obj->get_model();
2083
+		} else {
2084
+			$ignored_model = null;
2085
+		}
2086
+		// now check all the relations of $this_model_obj_or_id and see if there
2087
+		// are any related model objects blocking it?
2088
+		$is_blocked = false;
2089
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2091
+				// if $ignore_this_model_obj was supplied, then for the query
2092
+				// on that model needs to be told to ignore $ignore_this_model_obj
2093
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
+					$related_model_objects = $relation_obj->get_all_related(
2095
+						$this_model_obj_or_id,
2096
+						[
2097
+							[
2098
+								$ignored_model->get_primary_key_field()->get_name() => [
2099
+									'!=',
2100
+									$ignore_this_model_obj->ID(),
2101
+								],
2102
+							],
2103
+						]
2104
+					);
2105
+				} else {
2106
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2107
+				}
2108
+				if ($related_model_objects) {
2109
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2110
+					$is_blocked = true;
2111
+				}
2112
+			}
2113
+		}
2114
+		return $is_blocked;
2115
+	}
2116
+
2117
+
2118
+	/**
2119
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2120
+	 *
2121
+	 * @param array $row_results_for_deleting
2122
+	 * @param bool  $allow_blocking
2123
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2124
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2125
+	 *                              dimension array where the key is the fully qualified primary key column and the
2126
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2127
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2128
+	 *                              be a two dimensional array where each element is a group of columns and values that
2129
+	 *                              get deleted. Example: array(
2130
+	 *                              0 => array(
2131
+	 *                              'Term_Relationship.object_id' => 1
2132
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2133
+	 *                              ),
2134
+	 *                              1 => array(
2135
+	 *                              'Term_Relationship.object_id' => 1
2136
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2137
+	 *                              )
2138
+	 *                              )
2139
+	 * @throws EE_Error
2140
+	 * @throws ReflectionException
2141
+	 */
2142
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2143
+	{
2144
+		$ids_to_delete_indexed_by_column = [];
2145
+		if ($this->has_primary_key_field()) {
2146
+			$primary_table                   = $this->_get_main_table();
2147
+			$ids_to_delete_indexed_by_column = [];
2148
+			foreach ($row_results_for_deleting as $item_to_delete) {
2149
+				// before we mark this item for deletion,
2150
+				// make sure there's no related entities blocking its deletion (if we're checking)
2151
+				if (
2152
+					$allow_blocking
2153
+					&& $this->delete_is_blocked_by_related_models(
2154
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2155
+					)
2156
+				) {
2157
+					continue;
2158
+				}
2159
+				// primary table deletes
2160
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2161
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2162
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2163
+				}
2164
+			}
2165
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2166
+			$fields = $this->get_combined_primary_key_fields();
2167
+			foreach ($row_results_for_deleting as $item_to_delete) {
2168
+				$ids_to_delete_indexed_by_column_for_row = [];
2169
+				foreach ($fields as $cpk_field) {
2170
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2171
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2172
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2173
+					}
2174
+				}
2175
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2176
+			}
2177
+		} else {
2178
+			// so there's no primary key and no combined key...
2179
+			// sorry, can't help you
2180
+			throw new EE_Error(
2181
+				sprintf(
2182
+					esc_html__(
2183
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2184
+						"event_espresso"
2185
+					),
2186
+					get_class($this)
2187
+				)
2188
+			);
2189
+		}
2190
+		return $ids_to_delete_indexed_by_column;
2191
+	}
2192
+
2193
+
2194
+	/**
2195
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2196
+	 * the corresponding query_part for the query performing the delete.
2197
+	 *
2198
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2199
+	 * @return string
2200
+	 * @throws EE_Error
2201
+	 */
2202
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2203
+	{
2204
+		$query_part = '';
2205
+		if (empty($ids_to_delete_indexed_by_column)) {
2206
+			return $query_part;
2207
+		} elseif ($this->has_primary_key_field()) {
2208
+			$query = [];
2209
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210
+				// make sure we have unique $ids
2211
+				$ids     = array_unique($ids);
2212
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2213
+			}
2214
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2216
+			$ways_to_identify_a_row = [];
2217
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218
+				$values_for_each_combined_primary_key_for_a_row = [];
2219
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2221
+				}
2222
+				$value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2223
+				$ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
2224
+			}
2225
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2226
+		}
2227
+		return $query_part;
2228
+	}
2229
+
2230
+
2231
+	/**
2232
+	 * Gets the model field by the fully qualified name
2233
+	 *
2234
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2235
+	 * @return EE_Model_Field_Base
2236
+	 * @throws EE_Error
2237
+	 */
2238
+	public function get_field_by_column($qualified_column_name)
2239
+	{
2240
+		foreach ($this->field_settings(true) as $field_obj) {
2241
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242
+				return $field_obj;
2243
+			}
2244
+		}
2245
+		throw new EE_Error(
2246
+			sprintf(
2247
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2248
+				$this->get_this_model_name(),
2249
+				$qualified_column_name
2250
+			)
2251
+		);
2252
+	}
2253
+
2254
+
2255
+	/**
2256
+	 * Count all the rows that match criteria the model query params.
2257
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2258
+	 * column
2259
+	 *
2260
+	 * @param array  $query_params
2261
+	 * @param string $field_to_count field on model to count by (not column name)
2262
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2263
+	 *                               that by the setting $distinct to TRUE;
2264
+	 * @return int
2265
+	 * @throws EE_Error
2266
+	 * @throws ReflectionException
2267
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2268
+	 */
2269
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2270
+	{
2271
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
+		if ($field_to_count) {
2273
+			$field_obj       = $this->field_settings_for($field_to_count);
2274
+			$column_to_count = $field_obj->get_qualified_column();
2275
+		} elseif ($this->has_primary_key_field()) {
2276
+			$pk_field_obj    = $this->get_primary_key_field();
2277
+			$column_to_count = $pk_field_obj->get_qualified_column();
2278
+		} else {
2279
+			// there's no primary key
2280
+			// if we're counting distinct items, and there's no primary key,
2281
+			// we need to list out the columns for distinction;
2282
+			// otherwise we can just use star
2283
+			if ($distinct) {
2284
+				$columns_to_use = [];
2285
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2286
+					$columns_to_use[] = $field_obj->get_qualified_column();
2287
+				}
2288
+				$column_to_count = implode(',', $columns_to_use);
2289
+			} else {
2290
+				$column_to_count = '*';
2291
+			}
2292
+		}
2293
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2294
+		$SQL             =
2295
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
+		return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2297
+	}
2298
+
2299
+
2300
+	/**
2301
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2302
+	 *
2303
+	 * @param array  $query_params
2304
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2305
+	 * @return float
2306
+	 * @throws EE_Error
2307
+	 * @throws ReflectionException
2308
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2309
+	 */
2310
+	public function sum($query_params, $field_to_sum = null)
2311
+	{
2312
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2313
+		if ($field_to_sum) {
2314
+			$field_obj = $this->field_settings_for($field_to_sum);
2315
+		} else {
2316
+			$field_obj = $this->get_primary_key_field();
2317
+		}
2318
+		$column_to_count = $field_obj->get_qualified_column();
2319
+		$SQL             = "SELECT SUM(" . $column_to_count . ")"
2320
+						   . $this->_construct_2nd_half_of_select_query($model_query_info);
2321
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2322
+		// $data_type       = $field_obj->get_wpdb_data_type();
2323
+		// if ($data_type === '%d' || $data_type === '%s') {
2324
+		//     return (float)$return_value;
2325
+		// }
2326
+		// must be %f
2327
+		return (float)$return_value;
2328
+	}
2329
+
2330
+
2331
+	/**
2332
+	 * Just calls the specified method on $wpdb with the given arguments
2333
+	 * Consolidates a little extra error handling code
2334
+	 *
2335
+	 * @param string $wpdb_method
2336
+	 * @param array  $arguments_to_provide
2337
+	 * @return mixed
2338
+	 * @throws EE_Error
2339
+	 * @throws ReflectionException
2340
+	 * @global wpdb  $wpdb
2341
+	 */
2342
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2343
+	{
2344
+		// if we're in maintenance mode level 2, DON'T run any queries
2345
+		// because level 2 indicates the database needs updating and
2346
+		// is probably out of sync with the code
2347
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2348
+			throw new EE_Error(
2349
+				esc_html__(
2350
+					'Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.',
2351
+					'event_espresso'
2352
+				)
2353
+			);
2354
+		}
2355
+		global $wpdb;
2356
+		if (! method_exists($wpdb, $wpdb_method)) {
2357
+			throw new EE_Error(
2358
+				sprintf(
2359
+					esc_html__(
2360
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2361
+						'event_espresso'
2362
+					),
2363
+					$wpdb_method
2364
+				)
2365
+			);
2366
+		}
2367
+		$old_show_errors_value = $wpdb->show_errors;
2368
+		if (WP_DEBUG) {
2369
+			$wpdb->show_errors(false);
2370
+		}
2371
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2372
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2373
+		if (WP_DEBUG) {
2374
+			$wpdb->show_errors($old_show_errors_value);
2375
+			if (! empty($wpdb->last_error)) {
2376
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2377
+			}
2378
+			if ($result === false) {
2379
+				throw new EE_Error(
2380
+					sprintf(
2381
+						esc_html__(
2382
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2383
+							'event_espresso'
2384
+						),
2385
+						$wpdb_method,
2386
+						var_export($arguments_to_provide, true)
2387
+					)
2388
+				);
2389
+			}
2390
+		} elseif ($result === false) {
2391
+			EE_Error::add_error(
2392
+				sprintf(
2393
+					esc_html__(
2394
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2395
+						'event_espresso'
2396
+					),
2397
+					$wpdb_method,
2398
+					var_export($arguments_to_provide, true),
2399
+					$wpdb->last_error
2400
+				),
2401
+				__FILE__,
2402
+				__FUNCTION__,
2403
+				__LINE__
2404
+			);
2405
+		}
2406
+		return $result;
2407
+	}
2408
+
2409
+
2410
+	/**
2411
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2412
+	 * and if there's an error tries to verify the DB is correct. Uses
2413
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2414
+	 * we should try to fix the EE core db, the addons, or just give up
2415
+	 *
2416
+	 * @param string $wpdb_method
2417
+	 * @param array  $arguments_to_provide
2418
+	 * @return mixed
2419
+	 * @throws EE_Error
2420
+	 * @throws ReflectionException
2421
+	 */
2422
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2423
+	{
2424
+		global $wpdb;
2425
+		$wpdb->last_error = null;
2426
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2427
+		// was there an error running the query? but we don't care on new activations
2428
+		// (we're going to setup the DB anyway on new activations)
2429
+		if (
2430
+			($result === false || ! empty($wpdb->last_error))
2431
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2432
+		) {
2433
+			switch (EEM_Base::$_db_verification_level) {
2434
+				case EEM_Base::db_verified_none:
2435
+					// let's double-check core's DB
2436
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2437
+					break;
2438
+				case EEM_Base::db_verified_core:
2439
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2440
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2441
+					break;
2442
+				case EEM_Base::db_verified_addons:
2443
+					// ummmm... you in trouble
2444
+					return $result;
2445
+			}
2446
+			if (! empty($error_message)) {
2447
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2448
+				trigger_error($error_message);
2449
+			}
2450
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2451
+		}
2452
+		return $result;
2453
+	}
2454
+
2455
+
2456
+	/**
2457
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2458
+	 * EEM_Base::$_db_verification_level
2459
+	 *
2460
+	 * @param string $wpdb_method
2461
+	 * @param array  $arguments_to_provide
2462
+	 * @return string
2463
+	 * @throws EE_Error
2464
+	 * @throws ReflectionException
2465
+	 */
2466
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2467
+	{
2468
+		global $wpdb;
2469
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2470
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2471
+		$error_message                    = sprintf(
2472
+			esc_html__(
2473
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2474
+				'event_espresso'
2475
+			),
2476
+			$wpdb->last_error,
2477
+			$wpdb_method,
2478
+			wp_json_encode($arguments_to_provide)
2479
+		);
2480
+		EE_System::instance()->initialize_db_if_no_migrations_required();
2481
+		return $error_message;
2482
+	}
2483
+
2484
+
2485
+	/**
2486
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2487
+	 * EEM_Base::$_db_verification_level
2488
+	 *
2489
+	 * @param $wpdb_method
2490
+	 * @param $arguments_to_provide
2491
+	 * @return string
2492
+	 * @throws EE_Error
2493
+	 * @throws ReflectionException
2494
+	 */
2495
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2496
+	{
2497
+		global $wpdb;
2498
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2499
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2500
+		$error_message                    = sprintf(
2501
+			esc_html__(
2502
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2503
+				'event_espresso'
2504
+			),
2505
+			$wpdb->last_error,
2506
+			$wpdb_method,
2507
+			wp_json_encode($arguments_to_provide)
2508
+		);
2509
+		EE_System::instance()->initialize_addons();
2510
+		return $error_message;
2511
+	}
2512
+
2513
+
2514
+	/**
2515
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2516
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2517
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2518
+	 * ..."
2519
+	 *
2520
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2521
+	 * @return string
2522
+	 */
2523
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2524
+	{
2525
+		return " FROM " . $model_query_info->get_full_join_sql() .
2526
+			   $model_query_info->get_where_sql() .
2527
+			   $model_query_info->get_group_by_sql() .
2528
+			   $model_query_info->get_having_sql() .
2529
+			   $model_query_info->get_order_by_sql() .
2530
+			   $model_query_info->get_limit_sql();
2531
+	}
2532
+
2533
+
2534
+	/**
2535
+	 * Set to easily debug the next X queries ran from this model.
2536
+	 *
2537
+	 * @param int $count
2538
+	 */
2539
+	public function show_next_x_db_queries($count = 1)
2540
+	{
2541
+		$this->_show_next_x_db_queries = $count;
2542
+	}
2543
+
2544
+
2545
+	/**
2546
+	 * @param $sql_query
2547
+	 */
2548
+	public function show_db_query_if_previously_requested($sql_query)
2549
+	{
2550
+		if ($this->_show_next_x_db_queries > 0) {
2551
+			echo $sql_query;
2552
+			$this->_show_next_x_db_queries--;
2553
+		}
2554
+	}
2555
+
2556
+
2557
+	/**
2558
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2559
+	 * There are the 3 cases:
2560
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2561
+	 * $otherModelObject has no ID, it is first saved.
2562
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2563
+	 * has no ID, it is first saved.
2564
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2565
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2566
+	 * join table
2567
+	 *
2568
+	 * @param EE_Base_Class                     /int $thisModelObject
2569
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2570
+	 * @param string $relationName                     , key in EEM_Base::_relations
2571
+	 *                                                 an attendee to a group, you also want to specify which role they
2572
+	 *                                                 will have in that group. So you would use this parameter to
2573
+	 *                                                 specify array('role-column-name'=>'role-id')
2574
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2575
+	 *                                                 to for relation to methods that allow you to further specify
2576
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2577
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2578
+	 *                                                 because these will be inserted in any new rows created as well.
2579
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2580
+	 * @throws EE_Error
2581
+	 */
2582
+	public function add_relationship_to(
2583
+		$id_or_obj,
2584
+		$other_model_id_or_obj,
2585
+		$relationName,
2586
+		$extra_join_model_fields_n_values = []
2587
+	) {
2588
+		$relation_obj = $this->related_settings_for($relationName);
2589
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2590
+	}
2591
+
2592
+
2593
+	/**
2594
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2595
+	 * There are the 3 cases:
2596
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2597
+	 * error
2598
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2599
+	 * an error
2600
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2601
+	 *
2602
+	 * @param EE_Base_Class /int $id_or_obj
2603
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2604
+	 * @param string $relationName key in EEM_Base::_relations
2605
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2606
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2607
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2608
+	 *                             because these will be inserted in any new rows created as well.
2609
+	 * @return boolean of success
2610
+	 * @throws EE_Error
2611
+	 */
2612
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2613
+	{
2614
+		$relation_obj = $this->related_settings_for($relationName);
2615
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2616
+	}
2617
+
2618
+
2619
+	/**
2620
+	 * @param mixed  $id_or_obj
2621
+	 * @param string $relationName
2622
+	 * @param array  $where_query_params
2623
+	 * @param EE_Base_Class[] objects to which relations were removed
2624
+	 * @return EE_Base_Class[]
2625
+	 * @throws EE_Error
2626
+	 */
2627
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2628
+	{
2629
+		$relation_obj = $this->related_settings_for($relationName);
2630
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2631
+	}
2632
+
2633
+
2634
+	/**
2635
+	 * Gets all the related items of the specified $model_name, using $query_params.
2636
+	 * Note: by default, we remove the "default query params"
2637
+	 * because we want to get even deleted items etc.
2638
+	 *
2639
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2640
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2641
+	 * @param array  $query_params see github link below for more info
2642
+	 * @return EE_Base_Class[]
2643
+	 * @throws EE_Error
2644
+	 * @throws ReflectionException
2645
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2646
+	 */
2647
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2648
+	{
2649
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2650
+		$relation_settings = $this->related_settings_for($model_name);
2651
+		return $relation_settings->get_all_related($model_obj, $query_params);
2652
+	}
2653
+
2654
+
2655
+	/**
2656
+	 * Deletes all the model objects across the relation indicated by $model_name
2657
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2658
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2659
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2660
+	 *
2661
+	 * @param EE_Base_Class|int|string $id_or_obj
2662
+	 * @param string                   $model_name
2663
+	 * @param array                    $query_params
2664
+	 * @return int how many deleted
2665
+	 * @throws EE_Error
2666
+	 * @throws ReflectionException
2667
+	 */
2668
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2669
+	{
2670
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2671
+		$relation_settings = $this->related_settings_for($model_name);
2672
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2673
+	}
2674
+
2675
+
2676
+	/**
2677
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2678
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2679
+	 * the model objects can't be hard deleted because of blocking related model objects,
2680
+	 * just does a soft-delete on them instead.
2681
+	 *
2682
+	 * @param EE_Base_Class|int|string $id_or_obj
2683
+	 * @param string                   $model_name
2684
+	 * @param array                    $query_params
2685
+	 * @return int how many deleted
2686
+	 * @throws EE_Error
2687
+	 * @throws ReflectionException
2688
+	 */
2689
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2690
+	{
2691
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2692
+		$relation_settings = $this->related_settings_for($model_name);
2693
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2694
+	}
2695
+
2696
+
2697
+	/**
2698
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2699
+	 * unless otherwise specified in the $query_params
2700
+	 *
2701
+	 * @param int             /EE_Base_Class $id_or_obj
2702
+	 * @param string $model_name     like 'Event', or 'Registration'
2703
+	 * @param array  $query_params
2704
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2705
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2706
+	 *                               that by the setting $distinct to TRUE;
2707
+	 * @return int
2708
+	 * @throws EE_Error
2709
+	 * @throws ReflectionException
2710
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2711
+	 */
2712
+	public function count_related(
2713
+		$id_or_obj,
2714
+		$model_name,
2715
+		$query_params = [],
2716
+		$field_to_count = null,
2717
+		$distinct = false
2718
+	) {
2719
+		$related_model = $this->get_related_model_obj($model_name);
2720
+		// we're just going to use the query params on the related model's normal get_all query,
2721
+		// except add a condition to say to match the current mod
2722
+		if (! isset($query_params['default_where_conditions'])) {
2723
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2724
+		}
2725
+		$this_model_name                                                 = $this->get_this_model_name();
2726
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2727
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2728
+		return $related_model->count($query_params, $field_to_count, $distinct);
2729
+	}
2730
+
2731
+
2732
+	/**
2733
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2734
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2735
+	 *
2736
+	 * @param int           /EE_Base_Class $id_or_obj
2737
+	 * @param string $model_name   like 'Event', or 'Registration'
2738
+	 * @param array  $query_params
2739
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2740
+	 * @return float
2741
+	 * @throws EE_Error
2742
+	 * @throws ReflectionException
2743
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2744
+	 */
2745
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2746
+	{
2747
+		$related_model = $this->get_related_model_obj($model_name);
2748
+		if (! is_array($query_params)) {
2749
+			EE_Error::doing_it_wrong(
2750
+				'EEM_Base::sum_related',
2751
+				sprintf(
2752
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2753
+					gettype($query_params)
2754
+				),
2755
+				'4.6.0'
2756
+			);
2757
+			$query_params = [];
2758
+		}
2759
+		// we're just going to use the query params on the related model's normal get_all query,
2760
+		// except add a condition to say to match the current mod
2761
+		if (! isset($query_params['default_where_conditions'])) {
2762
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2763
+		}
2764
+		$this_model_name                                                 = $this->get_this_model_name();
2765
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2766
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2767
+		return $related_model->sum($query_params, $field_to_sum);
2768
+	}
2769
+
2770
+
2771
+	/**
2772
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2773
+	 * $modelObject
2774
+	 *
2775
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2776
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2777
+	 * @param array               $query_params     see github link below for more info
2778
+	 * @return EE_Base_Class
2779
+	 * @throws EE_Error
2780
+	 * @throws ReflectionException
2781
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2782
+	 */
2783
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2784
+	{
2785
+		$query_params['limit'] = 1;
2786
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2787
+		if ($results) {
2788
+			return array_shift($results);
2789
+		}
2790
+		return null;
2791
+	}
2792
+
2793
+
2794
+	/**
2795
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2796
+	 *
2797
+	 * @return string
2798
+	 */
2799
+	public function get_this_model_name()
2800
+	{
2801
+		return str_replace("EEM_", "", get_class($this));
2802
+	}
2803
+
2804
+
2805
+	/**
2806
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2807
+	 *
2808
+	 * @return EE_Any_Foreign_Model_Name_Field
2809
+	 * @throws EE_Error
2810
+	 */
2811
+	public function get_field_containing_related_model_name()
2812
+	{
2813
+		foreach ($this->field_settings(true) as $field) {
2814
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2815
+				$field_with_model_name = $field;
2816
+			}
2817
+		}
2818
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2819
+			throw new EE_Error(
2820
+				sprintf(
2821
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2822
+					$this->get_this_model_name()
2823
+				)
2824
+			);
2825
+		}
2826
+		return $field_with_model_name;
2827
+	}
2828
+
2829
+
2830
+	/**
2831
+	 * Inserts a new entry into the database, for each table.
2832
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2833
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2834
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2835
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2836
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2837
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2838
+	 *
2839
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2840
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2841
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2842
+	 *                              of EEM_Base)
2843
+	 * @return int|string new primary key on main table that got inserted
2844
+	 * @throws EE_Error
2845
+	 * @throws ReflectionException
2846
+	 */
2847
+	public function insert($field_n_values)
2848
+	{
2849
+		/**
2850
+		 * Filters the fields and their values before inserting an item using the models
2851
+		 *
2852
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2853
+		 * @param EEM_Base $model           the model used
2854
+		 */
2855
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2856
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2857
+			$main_table = $this->_get_main_table();
2858
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2859
+			if ($new_id !== false) {
2860
+				foreach ($this->_get_other_tables() as $other_table) {
2861
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2862
+				}
2863
+			}
2864
+			/**
2865
+			 * Done just after attempting to insert a new model object
2866
+			 *
2867
+			 * @param EEM_Base $model           used
2868
+			 * @param array    $fields_n_values fields and their values
2869
+			 * @param int|string the              ID of the newly-inserted model object
2870
+			 */
2871
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2872
+			return $new_id;
2873
+		}
2874
+		return false;
2875
+	}
2876
+
2877
+
2878
+	/**
2879
+	 * Checks that the result would satisfy the unique indexes on this model
2880
+	 *
2881
+	 * @param array  $field_n_values
2882
+	 * @param string $action
2883
+	 * @return boolean
2884
+	 * @throws EE_Error
2885
+	 * @throws ReflectionException
2886
+	 */
2887
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2888
+	{
2889
+		foreach ($this->unique_indexes() as $index_name => $index) {
2890
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2891
+			if ($this->exists([$uniqueness_where_params])) {
2892
+				EE_Error::add_error(
2893
+					sprintf(
2894
+						esc_html__(
2895
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2896
+							"event_espresso"
2897
+						),
2898
+						$action,
2899
+						$this->_get_class_name(),
2900
+						$index_name,
2901
+						implode(",", $index->field_names()),
2902
+						http_build_query($uniqueness_where_params)
2903
+					),
2904
+					__FILE__,
2905
+					__FUNCTION__,
2906
+					__LINE__
2907
+				);
2908
+				return false;
2909
+			}
2910
+		}
2911
+		return true;
2912
+	}
2913
+
2914
+
2915
+	/**
2916
+	 * Checks the database for an item that conflicts (ie, if this item were
2917
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2918
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2919
+	 * can be either an EE_Base_Class or an array of fields n values
2920
+	 *
2921
+	 * @param EE_Base_Class|array $obj_or_fields_array
2922
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2923
+	 *                                                 when looking for conflicts
2924
+	 *                                                 (ie, if false, we ignore the model object's primary key
2925
+	 *                                                 when finding "conflicts". If true, it's also considered).
2926
+	 *                                                 Only works for INT primary key,
2927
+	 *                                                 STRING primary keys cannot be ignored
2928
+	 * @return EE_Base_Class|array
2929
+	 * @throws EE_Error
2930
+	 * @throws ReflectionException
2931
+	 */
2932
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2933
+	{
2934
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2935
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2936
+		} elseif (is_array($obj_or_fields_array)) {
2937
+			$fields_n_values = $obj_or_fields_array;
2938
+		} else {
2939
+			throw new EE_Error(
2940
+				sprintf(
2941
+					esc_html__(
2942
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2943
+						"event_espresso"
2944
+					),
2945
+					get_class($this),
2946
+					$obj_or_fields_array
2947
+				)
2948
+			);
2949
+		}
2950
+		$query_params = [];
2951
+		if (
2952
+			$this->has_primary_key_field()
2953
+			&& ($include_primary_key
2954
+				|| $this->get_primary_key_field()
2955
+				   instanceof
2956
+				   EE_Primary_Key_String_Field)
2957
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2958
+		) {
2959
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2960
+		}
2961
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2962
+			$uniqueness_where_params                              =
2963
+				array_intersect_key($fields_n_values, $unique_index->fields());
2964
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2965
+		}
2966
+		// if there is nothing to base this search on, then we shouldn't find anything
2967
+		if (empty($query_params)) {
2968
+			return [];
2969
+		}
2970
+		return $this->get_one($query_params);
2971
+	}
2972
+
2973
+
2974
+	/**
2975
+	 * Like count, but is optimized and returns a boolean instead of an int
2976
+	 *
2977
+	 * @param array $query_params
2978
+	 * @return boolean
2979
+	 * @throws EE_Error
2980
+	 * @throws ReflectionException
2981
+	 */
2982
+	public function exists($query_params)
2983
+	{
2984
+		$query_params['limit'] = 1;
2985
+		return $this->count($query_params) > 0;
2986
+	}
2987
+
2988
+
2989
+	/**
2990
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2991
+	 *
2992
+	 * @param int|string $id
2993
+	 * @return boolean
2994
+	 * @throws EE_Error
2995
+	 * @throws ReflectionException
2996
+	 */
2997
+	public function exists_by_ID($id)
2998
+	{
2999
+		return $this->exists(
3000
+			[
3001
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3002
+				[
3003
+					$this->primary_key_name() => $id,
3004
+				],
3005
+			]
3006
+		);
3007
+	}
3008
+
3009
+
3010
+	/**
3011
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3012
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3013
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3014
+	 * on the main table)
3015
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3016
+	 * cases where we want to call it directly rather than via insert().
3017
+	 *
3018
+	 * @access   protected
3019
+	 * @param EE_Table_Base $table
3020
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3021
+	 *                                       float
3022
+	 * @param int           $new_id          for now we assume only int keys
3023
+	 * @return int ID of new row inserted, or FALSE on failure
3024
+	 * @throws EE_Error
3025
+	 * @throws ReflectionException
3026
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3027
+	 */
3028
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3029
+	{
3030
+		global $wpdb;
3031
+		$insertion_col_n_values = [];
3032
+		$format_for_insertion   = [];
3033
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3034
+		foreach ($fields_on_table as $field_obj) {
3035
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3036
+			if ($field_obj->is_auto_increment()) {
3037
+				continue;
3038
+			}
3039
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3040
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3041
+			if ($prepared_value !== null) {
3042
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3043
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3044
+			}
3045
+		}
3046
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3047
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3048
+			// so add the fk to the main table as a column
3049
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3050
+			$format_for_insertion[]                              =
3051
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3052
+		}
3053
+		// insert the new entry
3054
+		$result = $this->_do_wpdb_query(
3055
+			'insert',
3056
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3057
+		);
3058
+		if ($result === false) {
3059
+			return false;
3060
+		}
3061
+		// ok, now what do we return for the ID of the newly-inserted thing?
3062
+		if ($this->has_primary_key_field()) {
3063
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3064
+				return $wpdb->insert_id;
3065
+			}
3066
+			// it's not an auto-increment primary key, so
3067
+			// it must have been supplied
3068
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3069
+		}
3070
+		// we can't return a  primary key because there is none. instead return
3071
+		// a unique string indicating this model
3072
+		return $this->get_index_primary_key_string($fields_n_values);
3073
+	}
3074
+
3075
+
3076
+	/**
3077
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3078
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3079
+	 * and there is no default, we pass it along. WPDB will take care of it)
3080
+	 *
3081
+	 * @param EE_Model_Field_Base $field_obj
3082
+	 * @param array               $fields_n_values
3083
+	 * @return mixed string|int|float depending on what the table column will be expecting
3084
+	 * @throws EE_Error
3085
+	 */
3086
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3087
+	{
3088
+		// if this field doesn't allow nullable, don't allow it
3089
+		if (
3090
+			! $field_obj->is_nullable()
3091
+			&& (
3092
+				! isset($fields_n_values[ $field_obj->get_name() ])
3093
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3094
+			)
3095
+		) {
3096
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3097
+		}
3098
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3099
+			? $fields_n_values[ $field_obj->get_name() ]
3100
+			: null;
3101
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3102
+	}
3103
+
3104
+
3105
+	/**
3106
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3107
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3108
+	 * the field's prepare_for_set() method.
3109
+	 *
3110
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3111
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3112
+	 *                                   top of file)
3113
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3114
+	 *                                   $value is a custom selection
3115
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3116
+	 */
3117
+	private function _prepare_value_for_use_in_db($value, $field)
3118
+	{
3119
+		if ($field && $field instanceof EE_Model_Field_Base) {
3120
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3121
+			switch ($this->_values_already_prepared_by_model_object) {
3122
+				/** @noinspection PhpMissingBreakStatementInspection */
3123
+				case self::not_prepared_by_model_object:
3124
+					$value = $field->prepare_for_set($value);
3125
+				// purposefully left out "return"
3126
+				case self::prepared_by_model_object:
3127
+					/** @noinspection SuspiciousAssignmentsInspection */
3128
+					$value = $field->prepare_for_use_in_db($value);
3129
+				case self::prepared_for_use_in_db:
3130
+					// leave the value alone
3131
+			}
3132
+			return $value;
3133
+			// phpcs:enable
3134
+		}
3135
+		return $value;
3136
+	}
3137
+
3138
+
3139
+	/**
3140
+	 * Returns the main table on this model
3141
+	 *
3142
+	 * @return EE_Primary_Table
3143
+	 * @throws EE_Error
3144
+	 */
3145
+	protected function _get_main_table()
3146
+	{
3147
+		foreach ($this->_tables as $table) {
3148
+			if ($table instanceof EE_Primary_Table) {
3149
+				return $table;
3150
+			}
3151
+		}
3152
+		throw new EE_Error(
3153
+			sprintf(
3154
+				esc_html__(
3155
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3156
+					'event_espresso'
3157
+				),
3158
+				get_class($this)
3159
+			)
3160
+		);
3161
+	}
3162
+
3163
+
3164
+	/**
3165
+	 * table
3166
+	 * returns EE_Primary_Table table name
3167
+	 *
3168
+	 * @return string
3169
+	 * @throws EE_Error
3170
+	 */
3171
+	public function table()
3172
+	{
3173
+		return $this->_get_main_table()->get_table_name();
3174
+	}
3175
+
3176
+
3177
+	/**
3178
+	 * table
3179
+	 * returns first EE_Secondary_Table table name
3180
+	 *
3181
+	 * @return string
3182
+	 */
3183
+	public function second_table()
3184
+	{
3185
+		// grab second table from tables array
3186
+		$second_table = end($this->_tables);
3187
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * get_table_obj_by_alias
3193
+	 * returns table name given it's alias
3194
+	 *
3195
+	 * @param string $table_alias
3196
+	 * @return EE_Primary_Table | EE_Secondary_Table
3197
+	 */
3198
+	public function get_table_obj_by_alias($table_alias = '')
3199
+	{
3200
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3201
+	}
3202
+
3203
+
3204
+	/**
3205
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3206
+	 *
3207
+	 * @return EE_Secondary_Table[]
3208
+	 */
3209
+	protected function _get_other_tables()
3210
+	{
3211
+		$other_tables = [];
3212
+		foreach ($this->_tables as $table_alias => $table) {
3213
+			if ($table instanceof EE_Secondary_Table) {
3214
+				$other_tables[ $table_alias ] = $table;
3215
+			}
3216
+		}
3217
+		return $other_tables;
3218
+	}
3219
+
3220
+
3221
+	/**
3222
+	 * Finds all the fields that correspond to the given table
3223
+	 *
3224
+	 * @param string $table_alias , array key in EEM_Base::_tables
3225
+	 * @return EE_Model_Field_Base[]
3226
+	 */
3227
+	public function _get_fields_for_table($table_alias)
3228
+	{
3229
+		return $this->_fields[ $table_alias ];
3230
+	}
3231
+
3232
+
3233
+	/**
3234
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3235
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3236
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3237
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3238
+	 * related Registration, Transaction, and Payment models.
3239
+	 *
3240
+	 * @param array $query_params see github link below for more info
3241
+	 * @return EE_Model_Query_Info_Carrier
3242
+	 * @throws EE_Error
3243
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3244
+	 */
3245
+	public function _extract_related_models_from_query($query_params)
3246
+	{
3247
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3248
+		if (array_key_exists(0, $query_params)) {
3249
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3250
+		}
3251
+		if (array_key_exists('group_by', $query_params)) {
3252
+			if (is_array($query_params['group_by'])) {
3253
+				$this->_extract_related_models_from_sub_params_array_values(
3254
+					$query_params['group_by'],
3255
+					$query_info_carrier,
3256
+					'group_by'
3257
+				);
3258
+			} elseif (! empty($query_params['group_by'])) {
3259
+				$this->_extract_related_model_info_from_query_param(
3260
+					$query_params['group_by'],
3261
+					$query_info_carrier,
3262
+					'group_by'
3263
+				);
3264
+			}
3265
+		}
3266
+		if (array_key_exists('having', $query_params)) {
3267
+			$this->_extract_related_models_from_sub_params_array_keys(
3268
+				$query_params[0],
3269
+				$query_info_carrier,
3270
+				'having'
3271
+			);
3272
+		}
3273
+		if (array_key_exists('order_by', $query_params)) {
3274
+			if (is_array($query_params['order_by'])) {
3275
+				$this->_extract_related_models_from_sub_params_array_keys(
3276
+					$query_params['order_by'],
3277
+					$query_info_carrier,
3278
+					'order_by'
3279
+				);
3280
+			} elseif (! empty($query_params['order_by'])) {
3281
+				$this->_extract_related_model_info_from_query_param(
3282
+					$query_params['order_by'],
3283
+					$query_info_carrier,
3284
+					'order_by'
3285
+				);
3286
+			}
3287
+		}
3288
+		if (array_key_exists('force_join', $query_params)) {
3289
+			$this->_extract_related_models_from_sub_params_array_values(
3290
+				$query_params['force_join'],
3291
+				$query_info_carrier,
3292
+				'force_join'
3293
+			);
3294
+		}
3295
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3296
+		return $query_info_carrier;
3297
+	}
3298
+
3299
+
3300
+	/**
3301
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3302
+	 *
3303
+	 * @param array                       $sub_query_params
3304
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3306
+	 * @throws EE_Error
3307
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3308
+	 */
3309
+	private function _extract_related_models_from_sub_params_array_keys(
3310
+		$sub_query_params,
3311
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
+		$query_param_type
3313
+	) {
3314
+		if (! empty($sub_query_params)) {
3315
+			$sub_query_params = (array)$sub_query_params;
3316
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3317
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3318
+				$this->_extract_related_model_info_from_query_param(
3319
+					$param,
3320
+					$model_query_info_carrier,
3321
+					$query_param_type
3322
+				);
3323
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3324
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3325
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3326
+				// of array('Registration.TXN_ID'=>23)
3327
+				$query_param_sans_stars =
3328
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3329
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3330
+					if (! is_array($possibly_array_of_params)) {
3331
+						throw new EE_Error(
3332
+							sprintf(
3333
+								esc_html__(
3334
+									"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3335
+									"event_espresso"
3336
+								),
3337
+								$param,
3338
+								$possibly_array_of_params
3339
+							)
3340
+						);
3341
+					}
3342
+					$this->_extract_related_models_from_sub_params_array_keys(
3343
+						$possibly_array_of_params,
3344
+						$model_query_info_carrier,
3345
+						$query_param_type
3346
+					);
3347
+				} elseif (
3348
+					$query_param_type === 0 // ie WHERE
3349
+					&& is_array($possibly_array_of_params)
3350
+					&& isset($possibly_array_of_params[2])
3351
+					&& $possibly_array_of_params[2] == true
3352
+				) {
3353
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3354
+					// indicating that $possible_array_of_params[1] is actually a field name,
3355
+					// from which we should extract query parameters!
3356
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3357
+						throw new EE_Error(
3358
+							sprintf(
3359
+								esc_html__(
3360
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3361
+									"event_espresso"
3362
+								),
3363
+								$query_param_type,
3364
+								implode(",", $possibly_array_of_params)
3365
+							)
3366
+						);
3367
+					}
3368
+					$this->_extract_related_model_info_from_query_param(
3369
+						$possibly_array_of_params[1],
3370
+						$model_query_info_carrier,
3371
+						$query_param_type
3372
+					);
3373
+				}
3374
+			}
3375
+		}
3376
+	}
3377
+
3378
+
3379
+	/**
3380
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3381
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3382
+	 *
3383
+	 * @param array                       $sub_query_params
3384
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3385
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3386
+	 * @throws EE_Error
3387
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3388
+	 */
3389
+	private function _extract_related_models_from_sub_params_array_values(
3390
+		$sub_query_params,
3391
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392
+		$query_param_type
3393
+	) {
3394
+		if (! empty($sub_query_params)) {
3395
+			if (! is_array($sub_query_params)) {
3396
+				throw new EE_Error(
3397
+					sprintf(
3398
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
+						$sub_query_params
3400
+					)
3401
+				);
3402
+			}
3403
+			foreach ($sub_query_params as $param) {
3404
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3405
+				$this->_extract_related_model_info_from_query_param(
3406
+					$param,
3407
+					$model_query_info_carrier,
3408
+					$query_param_type
3409
+				);
3410
+			}
3411
+		}
3412
+	}
3413
+
3414
+
3415
+	/**
3416
+	 * Extract all the query parts from  model query params
3417
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
+	 * but use them in a different order. Eg, we need to know what models we are querying
3420
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
+	 * other models before we can finalize the where clause SQL.
3422
+	 *
3423
+	 * @param array $query_params see github link below for more info
3424
+	 * @return EE_Model_Query_Info_Carrier
3425
+	 * @throws EE_Error
3426
+	 * @throws ModelConfigurationException
3427
+	 * @throws ReflectionException
3428
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3429
+	 */
3430
+	public function _create_model_query_info_carrier($query_params)
3431
+	{
3432
+		if (! is_array($query_params)) {
3433
+			EE_Error::doing_it_wrong(
3434
+				'EEM_Base::_create_model_query_info_carrier',
3435
+				sprintf(
3436
+					esc_html__(
3437
+						'$query_params should be an array, you passed a variable of type %s',
3438
+						'event_espresso'
3439
+					),
3440
+					gettype($query_params)
3441
+				),
3442
+				'4.6.0'
3443
+			);
3444
+			$query_params = [];
3445
+		}
3446
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3447
+		// first check if we should alter the query to account for caps or not
3448
+		// because the caps might require us to do extra joins
3449
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3450
+			$query_params[0] = array_replace_recursive(
3451
+				$query_params[0],
3452
+				$this->caps_where_conditions(
3453
+					$query_params['caps']
3454
+				)
3455
+			);
3456
+		}
3457
+
3458
+		// check if we should alter the query to remove data related to protected
3459
+		// custom post types
3460
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3461
+			$where_param_key_for_password = $this->modelChainAndPassword();
3462
+			// only include if related to a cpt where no password has been set
3463
+			$query_params[0]['OR*nopassword'] = [
3464
+				$where_param_key_for_password       => '',
3465
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3466
+			];
3467
+		}
3468
+		$query_object = $this->_extract_related_models_from_query($query_params);
3469
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3470
+		foreach ($query_params[0] as $key => $value) {
3471
+			if (is_int($key)) {
3472
+				throw new EE_Error(
3473
+					sprintf(
3474
+						esc_html__(
3475
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3476
+							"event_espresso"
3477
+						),
3478
+						$key,
3479
+						var_export($value, true),
3480
+						var_export($query_params, true),
3481
+						get_class($this)
3482
+					)
3483
+				);
3484
+			}
3485
+		}
3486
+		if (
3487
+			array_key_exists('default_where_conditions', $query_params)
3488
+			&& ! empty($query_params['default_where_conditions'])
3489
+		) {
3490
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3491
+		} else {
3492
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3493
+		}
3494
+		$query_params[0] = array_merge(
3495
+			$this->_get_default_where_conditions_for_models_in_query(
3496
+				$query_object,
3497
+				$use_default_where_conditions,
3498
+				$query_params[0]
3499
+			),
3500
+			$query_params[0]
3501
+		);
3502
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3503
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3504
+		// So we need to setup a subquery and use that for the main join.
3505
+		// Note for now this only works on the primary table for the model.
3506
+		// So for instance, you could set the limit array like this:
3507
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3508
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3509
+			$query_object->set_main_model_join_sql(
3510
+				$this->_construct_limit_join_select(
3511
+					$query_params['on_join_limit'][0],
3512
+					$query_params['on_join_limit'][1]
3513
+				)
3514
+			);
3515
+		}
3516
+		// set limit
3517
+		if (array_key_exists('limit', $query_params)) {
3518
+			if (is_array($query_params['limit'])) {
3519
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3520
+					$e = sprintf(
3521
+						esc_html__(
3522
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3523
+							"event_espresso"
3524
+						),
3525
+						http_build_query($query_params['limit'])
3526
+					);
3527
+					throw new EE_Error($e . "|" . $e);
3528
+				}
3529
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3530
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3531
+			} elseif (! empty($query_params['limit'])) {
3532
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3533
+			}
3534
+		}
3535
+		// set order by
3536
+		if (array_key_exists('order_by', $query_params)) {
3537
+			if (is_array($query_params['order_by'])) {
3538
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3539
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3540
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3541
+				if (array_key_exists('order', $query_params)) {
3542
+					throw new EE_Error(
3543
+						sprintf(
3544
+							esc_html__(
3545
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3546
+								"event_espresso"
3547
+							),
3548
+							get_class($this),
3549
+							implode(", ", array_keys($query_params['order_by'])),
3550
+							implode(", ", $query_params['order_by']),
3551
+							$query_params['order']
3552
+						)
3553
+					);
3554
+				}
3555
+				$this->_extract_related_models_from_sub_params_array_keys(
3556
+					$query_params['order_by'],
3557
+					$query_object,
3558
+					'order_by'
3559
+				);
3560
+				// assume it's an array of fields to order by
3561
+				$order_array = [];
3562
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3563
+					$order         = $this->_extract_order($order);
3564
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3565
+				}
3566
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3567
+			} elseif (! empty($query_params['order_by'])) {
3568
+				$this->_extract_related_model_info_from_query_param(
3569
+					$query_params['order_by'],
3570
+					$query_object,
3571
+					'order',
3572
+					$query_params['order_by']
3573
+				);
3574
+				$order = isset($query_params['order'])
3575
+					? $this->_extract_order($query_params['order'])
3576
+					: 'DESC';
3577
+				$query_object->set_order_by_sql(
3578
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3579
+				);
3580
+			}
3581
+		}
3582
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3583
+		if (
3584
+			! array_key_exists('order_by', $query_params)
3585
+			&& array_key_exists('order', $query_params)
3586
+			&& ! empty($query_params['order'])
3587
+		) {
3588
+			$pk_field = $this->get_primary_key_field();
3589
+			$order    = $this->_extract_order($query_params['order']);
3590
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3591
+		}
3592
+		// set group by
3593
+		if (array_key_exists('group_by', $query_params)) {
3594
+			if (is_array($query_params['group_by'])) {
3595
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3596
+				$group_by_array = [];
3597
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3598
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3599
+				}
3600
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3601
+			} elseif (! empty($query_params['group_by'])) {
3602
+				$query_object->set_group_by_sql(
3603
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3604
+				);
3605
+			}
3606
+		}
3607
+		// set having
3608
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3609
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3610
+		}
3611
+		// now, just verify they didn't pass anything wack
3612
+		foreach ($query_params as $query_key => $query_value) {
3613
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3614
+				throw new EE_Error(
3615
+					sprintf(
3616
+						esc_html__(
3617
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3618
+							'event_espresso'
3619
+						),
3620
+						$query_key,
3621
+						get_class($this),
3622
+						//                      print_r( $this->_allowed_query_params, TRUE )
3623
+						implode(',', $this->_allowed_query_params)
3624
+					)
3625
+				);
3626
+			}
3627
+		}
3628
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3629
+		if (empty($main_model_join_sql)) {
3630
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3631
+		}
3632
+		return $query_object;
3633
+	}
3634
+
3635
+
3636
+	/**
3637
+	 * Gets the where conditions that should be imposed on the query based on the
3638
+	 * context (eg reading frontend, backend, edit or delete).
3639
+	 *
3640
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3641
+	 * @return array
3642
+	 * @throws EE_Error
3643
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3644
+	 */
3645
+	public function caps_where_conditions($context = self::caps_read)
3646
+	{
3647
+		EEM_Base::verify_is_valid_cap_context($context);
3648
+		$cap_where_conditions = [];
3649
+		$cap_restrictions     = $this->caps_missing($context);
3650
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3651
+			$cap_where_conditions = array_replace_recursive(
3652
+				$cap_where_conditions,
3653
+				$restriction_if_no_cap->get_default_where_conditions()
3654
+			);
3655
+		}
3656
+		return apply_filters(
3657
+			'FHEE__EEM_Base__caps_where_conditions__return',
3658
+			$cap_where_conditions,
3659
+			$this,
3660
+			$context,
3661
+			$cap_restrictions
3662
+		);
3663
+	}
3664
+
3665
+
3666
+	/**
3667
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3668
+	 * otherwise throws an exception
3669
+	 *
3670
+	 * @param string $should_be_order_string
3671
+	 * @return string either ASC, asc, DESC or desc
3672
+	 * @throws EE_Error
3673
+	 */
3674
+	private function _extract_order($should_be_order_string)
3675
+	{
3676
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3677
+			return $should_be_order_string;
3678
+		}
3679
+		throw new EE_Error(
3680
+			sprintf(
3681
+				esc_html__(
3682
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3683
+					"event_espresso"
3684
+				),
3685
+				get_class($this),
3686
+				$should_be_order_string
3687
+			)
3688
+		);
3689
+	}
3690
+
3691
+
3692
+	/**
3693
+	 * Looks at all the models which are included in this query, and asks each
3694
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3695
+	 * so they can be merged
3696
+	 *
3697
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3698
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3699
+	 *                                                                  'none' means NO default where conditions will
3700
+	 *                                                                  be used AT ALL during this query.
3701
+	 *                                                                  'other_models_only' means default where
3702
+	 *                                                                  conditions from other models will be used, but
3703
+	 *                                                                  not for this primary model. 'all', the default,
3704
+	 *                                                                  means default where conditions will apply as
3705
+	 *                                                                  normal
3706
+	 * @param array                       $where_query_params
3707
+	 * @return array
3708
+	 * @throws EE_Error
3709
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3710
+	 */
3711
+	private function _get_default_where_conditions_for_models_in_query(
3712
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3713
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3714
+		$where_query_params = []
3715
+	) {
3716
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3717
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3718
+			throw new EE_Error(
3719
+				sprintf(
3720
+					esc_html__(
3721
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3722
+						"event_espresso"
3723
+					),
3724
+					$use_default_where_conditions,
3725
+					implode(", ", $allowed_used_default_where_conditions_values)
3726
+				)
3727
+			);
3728
+		}
3729
+		$universal_query_params = [];
3730
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3731
+			$universal_query_params = $this->_get_default_where_conditions();
3732
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3733
+			$universal_query_params = $this->_get_minimum_where_conditions();
3734
+		}
3735
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
+			$related_model = $this->get_related_model_obj($model_name);
3737
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
+				$related_model_universal_where_params =
3739
+					$related_model->_get_default_where_conditions($model_relation_path);
3740
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3741
+				$related_model_universal_where_params =
3742
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3743
+			} else {
3744
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3745
+				continue;
3746
+			}
3747
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3748
+				$related_model_universal_where_params,
3749
+				$where_query_params,
3750
+				$related_model,
3751
+				$model_relation_path
3752
+			);
3753
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3754
+				$universal_query_params,
3755
+				$overrides
3756
+			);
3757
+		}
3758
+		return $universal_query_params;
3759
+	}
3760
+
3761
+
3762
+	/**
3763
+	 * Determines whether or not we should use default where conditions for the model in question
3764
+	 * (this model, or other related models).
3765
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3766
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3767
+	 * We should use default where conditions on related models when they requested to use default where conditions
3768
+	 * on all models, or specifically just on other related models
3769
+	 *
3770
+	 * @param      $default_where_conditions_value
3771
+	 * @param bool $for_this_model false means this is for OTHER related models
3772
+	 * @return bool
3773
+	 */
3774
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3775
+	{
3776
+		return (
3777
+				   $for_this_model
3778
+				   && in_array(
3779
+					   $default_where_conditions_value,
3780
+					   [
3781
+						   EEM_Base::default_where_conditions_all,
3782
+						   EEM_Base::default_where_conditions_this_only,
3783
+						   EEM_Base::default_where_conditions_minimum_others,
3784
+					   ],
3785
+					   true
3786
+				   )
3787
+			   )
3788
+			   || (
3789
+				   ! $for_this_model
3790
+				   && in_array(
3791
+					   $default_where_conditions_value,
3792
+					   [
3793
+						   EEM_Base::default_where_conditions_all,
3794
+						   EEM_Base::default_where_conditions_others_only,
3795
+					   ],
3796
+					   true
3797
+				   )
3798
+			   );
3799
+	}
3800
+
3801
+
3802
+	/**
3803
+	 * Determines whether or not we should use default minimum conditions for the model in question
3804
+	 * (this model, or other related models).
3805
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3806
+	 * where conditions.
3807
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3808
+	 * on this model or others
3809
+	 *
3810
+	 * @param      $default_where_conditions_value
3811
+	 * @param bool $for_this_model false means this is for OTHER related models
3812
+	 * @return bool
3813
+	 */
3814
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3815
+	{
3816
+		return (
3817
+				   $for_this_model
3818
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3819
+			   )
3820
+			   || (
3821
+				   ! $for_this_model
3822
+				   && in_array(
3823
+					   $default_where_conditions_value,
3824
+					   [
3825
+						   EEM_Base::default_where_conditions_minimum_others,
3826
+						   EEM_Base::default_where_conditions_minimum_all,
3827
+					   ],
3828
+					   true
3829
+				   )
3830
+			   );
3831
+	}
3832
+
3833
+
3834
+	/**
3835
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3836
+	 * then we also add a special where condition which allows for that model's primary key
3837
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3838
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3839
+	 *
3840
+	 * @param array    $default_where_conditions
3841
+	 * @param array    $provided_where_conditions
3842
+	 * @param EEM_Base $model
3843
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3844
+	 * @return array
3845
+	 * @throws EE_Error
3846
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3847
+	 */
3848
+	private function _override_defaults_or_make_null_friendly(
3849
+		$default_where_conditions,
3850
+		$provided_where_conditions,
3851
+		$model,
3852
+		$model_relation_path
3853
+	) {
3854
+		$null_friendly_where_conditions = [];
3855
+		$none_overridden                = true;
3856
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3857
+		foreach ($default_where_conditions as $key => $val) {
3858
+			if (isset($provided_where_conditions[ $key ])) {
3859
+				$none_overridden = false;
3860
+			} else {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3862
+			}
3863
+		}
3864
+		if ($none_overridden && $default_where_conditions) {
3865
+			if ($model->has_primary_key_field()) {
3866
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3867
+																				   . "."
3868
+																				   . $model->primary_key_name() ] =
3869
+					['IS NULL'];
3870
+			}/*else{
3871 3871
                 //@todo NO PK, use other defaults
3872 3872
             }*/
3873
-        }
3874
-        return $null_friendly_where_conditions;
3875
-    }
3876
-
3877
-
3878
-    /**
3879
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3880
-     * default where conditions on all get_all, update, and delete queries done by this model.
3881
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3882
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3883
-     *
3884
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3885
-     * @return array
3886
-     * @throws EE_Error
3887
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3888
-     */
3889
-    private function _get_default_where_conditions($model_relation_path = '')
3890
-    {
3891
-        if ($this->_ignore_where_strategy) {
3892
-            return [];
3893
-        }
3894
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3895
-    }
3896
-
3897
-
3898
-    /**
3899
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3900
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3901
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3902
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3903
-     * Similar to _get_default_where_conditions
3904
-     *
3905
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3906
-     * @return array
3907
-     * @throws EE_Error
3908
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3909
-     */
3910
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3911
-    {
3912
-        if ($this->_ignore_where_strategy) {
3913
-            return [];
3914
-        }
3915
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3916
-    }
3917
-
3918
-
3919
-    /**
3920
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3921
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3922
-     *
3923
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3924
-     * @return string
3925
-     * @throws EE_Error
3926
-     */
3927
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3928
-    {
3929
-        $selects = $this->_get_columns_to_select_for_this_model();
3930
-        foreach (
3931
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3932
-        ) {
3933
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3934
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3935
-            foreach ($other_model_selects as $value) {
3936
-                $selects[] = $value;
3937
-            }
3938
-        }
3939
-        return implode(", ", $selects);
3940
-    }
3941
-
3942
-
3943
-    /**
3944
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3945
-     * So that's going to be the columns for all the fields on the model
3946
-     *
3947
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3948
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3949
-     */
3950
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3951
-    {
3952
-        $fields                                       = $this->field_settings();
3953
-        $selects                                      = [];
3954
-        $table_alias_with_model_relation_chain_prefix =
3955
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3956
-                $model_relation_chain,
3957
-                $this->get_this_model_name()
3958
-            );
3959
-        foreach ($fields as $field_obj) {
3960
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3961
-                         . $field_obj->get_table_alias()
3962
-                         . "."
3963
-                         . $field_obj->get_table_column()
3964
-                         . " AS '"
3965
-                         . $table_alias_with_model_relation_chain_prefix
3966
-                         . $field_obj->get_table_alias()
3967
-                         . "."
3968
-                         . $field_obj->get_table_column()
3969
-                         . "'";
3970
-        }
3971
-        // make sure we are also getting the PKs of each table
3972
-        $tables = $this->get_tables();
3973
-        if (count($tables) > 1) {
3974
-            foreach ($tables as $table_obj) {
3975
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3976
-                                       . $table_obj->get_fully_qualified_pk_column();
3977
-                if (! in_array($qualified_pk_column, $selects)) {
3978
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3979
-                }
3980
-            }
3981
-        }
3982
-        return $selects;
3983
-    }
3984
-
3985
-
3986
-    /**
3987
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3988
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3989
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3990
-     * SQL for joining, and the data types
3991
-     *
3992
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3993
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3994
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3995
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3996
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3997
-     *                                                          or 'Registration's
3998
-     * @param string|null                 $original_query_param what it originally was (eg
3999
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4000
-     *                                                          matches $query_param
4001
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4002
-     * @throws EE_Error
4003
-     */
4004
-    private function _extract_related_model_info_from_query_param(
4005
-        $query_param,
4006
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4007
-        $query_param_type,
4008
-        $original_query_param = null
4009
-    ) {
4010
-        if ($original_query_param === null) {
4011
-            $original_query_param = $query_param;
4012
-        }
4013
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4014
-        // whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4015
-        $allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4016
-        $allow_fields             = in_array(
4017
-            $query_param_type,
4018
-            ['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4019
-            true
4020
-        );
4021
-        // check to see if we have a field on this model
4022
-        $this_model_fields = $this->field_settings(true);
4023
-        if (array_key_exists($query_param, $this_model_fields)) {
4024
-            if ($allow_fields) {
4025
-                return;
4026
-            }
4027
-            throw new EE_Error(
4028
-                sprintf(
4029
-                    esc_html__(
4030
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4031
-                        "event_espresso"
4032
-                    ),
4033
-                    $query_param,
4034
-                    get_class($this),
4035
-                    $query_param_type,
4036
-                    $original_query_param
4037
-                )
4038
-            );
4039
-        }
4040
-        // check if this is a special logic query param
4041
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4042
-            if ($allow_logic_query_params) {
4043
-                return;
4044
-            }
4045
-            throw new EE_Error(
4046
-                sprintf(
4047
-                    esc_html__(
4048
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4049
-                        'event_espresso'
4050
-                    ),
4051
-                    implode('", "', $this->_logic_query_param_keys),
4052
-                    $query_param,
4053
-                    get_class($this),
4054
-                    '<br />',
4055
-                    "\t"
4056
-                    . ' $passed_in_query_info = <pre>'
4057
-                    . print_r($passed_in_query_info, true)
4058
-                    . '</pre>'
4059
-                    . "\n\t"
4060
-                    . ' $query_param_type = '
4061
-                    . $query_param_type
4062
-                    . "\n\t"
4063
-                    . ' $original_query_param = '
4064
-                    . $original_query_param
4065
-                )
4066
-            );
4067
-        }
4068
-        // check if it's a custom selection
4069
-        if (
4070
-            $this->_custom_selections instanceof CustomSelects
4071
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4072
-        ) {
4073
-            return;
4074
-        }
4075
-        // check if has a model name at the beginning
4076
-        // and
4077
-        // check if it's a field on a related model
4078
-        if (
4079
-        $this->extractJoinModelFromQueryParams(
4080
-            $passed_in_query_info,
4081
-            $query_param,
4082
-            $original_query_param,
4083
-            $query_param_type
4084
-        )
4085
-        ) {
4086
-            return;
4087
-        }
4088
-
4089
-        // ok so $query_param didn't start with a model name
4090
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4091
-        // it's wack, that's what it is
4092
-        throw new EE_Error(
4093
-            sprintf(
4094
-                esc_html__(
4095
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4096
-                    "event_espresso"
4097
-                ),
4098
-                $query_param,
4099
-                get_class($this),
4100
-                $query_param_type,
4101
-                $original_query_param
4102
-            )
4103
-        );
4104
-    }
4105
-
4106
-
4107
-    /**
4108
-     * Extracts any possible join model information from the provided possible_join_string.
4109
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4110
-     * join
4111
-     * parts that should be added to the query.
4112
-     *
4113
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4115
-     * @param null|string                 $original_query_param
4116
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4117
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4118
-     *                                                           etc.)
4119
-     * @return bool  returns true if a join was added and false if not.
4120
-     * @throws EE_Error
4121
-     */
4122
-    private function extractJoinModelFromQueryParams(
4123
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4124
-        $possible_join_string,
4125
-        $original_query_param,
4126
-        $query_parameter_type
4127
-    ) {
4128
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4129
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4130
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4131
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4132
-                if ($possible_join_string === '') {
4133
-                    // nothing left to $query_param
4134
-                    // we should actually end in a field name, not a model like this!
4135
-                    throw new EE_Error(
4136
-                        sprintf(
4137
-                            esc_html__(
4138
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4139
-                                "event_espresso"
4140
-                            ),
4141
-                            $possible_join_string,
4142
-                            $query_parameter_type,
4143
-                            get_class($this),
4144
-                            $valid_related_model_name
4145
-                        )
4146
-                    );
4147
-                }
4148
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4149
-                $related_model_obj->_extract_related_model_info_from_query_param(
4150
-                    $possible_join_string,
4151
-                    $query_info_carrier,
4152
-                    $query_parameter_type,
4153
-                    $original_query_param
4154
-                );
4155
-                return true;
4156
-            }
4157
-            if ($possible_join_string === $valid_related_model_name) {
4158
-                $this->_add_join_to_model(
4159
-                    $valid_related_model_name,
4160
-                    $query_info_carrier,
4161
-                    $original_query_param
4162
-                );
4163
-                return true;
4164
-            }
4165
-        }
4166
-        return false;
4167
-    }
4168
-
4169
-
4170
-    /**
4171
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4172
-     *
4173
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4174
-     * @throws EE_Error
4175
-     */
4176
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4177
-    {
4178
-        if (
4179
-            $this->_custom_selections instanceof CustomSelects
4180
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4181
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4182
-            )
4183
-        ) {
4184
-            $original_selects = $this->_custom_selections->originalSelects();
4185
-            foreach ($original_selects as $select_configuration) {
4186
-                $this->extractJoinModelFromQueryParams(
4187
-                    $query_info_carrier,
4188
-                    $select_configuration[0],
4189
-                    $select_configuration[0],
4190
-                    'custom_selects'
4191
-                );
4192
-            }
4193
-        }
4194
-    }
4195
-
4196
-
4197
-    /**
4198
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4199
-     * and store it on $passed_in_query_info
4200
-     *
4201
-     * @param string                      $model_name
4202
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4203
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4204
-     *                                                          model and $model_name. Eg, if we are querying Event,
4205
-     *                                                          and are adding a join to 'Payment' with the original
4206
-     *                                                          query param key
4207
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4208
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4209
-     *                                                          Payment wants to add default query params so that it
4210
-     *                                                          will know what models to prepend onto its default query
4211
-     *                                                          params or in case it wants to rename tables (in case
4212
-     *                                                          there are multiple joins to the same table)
4213
-     * @return void
4214
-     * @throws EE_Error
4215
-     */
4216
-    private function _add_join_to_model(
4217
-        $model_name,
4218
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4219
-        $original_query_param
4220
-    ) {
4221
-        $relation_obj         = $this->related_settings_for($model_name);
4222
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4223
-        // check if the relation is HABTM, because then we're essentially doing two joins
4224
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4225
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4226
-            $join_model_obj = $relation_obj->get_join_model();
4227
-            // replace the model specified with the join model for this relation chain, whi
4228
-            $relation_chain_to_join_model =
4229
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4230
-                    $model_name,
4231
-                    $join_model_obj->get_this_model_name(),
4232
-                    $model_relation_chain
4233
-                );
4234
-            $passed_in_query_info->merge(
4235
-                new EE_Model_Query_Info_Carrier(
4236
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4237
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4238
-                )
4239
-            );
4240
-        }
4241
-        // now just join to the other table pointed to by the relation object, and add its data types
4242
-        $passed_in_query_info->merge(
4243
-            new EE_Model_Query_Info_Carrier(
4244
-                [$model_relation_chain => $model_name],
4245
-                $relation_obj->get_join_statement($model_relation_chain)
4246
-            )
4247
-        );
4248
-    }
4249
-
4250
-
4251
-    /**
4252
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4253
-     *
4254
-     * @param array $where_params
4255
-     * @return string of SQL
4256
-     * @throws EE_Error
4257
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4258
-     */
4259
-    private function _construct_where_clause($where_params)
4260
-    {
4261
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4262
-        if ($SQL) {
4263
-            return " WHERE " . $SQL;
4264
-        }
4265
-        return '';
4266
-    }
4267
-
4268
-
4269
-    /**
4270
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4271
-     * and should be passed HAVING parameters, not WHERE parameters
4272
-     *
4273
-     * @param array $having_params
4274
-     * @return string
4275
-     * @throws EE_Error
4276
-     */
4277
-    private function _construct_having_clause($having_params)
4278
-    {
4279
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4280
-        if ($SQL) {
4281
-            return " HAVING " . $SQL;
4282
-        }
4283
-        return '';
4284
-    }
4285
-
4286
-
4287
-    /**
4288
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4289
-     * Event_Meta.meta_value = 'foo'))"
4290
-     *
4291
-     * @param array  $where_params
4292
-     * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4293
-     * @return string of SQL
4294
-     * @throws EE_Error
4295
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4296
-     */
4297
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4298
-    {
4299
-        $where_clauses = [];
4300
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4301
-            $query_param =
4302
-                $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4303
-                    $query_param
4304
-                );// str_replace("*",'',$query_param);
4305
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4306
-                switch ($query_param) {
4307
-                    case 'not':
4308
-                    case 'NOT':
4309
-                        $where_clauses[] = "! ("
4310
-                                           . $this->_construct_condition_clause_recursive(
4311
-                                $op_and_value_or_sub_condition,
4312
-                                $glue
4313
-                            )
4314
-                                           . ")";
4315
-                        break;
4316
-                    case 'and':
4317
-                    case 'AND':
4318
-                        $where_clauses[] = " ("
4319
-                                           . $this->_construct_condition_clause_recursive(
4320
-                                $op_and_value_or_sub_condition,
4321
-                                ' AND '
4322
-                            )
4323
-                                           . ")";
4324
-                        break;
4325
-                    case 'or':
4326
-                    case 'OR':
4327
-                        $where_clauses[] = " ("
4328
-                                           . $this->_construct_condition_clause_recursive(
4329
-                                $op_and_value_or_sub_condition,
4330
-                                ' OR '
4331
-                            )
4332
-                                           . ")";
4333
-                        break;
4334
-                }
4335
-            } else {
4336
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4337
-                // if it's not a normal field, maybe it's a custom selection?
4338
-                if (! $field_obj) {
4339
-                    if ($this->_custom_selections instanceof CustomSelects) {
4340
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4341
-                    } else {
4342
-                        throw new EE_Error(
4343
-                            sprintf(
4344
-                                esc_html__(
4345
-                                    "%s is neither a valid model field name, nor a custom selection",
4346
-                                    "event_espresso"
4347
-                                ),
4348
-                                $query_param
4349
-                            )
4350
-                        );
4351
-                    }
4352
-                }
4353
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4354
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4355
-            }
4356
-        }
4357
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4358
-    }
4359
-
4360
-
4361
-    /**
4362
-     * Takes the input parameter and extract the table name (alias) and column name
4363
-     *
4364
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4365
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4366
-     * @throws EE_Error
4367
-     */
4368
-    private function _deduce_column_name_from_query_param($query_param)
4369
-    {
4370
-        $field = $this->_deduce_field_from_query_param($query_param);
4371
-        if ($field) {
4372
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4373
-                $field->get_model_name(),
4374
-                $query_param
4375
-            );
4376
-            return $table_alias_prefix . $field->get_qualified_column();
4377
-        }
4378
-        if (
4379
-            $this->_custom_selections instanceof CustomSelects
4380
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4381
-        ) {
4382
-            // maybe it's custom selection item?
4383
-            // if so, just use it as the "column name"
4384
-            return $query_param;
4385
-        }
4386
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4387
-            ? implode(',', $this->_custom_selections->columnAliases())
4388
-            : '';
4389
-        throw new EE_Error(
4390
-            sprintf(
4391
-                esc_html__(
4392
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4393
-                    "event_espresso"
4394
-                ),
4395
-                $query_param,
4396
-                $custom_select_aliases
4397
-            )
4398
-        );
4399
-    }
4400
-
4401
-
4402
-    /**
4403
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4404
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4405
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4406
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4407
-     *
4408
-     * @param string $condition_query_param_key
4409
-     * @return string
4410
-     */
4411
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4412
-    {
4413
-        $pos_of_star = strpos($condition_query_param_key, '*');
4414
-        if ($pos_of_star === false) {
4415
-            return $condition_query_param_key;
4416
-        }
4417
-        return substr($condition_query_param_key, 0, $pos_of_star);
4418
-    }
4419
-
4420
-
4421
-    /**
4422
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4423
-     *
4424
-     * @param mixed      array | string    $op_and_value
4425
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4426
-     * @return string
4427
-     * @throws EE_Error
4428
-     */
4429
-    private function _construct_op_and_value($op_and_value, $field_obj)
4430
-    {
4431
-        if (is_array($op_and_value)) {
4432
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4433
-            if (! $operator) {
4434
-                $php_array_like_string = [];
4435
-                foreach ($op_and_value as $key => $value) {
4436
-                    $php_array_like_string[] = "$key=>$value";
4437
-                }
4438
-                throw new EE_Error(
4439
-                    sprintf(
4440
-                        esc_html__(
4441
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4442
-                            "event_espresso"
4443
-                        ),
4444
-                        implode(",", $php_array_like_string)
4445
-                    )
4446
-                );
4447
-            }
4448
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4449
-        } else {
4450
-            $operator = '=';
4451
-            $value    = $op_and_value;
4452
-        }
4453
-        // check to see if the value is actually another field
4454
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4455
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4456
-        }
4457
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4458
-            // in this case, the value should be an array, or at least a comma-separated list
4459
-            // it will need to handle a little differently
4460
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4461
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4462
-            return $operator . SP . $cleaned_value;
4463
-        }
4464
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4465
-            // the value should be an array with count of two.
4466
-            if (count($value) !== 2) {
4467
-                throw new EE_Error(
4468
-                    sprintf(
4469
-                        esc_html__(
4470
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4471
-                            'event_espresso'
4472
-                        ),
4473
-                        "BETWEEN"
4474
-                    )
4475
-                );
4476
-            }
4477
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4478
-            return $operator . SP . $cleaned_value;
4479
-        }
4480
-        if (in_array($operator, $this->valid_null_style_operators())) {
4481
-            if ($value !== null) {
4482
-                throw new EE_Error(
4483
-                    sprintf(
4484
-                        esc_html__(
4485
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4486
-                            "event_espresso"
4487
-                        ),
4488
-                        $value,
4489
-                        $operator
4490
-                    )
4491
-                );
4492
-            }
4493
-            return $operator;
4494
-        }
4495
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4496
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4497
-            // remove other junk. So just treat it as a string.
4498
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4499
-        }
4500
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4502
-        }
4503
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4504
-            throw new EE_Error(
4505
-                sprintf(
4506
-                    esc_html__(
4507
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4508
-                        'event_espresso'
4509
-                    ),
4510
-                    $operator,
4511
-                    $operator
4512
-                )
4513
-            );
4514
-        }
4515
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4516
-            throw new EE_Error(
4517
-                sprintf(
4518
-                    esc_html__(
4519
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4520
-                        'event_espresso'
4521
-                    ),
4522
-                    $operator,
4523
-                    $operator
4524
-                )
4525
-            );
4526
-        }
4527
-        throw new EE_Error(
4528
-            sprintf(
4529
-                esc_html__(
4530
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4531
-                    "event_espresso"
4532
-                ),
4533
-                http_build_query($op_and_value)
4534
-            )
4535
-        );
4536
-    }
4537
-
4538
-
4539
-    /**
4540
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4541
-     *
4542
-     * @param array                      $values
4543
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4544
-     *                                              '%s'
4545
-     * @return string
4546
-     * @throws EE_Error
4547
-     */
4548
-    public function _construct_between_value($values, $field_obj)
4549
-    {
4550
-        $cleaned_values = [];
4551
-        foreach ($values as $value) {
4552
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4553
-        }
4554
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4555
-    }
4556
-
4557
-
4558
-    /**
4559
-     * Takes an array or a comma-separated list of $values and cleans them
4560
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4561
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4562
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4563
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4564
-     *
4565
-     * @param mixed                      $values    array or comma-separated string
4566
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4567
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4568
-     * @throws EE_Error
4569
-     */
4570
-    public function _construct_in_value($values, $field_obj)
4571
-    {
4572
-        // check if the value is a CSV list
4573
-        if (is_string($values)) {
4574
-            // in which case, turn it into an array
4575
-            $values = explode(",", $values);
4576
-        }
4577
-        $cleaned_values = [];
4578
-        foreach ($values as $value) {
4579
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4580
-        }
4581
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4582
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4583
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4584
-        if (empty($cleaned_values)) {
4585
-            $all_fields       = $this->field_settings();
4586
-            $a_field          = array_shift($all_fields);
4587
-            $main_table       = $this->_get_main_table();
4588
-            $cleaned_values[] = "SELECT "
4589
-                                . $a_field->get_table_column()
4590
-                                . " FROM "
4591
-                                . $main_table->get_table_name()
4592
-                                . " WHERE FALSE";
4593
-        }
4594
-        return "(" . implode(",", $cleaned_values) . ")";
4595
-    }
4596
-
4597
-
4598
-    /**
4599
-     * @param mixed                      $value
4600
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4601
-     * @return string
4602
-     * @throws EE_Error
4603
-     */
4604
-    private function _wpdb_prepare_using_field($value, $field_obj)
4605
-    {
4606
-        global $wpdb;
4607
-        if ($field_obj instanceof EE_Model_Field_Base) {
4608
-            return $wpdb->prepare(
4609
-                $field_obj->get_wpdb_data_type(),
4610
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4611
-            );
4612
-        } //$field_obj should really just be a data type
4613
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4614
-            throw new EE_Error(
4615
-                sprintf(
4616
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4617
-                    $field_obj,
4618
-                    implode(",", $this->_valid_wpdb_data_types)
4619
-                )
4620
-            );
4621
-        }
4622
-        return $wpdb->prepare($field_obj, $value);
4623
-    }
4624
-
4625
-
4626
-    /**
4627
-     * Takes the input parameter and finds the model field that it indicates.
4628
-     *
4629
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4630
-     * @return EE_Model_Field_Base
4631
-     * @throws EE_Error
4632
-     */
4633
-    protected function _deduce_field_from_query_param($query_param_name)
4634
-    {
4635
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4636
-        // which will help us find the database table and column
4637
-        $query_param_parts = explode(".", $query_param_name);
4638
-        if (empty($query_param_parts)) {
4639
-            throw new EE_Error(
4640
-                sprintf(
4641
-                    esc_html__(
4642
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4643
-                        'event_espresso'
4644
-                    ),
4645
-                    $query_param_name
4646
-                )
4647
-            );
4648
-        }
4649
-        $number_of_parts       = count($query_param_parts);
4650
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4651
-        $field_name = $last_query_param_part;
4652
-        $model_obj  = $number_of_parts === 1
4653
-            ? $this
4654
-            // $number_of_parts >= 2, the last part is the column name, and there are only 2parts. therefore...
4655
-            : $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4656
-        try {
4657
-            return $model_obj->field_settings_for($field_name);
4658
-        } catch (EE_Error $e) {
4659
-            return null;
4660
-        }
4661
-    }
4662
-
4663
-
4664
-    /**
4665
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4666
-     * alias and column which corresponds to it
4667
-     *
4668
-     * @param string $field_name
4669
-     * @return string
4670
-     * @throws EE_Error
4671
-     */
4672
-    public function _get_qualified_column_for_field($field_name)
4673
-    {
4674
-        $all_fields = $this->field_settings();
4675
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4676
-        if ($field) {
4677
-            return $field->get_qualified_column();
4678
-        }
4679
-        throw new EE_Error(
4680
-            sprintf(
4681
-                esc_html__(
4682
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4683
-                    'event_espresso'
4684
-                ),
4685
-                $field_name,
4686
-                get_class($this)
4687
-            )
4688
-        );
4689
-    }
4690
-
4691
-
4692
-    /**
4693
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4694
-     * Example usage:
4695
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4696
-     *      array(),
4697
-     *      ARRAY_A,
4698
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4699
-     *  );
4700
-     * is equivalent to
4701
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4702
-     * and
4703
-     *  EEM_Event::instance()->get_all_wpdb_results(
4704
-     *      array(
4705
-     *          array(
4706
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4707
-     *          ),
4708
-     *          ARRAY_A,
4709
-     *          implode(
4710
-     *              ', ',
4711
-     *              array_merge(
4712
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4713
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4714
-     *              )
4715
-     *          )
4716
-     *      )
4717
-     *  );
4718
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4719
-     *
4720
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4721
-     *                                            and the one whose fields you are selecting for example: when querying
4722
-     *                                            tickets model and selecting fields from the tickets model you would
4723
-     *                                            leave this parameter empty, because no models are needed to join
4724
-     *                                            between the queried model and the selected one. Likewise when
4725
-     *                                            querying the datetime model and selecting fields from the tickets
4726
-     *                                            model, it would also be left empty, because there is a direct
4727
-     *                                            relation from datetimes to tickets, so no model is needed to join
4728
-     *                                            them together. However, when querying from the event model and
4729
-     *                                            selecting fields from the ticket model, you should provide the string
4730
-     *                                            'Datetime', indicating that the event model must first join to the
4731
-     *                                            datetime model in order to find its relation to ticket model.
4732
-     *                                            Also, when querying from the venue model and selecting fields from
4733
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4734
-     *                                            indicating you need to join the venue model to the event model,
4735
-     *                                            to the datetime model, in order to find its relation to the ticket
4736
-     *                                            model. This string is used to deduce the prefix that gets added onto
4737
-     *                                            the models' tables qualified columns
4738
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4739
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4740
-     *                                            qualified column names
4741
-     * @return array|string
4742
-     */
4743
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4744
-    {
4745
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4746
-        $qualified_columns = [];
4747
-        foreach ($this->field_settings() as $field) {
4748
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4749
-        }
4750
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4751
-    }
4752
-
4753
-
4754
-    /**
4755
-     * constructs the select use on special limit joins
4756
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4757
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4758
-     * (as that is typically where the limits would be set).
4759
-     *
4760
-     * @param string       $table_alias The table the select is being built for
4761
-     * @param mixed|string $limit       The limit for this select
4762
-     * @return string                The final select join element for the query.
4763
-     * @throws EE_Error
4764
-     */
4765
-    public function _construct_limit_join_select($table_alias, $limit)
4766
-    {
4767
-        $SQL = '';
4768
-        foreach ($this->_tables as $table_obj) {
4769
-            if ($table_obj instanceof EE_Primary_Table) {
4770
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4771
-                    ? $table_obj->get_select_join_limit($limit)
4772
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4773
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4774
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4775
-                    ? $table_obj->get_select_join_limit_join($limit)
4776
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4777
-            }
4778
-        }
4779
-        return $SQL;
4780
-    }
4781
-
4782
-
4783
-    /**
4784
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4785
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4786
-     *
4787
-     * @return string SQL
4788
-     * @throws EE_Error
4789
-     */
4790
-    public function _construct_internal_join()
4791
-    {
4792
-        $SQL = $this->_get_main_table()->get_table_sql();
4793
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4794
-        return $SQL;
4795
-    }
4796
-
4797
-
4798
-    /**
4799
-     * Constructs the SQL for joining all the tables on this model.
4800
-     * Normally $alias should be the primary table's alias, but in cases where
4801
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4802
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4803
-     * alias, this will construct SQL like:
4804
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4805
-     * With $alias being a secondary table's alias, this will construct SQL like:
4806
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4807
-     *
4808
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4809
-     * @return string
4810
-     * @throws EE_Error
4811
-     */
4812
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4813
-    {
4814
-        $SQL               = '';
4815
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4816
-        foreach ($this->_tables as $table_obj) {
4817
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4818
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4819
-                    // so we're joining to this table, meaning the table is already in
4820
-                    // the FROM statement, BUT the primary table isn't. So we want
4821
-                    // to add the inverse join sql
4822
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4823
-                } else {
4824
-                    // just add a regular JOIN to this table from the primary table
4825
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4826
-                }
4827
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4828
-        }
4829
-        return $SQL;
4830
-    }
4831
-
4832
-
4833
-    /**
4834
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4835
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4836
-     * their data type (eg, '%s', '%d', etc)
4837
-     *
4838
-     * @return array
4839
-     */
4840
-    public function _get_data_types()
4841
-    {
4842
-        $data_types = [];
4843
-        foreach ($this->field_settings() as $field_obj) {
4844
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4845
-            /** @var $field_obj EE_Model_Field_Base */
4846
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4847
-        }
4848
-        return $data_types;
4849
-    }
4850
-
4851
-
4852
-    /**
4853
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4854
-     *
4855
-     * @param string $model_name
4856
-     * @return EEM_Base
4857
-     * @throws EE_Error
4858
-     */
4859
-    public function get_related_model_obj($model_name)
4860
-    {
4861
-        $model_classname = "EEM_" . $model_name;
4862
-        if (! class_exists($model_classname)) {
4863
-            throw new EE_Error(
4864
-                sprintf(
4865
-                    esc_html__(
4866
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4867
-                        'event_espresso'
4868
-                    ),
4869
-                    $model_name,
4870
-                    $model_classname
4871
-                )
4872
-            );
4873
-        }
4874
-        return call_user_func($model_classname . "::instance");
4875
-    }
4876
-
4877
-
4878
-    /**
4879
-     * Returns the array of EE_ModelRelations for this model.
4880
-     *
4881
-     * @return EE_Model_Relation_Base[]
4882
-     */
4883
-    public function relation_settings()
4884
-    {
4885
-        return $this->_model_relations;
4886
-    }
4887
-
4888
-
4889
-    /**
4890
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4891
-     * because without THOSE models, this model probably doesn't have much purpose.
4892
-     * (Eg, without an event, datetimes have little purpose.)
4893
-     *
4894
-     * @return EE_Belongs_To_Relation[]
4895
-     */
4896
-    public function belongs_to_relations()
4897
-    {
4898
-        $belongs_to_relations = [];
4899
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4900
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4901
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4902
-            }
4903
-        }
4904
-        return $belongs_to_relations;
4905
-    }
4906
-
4907
-
4908
-    /**
4909
-     * Returns the specified EE_Model_Relation, or throws an exception
4910
-     *
4911
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4912
-     * @return EE_Model_Relation_Base
4913
-     * @throws EE_Error
4914
-     */
4915
-    public function related_settings_for($relation_name)
4916
-    {
4917
-        $relatedModels = $this->relation_settings();
4918
-        if (! array_key_exists($relation_name, $relatedModels)) {
4919
-            throw new EE_Error(
4920
-                sprintf(
4921
-                    esc_html__(
4922
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4923
-                        'event_espresso'
4924
-                    ),
4925
-                    $relation_name,
4926
-                    $this->_get_class_name(),
4927
-                    implode(', ', array_keys($relatedModels))
4928
-                )
4929
-            );
4930
-        }
4931
-        return $relatedModels[ $relation_name ];
4932
-    }
4933
-
4934
-
4935
-    /**
4936
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4937
-     * fields
4938
-     *
4939
-     * @param string  $fieldName
4940
-     * @param boolean $include_db_only_fields
4941
-     * @return EE_Model_Field_Base
4942
-     * @throws EE_Error
4943
-     */
4944
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4945
-    {
4946
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4947
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4948
-            throw new EE_Error(
4949
-                sprintf(
4950
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4951
-                    $fieldName,
4952
-                    get_class($this)
4953
-                )
4954
-            );
4955
-        }
4956
-        return $fieldSettings[ $fieldName ];
4957
-    }
4958
-
4959
-
4960
-    /**
4961
-     * Checks if this field exists on this model
4962
-     *
4963
-     * @param string $fieldName a key in the model's _field_settings array
4964
-     * @return boolean
4965
-     */
4966
-    public function has_field($fieldName)
4967
-    {
4968
-        $fieldSettings = $this->field_settings(true);
4969
-        if (isset($fieldSettings[ $fieldName ])) {
4970
-            return true;
4971
-        }
4972
-        return false;
4973
-    }
4974
-
4975
-
4976
-    /**
4977
-     * Returns whether or not this model has a relation to the specified model
4978
-     *
4979
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4980
-     * @return boolean
4981
-     */
4982
-    public function has_relation($relation_name)
4983
-    {
4984
-        $relations = $this->relation_settings();
4985
-        if (isset($relations[ $relation_name ])) {
4986
-            return true;
4987
-        }
4988
-        return false;
4989
-    }
4990
-
4991
-
4992
-    /**
4993
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4994
-     * Eg, on EE_Answer that would be ANS_ID field object
4995
-     *
4996
-     * @param $field_obj
4997
-     * @return boolean
4998
-     */
4999
-    public function is_primary_key_field($field_obj)
5000
-    {
5001
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5002
-    }
5003
-
5004
-
5005
-    /**
5006
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5007
-     * Eg, on EE_Answer that would be ANS_ID field object
5008
-     *
5009
-     * @return EE_Model_Field_Base
5010
-     * @throws EE_Error
5011
-     */
5012
-    public function get_primary_key_field()
5013
-    {
5014
-        if ($this->_primary_key_field === null) {
5015
-            foreach ($this->field_settings(true) as $field_obj) {
5016
-                if ($this->is_primary_key_field($field_obj)) {
5017
-                    $this->_primary_key_field = $field_obj;
5018
-                    break;
5019
-                }
5020
-            }
5021
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5022
-                throw new EE_Error(
5023
-                    sprintf(
5024
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5025
-                        get_class($this)
5026
-                    )
5027
-                );
5028
-            }
5029
-        }
5030
-        return $this->_primary_key_field;
5031
-    }
5032
-
5033
-
5034
-    /**
5035
-     * Returns whether or not not there is a primary key on this model.
5036
-     * Internally does some caching.
5037
-     *
5038
-     * @return boolean
5039
-     */
5040
-    public function has_primary_key_field()
5041
-    {
5042
-        if ($this->_has_primary_key_field === null) {
5043
-            try {
5044
-                $this->get_primary_key_field();
5045
-                $this->_has_primary_key_field = true;
5046
-            } catch (EE_Error $e) {
5047
-                $this->_has_primary_key_field = false;
5048
-            }
5049
-        }
5050
-        return $this->_has_primary_key_field;
5051
-    }
5052
-
5053
-
5054
-    /**
5055
-     * Finds the first field of type $field_class_name.
5056
-     *
5057
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5058
-     *                                 EE_Foreign_Key_Field, etc
5059
-     * @return EE_Model_Field_Base or null if none is found
5060
-     */
5061
-    public function get_a_field_of_type($field_class_name)
5062
-    {
5063
-        foreach ($this->field_settings() as $field) {
5064
-            if ($field instanceof $field_class_name) {
5065
-                return $field;
5066
-            }
5067
-        }
5068
-        return null;
5069
-    }
5070
-
5071
-
5072
-    /**
5073
-     * Gets a foreign key field pointing to model.
5074
-     *
5075
-     * @param string $model_name eg Event, Registration, not EEM_Event
5076
-     * @return EE_Foreign_Key_Field_Base
5077
-     * @throws EE_Error
5078
-     */
5079
-    public function get_foreign_key_to($model_name)
5080
-    {
5081
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
-            foreach ($this->field_settings() as $field) {
5083
-                if (
5084
-                    $field instanceof EE_Foreign_Key_Field_Base
5085
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5086
-                ) {
5087
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5088
-                    break;
5089
-                }
5090
-            }
5091
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5092
-                throw new EE_Error(
5093
-                    sprintf(
5094
-                        esc_html__(
5095
-                            "There is no foreign key field pointing to model %s on model %s",
5096
-                            'event_espresso'
5097
-                        ),
5098
-                        $model_name,
5099
-                        get_class($this)
5100
-                    )
5101
-                );
5102
-            }
5103
-        }
5104
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5105
-    }
5106
-
5107
-
5108
-    /**
5109
-     * Gets the table name (including $wpdb->prefix) for the table alias
5110
-     *
5111
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5112
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5113
-     *                            Either one works
5114
-     * @return string
5115
-     */
5116
-    public function get_table_for_alias($table_alias)
5117
-    {
5118
-        $table_alias_sans_model_relation_chain_prefix =
5119
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5120
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5121
-    }
5122
-
5123
-
5124
-    /**
5125
-     * Returns a flat array of all field son this model, instead of organizing them
5126
-     * by table_alias as they are in the constructor.
5127
-     *
5128
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5129
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5130
-     */
5131
-    public function field_settings($include_db_only_fields = false)
5132
-    {
5133
-        if ($include_db_only_fields) {
5134
-            if ($this->_cached_fields === null) {
5135
-                $this->_cached_fields = [];
5136
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5137
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5139
-                    }
5140
-                }
5141
-            }
5142
-            return $this->_cached_fields;
5143
-        }
5144
-        if ($this->_cached_fields_non_db_only === null) {
5145
-            $this->_cached_fields_non_db_only = [];
5146
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5147
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148
-                    /** @var $field_obj EE_Model_Field_Base */
5149
-                    if (! $field_obj->is_db_only_field()) {
5150
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5151
-                    }
5152
-                }
5153
-            }
5154
-        }
5155
-        return $this->_cached_fields_non_db_only;
5156
-    }
5157
-
5158
-
5159
-    /**
5160
-     *        cycle though array of attendees and create objects out of each item
5161
-     *
5162
-     * @access        private
5163
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5164
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5165
-     *                           numerically indexed)
5166
-     * @throws EE_Error
5167
-     * @throws ReflectionException
5168
-     */
5169
-    protected function _create_objects($rows = [])
5170
-    {
5171
-        $array_of_objects = [];
5172
-        if (empty($rows)) {
5173
-            return [];
5174
-        }
5175
-        $count_if_model_has_no_primary_key = 0;
5176
-        $has_primary_key                   = $this->has_primary_key_field();
5177
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5178
-        foreach ((array)$rows as $row) {
5179
-            if (empty($row)) {
5180
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5181
-                return [];
5182
-            }
5183
-            // check if we've already set this object in the results array,
5184
-            // in which case there's no need to process it further (again)
5185
-            if ($has_primary_key) {
5186
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5187
-                    $row,
5188
-                    $primary_key_field->get_qualified_column(),
5189
-                    $primary_key_field->get_table_column()
5190
-                );
5191
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5192
-                    continue;
5193
-                }
5194
-            }
5195
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5196
-            if (! $classInstance) {
5197
-                throw new EE_Error(
5198
-                    sprintf(
5199
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5200
-                        $this->get_this_model_name(),
5201
-                        http_build_query($row)
5202
-                    )
5203
-                );
5204
-            }
5205
-            // set the timezone on the instantiated objects
5206
-            $classInstance->set_timezone($this->get_timezone(), true);
5207
-            // make sure if there is any timezone setting present that we set the timezone for the object
5208
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5209
-            $array_of_objects[ $key ] = $classInstance;
5210
-            // also, for all the relations of type BelongsTo, see if we can cache
5211
-            // those related models
5212
-            // (we could do this for other relations too, but if there are conditions
5213
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5214
-            // so it requires a little more thought than just caching them immediately...)
5215
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5216
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5217
-                    // check if this model's INFO is present. If so, cache it on the model
5218
-                    $other_model           = $relation_obj->get_other_model();
5219
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5220
-                    // if we managed to make a model object from the results, cache it on the main model object
5221
-                    if ($other_model_obj_maybe) {
5222
-                        // set timezone on these other model objects if they are present
5223
-                        $other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5224
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5225
-                    }
5226
-                }
5227
-            }
5228
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5229
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5230
-            // the field in the CustomSelects object
5231
-            if ($this->_custom_selections instanceof CustomSelects) {
5232
-                $classInstance->setCustomSelectsValues(
5233
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5234
-                );
5235
-            }
5236
-        }
5237
-        return $array_of_objects;
5238
-    }
5239
-
5240
-
5241
-    /**
5242
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5243
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5244
-     *
5245
-     * @param array $db_results_row
5246
-     * @return array
5247
-     */
5248
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5249
-    {
5250
-        $results = [];
5251
-        if ($this->_custom_selections instanceof CustomSelects) {
5252
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5253
-                if (isset($db_results_row[ $alias ])) {
5254
-                    $results[ $alias ] = $this->convertValueToDataType(
5255
-                        $db_results_row[ $alias ],
5256
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5257
-                    );
5258
-                }
5259
-            }
5260
-        }
5261
-        return $results;
5262
-    }
5263
-
5264
-
5265
-    /**
5266
-     * This will set the value for the given alias
5267
-     *
5268
-     * @param string $value
5269
-     * @param string $datatype (one of %d, %s, %f)
5270
-     * @return int|string|float (int for %d, string for %s, float for %f)
5271
-     */
5272
-    protected function convertValueToDataType($value, $datatype)
5273
-    {
5274
-        switch ($datatype) {
5275
-            case '%f':
5276
-                return (float)$value;
5277
-            case '%d':
5278
-                return (int)$value;
5279
-            default:
5280
-                return (string)$value;
5281
-        }
5282
-    }
5283
-
5284
-
5285
-    /**
5286
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5287
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5288
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5289
-     * object (as set in the model_field!).
5290
-     *
5291
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5292
-     * @throws EE_Error
5293
-     * @throws ReflectionException
5294
-     */
5295
-    public function create_default_object()
5296
-    {
5297
-        $this_model_fields_and_values = [];
5298
-        // setup the row using default values;
5299
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5300
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5301
-        }
5302
-        $className = $this->_get_class_name();
5303
-        return EE_Registry::instance()->load_class(
5304
-            $className,
5305
-            [$this_model_fields_and_values],
5306
-            false,
5307
-            false
5308
-        );
5309
-    }
5310
-
5311
-
5312
-    /**
5313
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5314
-     *                             or an stdClass where each property is the name of a column,
5315
-     * @return EE_Base_Class
5316
-     * @throws EE_Error
5317
-     * @throws ReflectionException
5318
-     */
5319
-    public function instantiate_class_from_array_or_object($cols_n_values)
5320
-    {
5321
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5322
-            $cols_n_values = get_object_vars($cols_n_values);
5323
-        }
5324
-        $primary_key = null;
5325
-        // make sure the array only has keys that are fields/columns on this model
5326
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5327
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5328
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5329
-        }
5330
-        $className = $this->_get_class_name();
5331
-        // check we actually found results that we can use to build our model object
5332
-        // if not, return null
5333
-        if ($this->has_primary_key_field()) {
5334
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5335
-                return null;
5336
-            }
5337
-        } elseif ($this->unique_indexes()) {
5338
-            $first_column = reset($this_model_fields_n_values);
5339
-            if (empty($first_column)) {
5340
-                return null;
5341
-            }
5342
-        }
5343
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5344
-        if ($primary_key) {
5345
-            $classInstance = $this->get_from_entity_map($primary_key);
5346
-            if (! $classInstance) {
5347
-                $classInstance = EE_Registry::instance()->load_class(
5348
-                    $className,
5349
-                    [$this_model_fields_n_values, $this->get_timezone()],
5350
-                    true,
5351
-                    false
5352
-                );
5353
-                // add this new object to the entity map
5354
-                $classInstance = $this->add_to_entity_map($classInstance);
5355
-            }
5356
-        } else {
5357
-            $classInstance = EE_Registry::instance()->load_class(
5358
-                $className,
5359
-                [$this_model_fields_n_values, $this->get_timezone()],
5360
-                true,
5361
-                false
5362
-            );
5363
-        }
5364
-        return $classInstance;
5365
-    }
5366
-
5367
-
5368
-    /**
5369
-     * Gets the model object from the  entity map if it exists
5370
-     *
5371
-     * @param int|string $id the ID of the model object
5372
-     * @return EE_Base_Class
5373
-     */
5374
-    public function get_from_entity_map($id)
5375
-    {
5376
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5377
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5378
-            : null;
5379
-    }
5380
-
5381
-
5382
-    /**
5383
-     * add_to_entity_map
5384
-     * Adds the object to the model's entity mappings
5385
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5386
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5387
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5388
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5389
-     *        then this method should be called immediately after the update query
5390
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5391
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5392
-     *
5393
-     * @param EE_Base_Class $object
5394
-     * @return EE_Base_Class
5395
-     * @throws EE_Error
5396
-     */
5397
-    public function add_to_entity_map(EE_Base_Class $object)
5398
-    {
5399
-        $className = $this->_get_class_name();
5400
-        if (! $object instanceof $className) {
5401
-            throw new EE_Error(
5402
-                sprintf(
5403
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5404
-                    is_object($object) ? get_class($object) : $object,
5405
-                    $className
5406
-                )
5407
-            );
5408
-        }
5409
-        if (! $object->ID()) {
5410
-            throw new DomainException(
5411
-                sprintf(
5412
-                    esc_html__(
5413
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5414
-                        "event_espresso"
5415
-                    ),
5416
-                    get_class($this)
5417
-                )
5418
-            );
5419
-        }
5420
-        // double check it's not already there
5421
-        $classInstance = $this->get_from_entity_map($object->ID());
5422
-        if ($classInstance) {
5423
-            return $classInstance;
5424
-        }
5425
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5426
-        return $object;
5427
-    }
5428
-
5429
-
5430
-    /**
5431
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5432
-     * if no identifier is provided, then the entire entity map is emptied
5433
-     *
5434
-     * @param int|string $id the ID of the model object
5435
-     * @return boolean
5436
-     */
5437
-    public function clear_entity_map($id = null)
5438
-    {
5439
-        if (empty($id)) {
5440
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5441
-            return true;
5442
-        }
5443
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5444
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5445
-            return true;
5446
-        }
5447
-        return false;
5448
-    }
5449
-
5450
-
5451
-    /**
5452
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5453
-     * Given an array where keys are column (or column alias) names and values,
5454
-     * returns an array of their corresponding field names and database values
5455
-     *
5456
-     * @param array $cols_n_values
5457
-     * @return array
5458
-     * @throws EE_Error
5459
-     * @throws ReflectionException
5460
-     */
5461
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5462
-    {
5463
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5464
-    }
5465
-
5466
-
5467
-    /**
5468
-     * _deduce_fields_n_values_from_cols_n_values
5469
-     * Given an array where keys are column (or column alias) names and values,
5470
-     * returns an array of their corresponding field names and database values
5471
-     *
5472
-     * @param array $cols_n_values
5473
-     * @return array
5474
-     * @throws EE_Error
5475
-     * @throws ReflectionException
5476
-     */
5477
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5478
-    {
5479
-        $this_model_fields_n_values = [];
5480
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5481
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5482
-                $cols_n_values,
5483
-                $table_obj->get_fully_qualified_pk_column(),
5484
-                $table_obj->get_pk_column()
5485
-            );
5486
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5487
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5488
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5489
-                    if (! $field_obj->is_db_only_field()) {
5490
-                        // prepare field as if its coming from db
5491
-                        $prepared_value                            =
5492
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5493
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5494
-                    }
5495
-                }
5496
-            } else {
5497
-                // the table's rows existed. Use their values
5498
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5499
-                    if (! $field_obj->is_db_only_field()) {
5500
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5501
-                            $cols_n_values,
5502
-                            $field_obj->get_qualified_column(),
5503
-                            $field_obj->get_table_column()
5504
-                        );
5505
-                    }
5506
-                }
5507
-            }
5508
-        }
5509
-        return $this_model_fields_n_values;
5510
-    }
5511
-
5512
-
5513
-    /**
5514
-     * @param array  $cols_n_values
5515
-     * @param string $qualified_column
5516
-     * @param string $regular_column
5517
-     * @return null
5518
-     * @throws EE_Error
5519
-     * @throws ReflectionException
5520
-     */
5521
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5522
-    {
5523
-        $value = null;
5524
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5525
-        // does the field on the model relate to this column retrieved from the db?
5526
-        // or is it a db-only field? (not relating to the model)
5527
-        if (isset($cols_n_values[ $qualified_column ])) {
5528
-            $value = $cols_n_values[ $qualified_column ];
5529
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5530
-            $value = $cols_n_values[ $regular_column ];
5531
-        } elseif (! empty($this->foreign_key_aliases)) {
5532
-            // no PK?  ok check if there is a foreign key alias set for this table
5533
-            // then check if that alias exists in the incoming data
5534
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5535
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5536
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5537
-                    $value = $cols_n_values[ $FK_alias ];
5538
-                    [$pk_class] = explode('.', $PK_column);
5539
-                    $pk_model_name = "EEM_{$pk_class}";
5540
-                    /** @var EEM_Base $pk_model */
5541
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5542
-                    if ($pk_model instanceof EEM_Base) {
5543
-                        // make sure object is pulled from db and added to entity map
5544
-                        $pk_model->get_one_by_ID($value);
5545
-                    }
5546
-                    break;
5547
-                }
5548
-            }
5549
-        }
5550
-        return $value;
5551
-    }
5552
-
5553
-
5554
-    /**
5555
-     * refresh_entity_map_from_db
5556
-     * Makes sure the model object in the entity map at $id assumes the values
5557
-     * of the database (opposite of EE_base_Class::save())
5558
-     *
5559
-     * @param int|string $id
5560
-     * @return EE_Base_Class
5561
-     * @throws EE_Error
5562
-     * @throws ReflectionException
5563
-     */
5564
-    public function refresh_entity_map_from_db($id)
5565
-    {
5566
-        $obj_in_map = $this->get_from_entity_map($id);
5567
-        if ($obj_in_map) {
5568
-            $wpdb_results = $this->_get_all_wpdb_results(
5569
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5570
-            );
5571
-            if ($wpdb_results && is_array($wpdb_results)) {
5572
-                $one_row = reset($wpdb_results);
5573
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5574
-                    $obj_in_map->set_from_db($field_name, $db_value);
5575
-                }
5576
-                // clear the cache of related model objects
5577
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5578
-                    $obj_in_map->clear_cache($relation_name, null, true);
5579
-                }
5580
-            }
5581
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5582
-            return $obj_in_map;
5583
-        }
5584
-        return $this->get_one_by_ID($id);
5585
-    }
5586
-
5587
-
5588
-    /**
5589
-     * refresh_entity_map_with
5590
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5591
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5592
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5593
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5594
-     *
5595
-     * @param int|string    $id
5596
-     * @param EE_Base_Class $replacing_model_obj
5597
-     * @return EE_Base_Class
5598
-     * @throws EE_Error
5599
-     * @throws ReflectionException
5600
-     */
5601
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5602
-    {
5603
-        $obj_in_map = $this->get_from_entity_map($id);
5604
-        if ($obj_in_map) {
5605
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5606
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5607
-                    $obj_in_map->set($field_name, $value);
5608
-                }
5609
-                // make the model object in the entity map's cache match the $replacing_model_obj
5610
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5611
-                    $obj_in_map->clear_cache($relation_name, null, true);
5612
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5613
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5614
-                    }
5615
-                }
5616
-            }
5617
-            return $obj_in_map;
5618
-        }
5619
-        $this->add_to_entity_map($replacing_model_obj);
5620
-        return $replacing_model_obj;
5621
-    }
5622
-
5623
-
5624
-    /**
5625
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5626
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5627
-     * require_once($this->_getClassName().".class.php");
5628
-     *
5629
-     * @return string
5630
-     */
5631
-    private function _get_class_name()
5632
-    {
5633
-        return "EE_" . $this->get_this_model_name();
5634
-    }
5635
-
5636
-
5637
-    /**
5638
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5639
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5640
-     * it would be 'Events'.
5641
-     *
5642
-     * @param int $quantity
5643
-     * @return string
5644
-     */
5645
-    public function item_name($quantity = 1)
5646
-    {
5647
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5648
-    }
5649
-
5650
-
5651
-    /**
5652
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5653
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5654
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5655
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5656
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5657
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5658
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5659
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5660
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5661
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5662
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5663
-     *        return $previousReturnValue.$returnString;
5664
-     * }
5665
-     * require('EEM_Answer.model.php');
5666
-     * $answer=EEM_Answer::instance();
5667
-     * echo $answer->my_callback('monkeys',100);
5668
-     * //will output "you called my_callback! and passed args:monkeys,100"
5669
-     *
5670
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5671
-     * @param array  $args       array of original arguments passed to the function
5672
-     * @return mixed whatever the plugin which calls add_filter decides
5673
-     * @throws EE_Error
5674
-     */
5675
-    public function __call($methodName, $args)
5676
-    {
5677
-        $className = get_class($this);
5678
-        $tagName   = "FHEE__{$className}__{$methodName}";
5679
-        if (! has_filter($tagName)) {
5680
-            throw new EE_Error(
5681
-                sprintf(
5682
-                    esc_html__(
5683
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5684
-                        'event_espresso'
5685
-                    ),
5686
-                    $methodName,
5687
-                    $className,
5688
-                    $tagName,
5689
-                    '<br />'
5690
-                )
5691
-            );
5692
-        }
5693
-        return apply_filters($tagName, null, $this, $args);
5694
-    }
5695
-
5696
-
5697
-    /**
5698
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5699
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5700
-     *
5701
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5702
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5703
-     *                                                       the object's class name
5704
-     *                                                       or object's ID
5705
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5706
-     *                                                       exists in the database. If it does not, we add it
5707
-     * @return EE_Base_Class
5708
-     * @throws EE_Error
5709
-     * @throws ReflectionException
5710
-     */
5711
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5712
-    {
5713
-        $className = $this->_get_class_name();
5714
-        if ($base_class_obj_or_id instanceof $className) {
5715
-            $model_object = $base_class_obj_or_id;
5716
-        } else {
5717
-            $primary_key_field = $this->get_primary_key_field();
5718
-            if (
5719
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5720
-                && (
5721
-                    is_int($base_class_obj_or_id)
5722
-                    || is_string($base_class_obj_or_id)
5723
-                )
5724
-            ) {
5725
-                // assume it's an ID.
5726
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5727
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5728
-            } elseif (
5729
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5730
-                && is_string($base_class_obj_or_id)
5731
-            ) {
5732
-                // assume its a string representation of the object
5733
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5734
-            } else {
5735
-                throw new EE_Error(
5736
-                    sprintf(
5737
-                        esc_html__(
5738
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5739
-                            'event_espresso'
5740
-                        ),
5741
-                        $base_class_obj_or_id,
5742
-                        $this->_get_class_name(),
5743
-                        print_r($base_class_obj_or_id, true)
5744
-                    )
5745
-                );
5746
-            }
5747
-        }
5748
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5749
-            $model_object->save();
5750
-        }
5751
-        return $model_object;
5752
-    }
5753
-
5754
-
5755
-    /**
5756
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5757
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5758
-     * returns it ID.
5759
-     *
5760
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5761
-     * @return int|string depending on the type of this model object's ID
5762
-     * @throws EE_Error
5763
-     */
5764
-    public function ensure_is_ID($base_class_obj_or_id)
5765
-    {
5766
-        $className = $this->_get_class_name();
5767
-        if ($base_class_obj_or_id instanceof $className) {
5768
-            $id = $base_class_obj_or_id->ID();
5769
-        } elseif (is_int($base_class_obj_or_id)) {
5770
-            // assume it's an ID
5771
-            $id = $base_class_obj_or_id;
5772
-        } elseif (is_string($base_class_obj_or_id)) {
5773
-            // assume its a string representation of the object
5774
-            $id = $base_class_obj_or_id;
5775
-        } else {
5776
-            throw new EE_Error(
5777
-                sprintf(
5778
-                    esc_html__(
5779
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5780
-                        'event_espresso'
5781
-                    ),
5782
-                    $base_class_obj_or_id,
5783
-                    $this->_get_class_name(),
5784
-                    print_r($base_class_obj_or_id, true)
5785
-                )
5786
-            );
5787
-        }
5788
-        return $id;
5789
-    }
5790
-
5791
-
5792
-    /**
5793
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5794
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5795
-     * been sanitized and converted into the appropriate domain.
5796
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5797
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5798
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5799
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5800
-     * $EVT = EEM_Event::instance(); $old_setting =
5801
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5802
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5803
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5804
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5805
-     *
5806
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5807
-     * @return void
5808
-     */
5809
-    public function assume_values_already_prepared_by_model_object(
5810
-        $values_already_prepared = self::not_prepared_by_model_object
5811
-    ) {
5812
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5813
-    }
5814
-
5815
-
5816
-    /**
5817
-     * Read comments for assume_values_already_prepared_by_model_object()
5818
-     *
5819
-     * @return int
5820
-     */
5821
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5822
-    {
5823
-        return $this->_values_already_prepared_by_model_object;
5824
-    }
5825
-
5826
-
5827
-    /**
5828
-     * Gets all the indexes on this model
5829
-     *
5830
-     * @return EE_Index[]
5831
-     */
5832
-    public function indexes()
5833
-    {
5834
-        return $this->_indexes;
5835
-    }
5836
-
5837
-
5838
-    /**
5839
-     * Gets all the Unique Indexes on this model
5840
-     *
5841
-     * @return EE_Unique_Index[]
5842
-     */
5843
-    public function unique_indexes()
5844
-    {
5845
-        $unique_indexes = [];
5846
-        foreach ($this->_indexes as $name => $index) {
5847
-            if ($index instanceof EE_Unique_Index) {
5848
-                $unique_indexes [ $name ] = $index;
5849
-            }
5850
-        }
5851
-        return $unique_indexes;
5852
-    }
5853
-
5854
-
5855
-    /**
5856
-     * Gets all the fields which, when combined, make the primary key.
5857
-     * This is usually just an array with 1 element (the primary key), but in cases
5858
-     * where there is no primary key, it's a combination of fields as defined
5859
-     * on a primary index
5860
-     *
5861
-     * @return EE_Model_Field_Base[] indexed by the field's name
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function get_combined_primary_key_fields()
5865
-    {
5866
-        foreach ($this->indexes() as $index) {
5867
-            if ($index instanceof EE_Primary_Key_Index) {
5868
-                return $index->fields();
5869
-            }
5870
-        }
5871
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5872
-    }
5873
-
5874
-
5875
-    /**
5876
-     * Used to build a primary key string (when the model has no primary key),
5877
-     * which can be used a unique string to identify this model object.
5878
-     *
5879
-     * @param array $fields_n_values keys are field names, values are their values.
5880
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5881
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5882
-     *                               before passing it to this function (that will convert it from columns-n-values
5883
-     *                               to field-names-n-values).
5884
-     * @return string
5885
-     * @throws EE_Error
5886
-     */
5887
-    public function get_index_primary_key_string($fields_n_values)
5888
-    {
5889
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5890
-            $fields_n_values,
5891
-            $this->get_combined_primary_key_fields()
5892
-        );
5893
-        return http_build_query($cols_n_values_for_primary_key_index);
5894
-    }
5895
-
5896
-
5897
-    /**
5898
-     * Gets the field values from the primary key string
5899
-     *
5900
-     * @param string $index_primary_key_string
5901
-     * @return null|array
5902
-     * @throws EE_Error
5903
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5904
-     */
5905
-    public function parse_index_primary_key_string($index_primary_key_string)
5906
-    {
5907
-        $key_fields = $this->get_combined_primary_key_fields();
5908
-        // check all of them are in the $id
5909
-        $key_values_in_combined_pk = [];
5910
-        parse_str($index_primary_key_string, $key_values_in_combined_pk);
5911
-        foreach ($key_fields as $key_field_name => $field_obj) {
5912
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5913
-                return null;
5914
-            }
5915
-        }
5916
-        return $key_values_in_combined_pk;
5917
-    }
5918
-
5919
-
5920
-    /**
5921
-     * verifies that an array of key-value pairs for model fields has a key
5922
-     * for each field comprising the primary key index
5923
-     *
5924
-     * @param array $key_values
5925
-     * @return boolean
5926
-     * @throws EE_Error
5927
-     */
5928
-    public function has_all_combined_primary_key_fields($key_values)
5929
-    {
5930
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5931
-        foreach ($keys_it_should_have as $key) {
5932
-            if (! isset($key_values[ $key ])) {
5933
-                return false;
5934
-            }
5935
-        }
5936
-        return true;
5937
-    }
5938
-
5939
-
5940
-    /**
5941
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5942
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5943
-     *
5944
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5945
-     * @param array               $query_params                     see github link below for more info
5946
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5947
-     * @throws EE_Error
5948
-     * @throws ReflectionException
5949
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5950
-     *                                                              indexed)
5951
-     */
5952
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5953
-    {
5954
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5955
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5956
-        } elseif (is_array($model_object_or_attributes_array)) {
5957
-            $attributes_array = $model_object_or_attributes_array;
5958
-        } else {
5959
-            throw new EE_Error(
5960
-                sprintf(
5961
-                    esc_html__(
5962
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5963
-                        "event_espresso"
5964
-                    ),
5965
-                    $model_object_or_attributes_array
5966
-                )
5967
-            );
5968
-        }
5969
-        // even copies obviously won't have the same ID, so remove the primary key
5970
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5971
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5972
-            unset($attributes_array[ $this->primary_key_name() ]);
5973
-        }
5974
-        if (isset($query_params[0])) {
5975
-            $query_params[0] = array_merge($attributes_array, $query_params);
5976
-        } else {
5977
-            $query_params[0] = $attributes_array;
5978
-        }
5979
-        return $this->get_all($query_params);
5980
-    }
5981
-
5982
-
5983
-    /**
5984
-     * Gets the first copy we find. See get_all_copies for more details
5985
-     *
5986
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5987
-     * @param array $query_params
5988
-     * @return EE_Base_Class
5989
-     * @throws EE_Error
5990
-     * @throws ReflectionException
5991
-     */
5992
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5993
-    {
5994
-        if (! is_array($query_params)) {
5995
-            EE_Error::doing_it_wrong(
5996
-                'EEM_Base::get_one_copy',
5997
-                sprintf(
5998
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5999
-                    gettype($query_params)
6000
-                ),
6001
-                '4.6.0'
6002
-            );
6003
-            $query_params = [];
6004
-        }
6005
-        $query_params['limit'] = 1;
6006
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6007
-        if (is_array($copies)) {
6008
-            return array_shift($copies);
6009
-        }
6010
-        return null;
6011
-    }
6012
-
6013
-
6014
-    /**
6015
-     * Updates the item with the specified id. Ignores default query parameters because
6016
-     * we have specified the ID, and its assumed we KNOW what we're doing
6017
-     *
6018
-     * @param array      $fields_n_values keys are field names, values are their new values
6019
-     * @param int|string $id              the value of the primary key to update
6020
-     * @return int number of rows updated
6021
-     * @throws EE_Error
6022
-     * @throws ReflectionException
6023
-     */
6024
-    public function update_by_ID($fields_n_values, $id)
6025
-    {
6026
-        $query_params = [
6027
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6028
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6029
-        ];
6030
-        return $this->update($fields_n_values, $query_params);
6031
-    }
6032
-
6033
-
6034
-    /**
6035
-     * Changes an operator which was supplied to the models into one usable in SQL
6036
-     *
6037
-     * @param string $operator_supplied
6038
-     * @return string an operator which can be used in SQL
6039
-     * @throws EE_Error
6040
-     */
6041
-    private function _prepare_operator_for_sql($operator_supplied)
6042
-    {
6043
-        $sql_operator =
6044
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6045
-                : null;
6046
-        if ($sql_operator) {
6047
-            return $sql_operator;
6048
-        }
6049
-        throw new EE_Error(
6050
-            sprintf(
6051
-                esc_html__(
6052
-                    "The operator '%s' is not in the list of valid operators: %s",
6053
-                    "event_espresso"
6054
-                ),
6055
-                $operator_supplied,
6056
-                implode(",", array_keys($this->_valid_operators))
6057
-            )
6058
-        );
6059
-    }
6060
-
6061
-
6062
-    /**
6063
-     * Gets the valid operators
6064
-     *
6065
-     * @return array keys are accepted strings, values are the SQL they are converted to
6066
-     */
6067
-    public function valid_operators()
6068
-    {
6069
-        return $this->_valid_operators;
6070
-    }
6071
-
6072
-
6073
-    /**
6074
-     * Gets the between-style operators (take 2 arguments).
6075
-     *
6076
-     * @return array keys are accepted strings, values are the SQL they are converted to
6077
-     */
6078
-    public function valid_between_style_operators()
6079
-    {
6080
-        return array_intersect(
6081
-            $this->valid_operators(),
6082
-            $this->_between_style_operators
6083
-        );
6084
-    }
6085
-
6086
-
6087
-    /**
6088
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6089
-     *
6090
-     * @return array keys are accepted strings, values are the SQL they are converted to
6091
-     */
6092
-    public function valid_like_style_operators()
6093
-    {
6094
-        return array_intersect(
6095
-            $this->valid_operators(),
6096
-            $this->_like_style_operators
6097
-        );
6098
-    }
6099
-
6100
-
6101
-    /**
6102
-     * Gets the "in"-style operators
6103
-     *
6104
-     * @return array keys are accepted strings, values are the SQL they are converted to
6105
-     */
6106
-    public function valid_in_style_operators()
6107
-    {
6108
-        return array_intersect(
6109
-            $this->valid_operators(),
6110
-            $this->_in_style_operators
6111
-        );
6112
-    }
6113
-
6114
-
6115
-    /**
6116
-     * Gets the "null"-style operators (accept no arguments)
6117
-     *
6118
-     * @return array keys are accepted strings, values are the SQL they are converted to
6119
-     */
6120
-    public function valid_null_style_operators()
6121
-    {
6122
-        return array_intersect(
6123
-            $this->valid_operators(),
6124
-            $this->_null_style_operators
6125
-        );
6126
-    }
6127
-
6128
-
6129
-    /**
6130
-     * Gets an array where keys are the primary keys and values are their 'names'
6131
-     * (as determined by the model object's name() function, which is often overridden)
6132
-     *
6133
-     * @param array $query_params like get_all's
6134
-     * @return string[]
6135
-     * @throws EE_Error
6136
-     * @throws ReflectionException
6137
-     */
6138
-    public function get_all_names($query_params = [])
6139
-    {
6140
-        $objs  = $this->get_all($query_params);
6141
-        $names = [];
6142
-        foreach ($objs as $obj) {
6143
-            $names[ $obj->ID() ] = $obj->name();
6144
-        }
6145
-        return $names;
6146
-    }
6147
-
6148
-
6149
-    /**
6150
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6151
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6152
-     * this is duplicated effort and reduces efficiency) you would be better to use
6153
-     * array_keys() on $model_objects.
6154
-     *
6155
-     * @param EE_Base_Class[] $model_objects
6156
-     * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6157
-     *                                               in the returned array
6158
-     * @return array
6159
-     * @throws EE_Error
6160
-     */
6161
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6162
-    {
6163
-        if (! $this->has_primary_key_field()) {
6164
-            if (WP_DEBUG) {
6165
-                EE_Error::add_error(
6166
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6167
-                    __FILE__,
6168
-                    __FUNCTION__,
6169
-                    __LINE__
6170
-                );
6171
-            }
6172
-        }
6173
-        $IDs = [];
6174
-        foreach ($model_objects as $model_object) {
6175
-            $id = $model_object->ID();
6176
-            if (! $id) {
6177
-                if ($filter_out_empty_ids) {
6178
-                    continue;
6179
-                }
6180
-                if (WP_DEBUG) {
6181
-                    EE_Error::add_error(
6182
-                        esc_html__(
6183
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6184
-                            'event_espresso'
6185
-                        ),
6186
-                        __FILE__,
6187
-                        __FUNCTION__,
6188
-                        __LINE__
6189
-                    );
6190
-                }
6191
-            }
6192
-            $IDs[] = $id;
6193
-        }
6194
-        return $IDs;
6195
-    }
6196
-
6197
-
6198
-    /**
6199
-     * Returns the string used in capabilities relating to this model. If there
6200
-     * are no capabilities that relate to this model returns false
6201
-     *
6202
-     * @return string|false
6203
-     */
6204
-    public function cap_slug()
6205
-    {
6206
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6207
-    }
6208
-
6209
-
6210
-    /**
6211
-     * Returns the capability-restrictions array (@param string $context
6212
-     *
6213
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6214
-     * @throws EE_Error
6215
-     * @see EEM_Base::_cap_restrictions).
6216
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6217
-     *      only returns the cap restrictions array in that context (ie, the array
6218
-     *      at that key)
6219
-     *
6220
-     */
6221
-    public function cap_restrictions($context = EEM_Base::caps_read)
6222
-    {
6223
-        EEM_Base::verify_is_valid_cap_context($context);
6224
-        // check if we ought to run the restriction generator first
6225
-        if (
6226
-            isset($this->_cap_restriction_generators[ $context ])
6227
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6228
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6229
-        ) {
6230
-            $this->_cap_restrictions[ $context ] = array_merge(
6231
-                $this->_cap_restrictions[ $context ],
6232
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6233
-            );
6234
-        }
6235
-        // and make sure we've finalized the construction of each restriction
6236
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6237
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6238
-                $where_conditions_obj->_finalize_construct($this);
6239
-            }
6240
-        }
6241
-        return $this->_cap_restrictions[ $context ];
6242
-    }
6243
-
6244
-
6245
-    /**
6246
-     * Indicating whether or not this model thinks its a wp core model
6247
-     *
6248
-     * @return boolean
6249
-     */
6250
-    public function is_wp_core_model()
6251
-    {
6252
-        return $this->_wp_core_model;
6253
-    }
6254
-
6255
-
6256
-    /**
6257
-     * Gets all the caps that are missing which impose a restriction on
6258
-     * queries made in this context
6259
-     *
6260
-     * @param string $context one of EEM_Base::caps_ constants
6261
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6262
-     * @throws EE_Error
6263
-     */
6264
-    public function caps_missing($context = EEM_Base::caps_read)
6265
-    {
6266
-        $missing_caps     = [];
6267
-        $cap_restrictions = $this->cap_restrictions($context);
6268
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6269
-            if (
6270
-            ! EE_Capabilities::instance()
6271
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6272
-            ) {
6273
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6274
-            }
6275
-        }
6276
-        return $missing_caps;
6277
-    }
6278
-
6279
-
6280
-    /**
6281
-     * Gets the mapping from capability contexts to action strings used in capability names
6282
-     *
6283
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6284
-     * one of 'read', 'edit', or 'delete'
6285
-     */
6286
-    public function cap_contexts_to_cap_action_map()
6287
-    {
6288
-        return apply_filters(
6289
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6290
-            $this->_cap_contexts_to_cap_action_map,
6291
-            $this
6292
-        );
6293
-    }
6294
-
6295
-
6296
-    /**
6297
-     * Gets the action string for the specified capability context
6298
-     *
6299
-     * @param string $context
6300
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6301
-     * @throws EE_Error
6302
-     */
6303
-    public function cap_action_for_context($context)
6304
-    {
6305
-        $mapping = $this->cap_contexts_to_cap_action_map();
6306
-        if (isset($mapping[ $context ])) {
6307
-            return $mapping[ $context ];
6308
-        }
6309
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6310
-            return $action;
6311
-        }
6312
-        throw new EE_Error(
6313
-            sprintf(
6314
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6315
-                $context,
6316
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6317
-            )
6318
-        );
6319
-    }
6320
-
6321
-
6322
-    /**
6323
-     * Returns all the capability contexts which are valid when querying models
6324
-     *
6325
-     * @return array
6326
-     */
6327
-    public static function valid_cap_contexts()
6328
-    {
6329
-        return apply_filters(
6330
-            'FHEE__EEM_Base__valid_cap_contexts',
6331
-            [
6332
-                self::caps_read,
6333
-                self::caps_read_admin,
6334
-                self::caps_edit,
6335
-                self::caps_delete,
6336
-            ]
6337
-        );
6338
-    }
6339
-
6340
-
6341
-    /**
6342
-     * Returns all valid options for 'default_where_conditions'
6343
-     *
6344
-     * @return array
6345
-     */
6346
-    public static function valid_default_where_conditions()
6347
-    {
6348
-        return [
6349
-            EEM_Base::default_where_conditions_all,
6350
-            EEM_Base::default_where_conditions_this_only,
6351
-            EEM_Base::default_where_conditions_others_only,
6352
-            EEM_Base::default_where_conditions_minimum_all,
6353
-            EEM_Base::default_where_conditions_minimum_others,
6354
-            EEM_Base::default_where_conditions_none,
6355
-        ];
6356
-    }
6357
-
6358
-    // public static function default_where_conditions_full
6359
-
6360
-
6361
-    /**
6362
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6363
-     *
6364
-     * @param string $context
6365
-     * @return bool
6366
-     * @throws EE_Error
6367
-     */
6368
-    public static function verify_is_valid_cap_context($context)
6369
-    {
6370
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6371
-        if (in_array($context, $valid_cap_contexts)) {
6372
-            return true;
6373
-        }
6374
-        throw new EE_Error(
6375
-            sprintf(
6376
-                esc_html__(
6377
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6378
-                    'event_espresso'
6379
-                ),
6380
-                $context,
6381
-                'EEM_Base',
6382
-                implode(',', $valid_cap_contexts)
6383
-            )
6384
-        );
6385
-    }
6386
-
6387
-
6388
-    /**
6389
-     * Clears all the models field caches. This is only useful when a sub-class
6390
-     * might have added a field or something and these caches might be invalidated
6391
-     */
6392
-    protected function _invalidate_field_caches()
6393
-    {
6394
-        $this->_cache_foreign_key_to_fields = [];
6395
-        $this->_cached_fields               = null;
6396
-        $this->_cached_fields_non_db_only   = null;
6397
-    }
6398
-
6399
-
6400
-    /**
6401
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6402
-     * (eg "and", "or", "not").
6403
-     *
6404
-     * @return array
6405
-     */
6406
-    public function logic_query_param_keys()
6407
-    {
6408
-        return $this->_logic_query_param_keys;
6409
-    }
6410
-
6411
-
6412
-    /**
6413
-     * Determines whether or not the where query param array key is for a logic query param.
6414
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6415
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6416
-     *
6417
-     * @param $query_param_key
6418
-     * @return bool
6419
-     */
6420
-    public function is_logic_query_param_key($query_param_key)
6421
-    {
6422
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6423
-            if (
6424
-                $query_param_key === $logic_query_param_key
6425
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6426
-            ) {
6427
-                return true;
6428
-            }
6429
-        }
6430
-        return false;
6431
-    }
6432
-
6433
-
6434
-    /**
6435
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6436
-     *
6437
-     * @return boolean
6438
-     * @since 4.9.74.p
6439
-     */
6440
-    public function hasPassword()
6441
-    {
6442
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6443
-        if ($this->has_password_field === null) {
6444
-            $password_field           = $this->getPasswordField();
6445
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6446
-        }
6447
-        return $this->has_password_field;
6448
-    }
6449
-
6450
-
6451
-    /**
6452
-     * Returns the password field on this model, if there is one
6453
-     *
6454
-     * @return EE_Password_Field|null
6455
-     * @since 4.9.74.p
6456
-     */
6457
-    public function getPasswordField()
6458
-    {
6459
-        // if we definitely already know there is a password field or not (because has_password_field is true or false)
6460
-        // there's no need to search for it. If we don't know yet, then find out
6461
-        if ($this->has_password_field === null && $this->password_field === null) {
6462
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6463
-        }
6464
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6465
-        return $this->password_field;
6466
-    }
6467
-
6468
-
6469
-    /**
6470
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6471
-     *
6472
-     * @return EE_Model_Field_Base[]
6473
-     * @throws EE_Error
6474
-     * @since 4.9.74.p
6475
-     */
6476
-    public function getPasswordProtectedFields()
6477
-    {
6478
-        $password_field = $this->getPasswordField();
6479
-        $fields         = [];
6480
-        if ($password_field instanceof EE_Password_Field) {
6481
-            $field_names = $password_field->protectedFields();
6482
-            foreach ($field_names as $field_name) {
6483
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6484
-            }
6485
-        }
6486
-        return $fields;
6487
-    }
6488
-
6489
-
6490
-    /**
6491
-     * Checks if the current user can perform the requested action on this model
6492
-     *
6493
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6494
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6495
-     * @return bool
6496
-     * @throws EE_Error
6497
-     * @throws InvalidArgumentException
6498
-     * @throws InvalidDataTypeException
6499
-     * @throws InvalidInterfaceException
6500
-     * @throws ReflectionException
6501
-     * @throws UnexpectedEntityException
6502
-     * @since 4.9.74.p
6503
-     */
6504
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6505
-    {
6506
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6507
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6508
-        }
6509
-        if (! is_array($model_obj_or_fields_n_values)) {
6510
-            throw new UnexpectedEntityException(
6511
-                $model_obj_or_fields_n_values,
6512
-                'EE_Base_Class',
6513
-                sprintf(
6514
-                    esc_html__(
6515
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6516
-                        'event_espresso'
6517
-                    ),
6518
-                    __FUNCTION__
6519
-                )
6520
-            );
6521
-        }
6522
-        return $this->exists(
6523
-            $this->alter_query_params_to_restrict_by_ID(
6524
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6525
-                [
6526
-                    'default_where_conditions' => 'none',
6527
-                    'caps'                     => $cap_to_check,
6528
-                ]
6529
-            )
6530
-        );
6531
-    }
6532
-
6533
-
6534
-    /**
6535
-     * Returns the query param where conditions key to the password affecting this model.
6536
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6537
-     *
6538
-     * @return null|string
6539
-     * @throws EE_Error
6540
-     * @throws InvalidArgumentException
6541
-     * @throws InvalidDataTypeException
6542
-     * @throws InvalidInterfaceException
6543
-     * @throws ModelConfigurationException
6544
-     * @throws ReflectionException
6545
-     * @since 4.9.74.p
6546
-     */
6547
-    public function modelChainAndPassword()
6548
-    {
6549
-        if ($this->model_chain_to_password === null) {
6550
-            throw new ModelConfigurationException(
6551
-                $this,
6552
-                esc_html_x(
6553
-                // @codingStandardsIgnoreStart
6554
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6555
-                    // @codingStandardsIgnoreEnd
6556
-                    '1: model name',
6557
-                    'event_espresso'
6558
-                )
6559
-            );
6560
-        }
6561
-        if ($this->model_chain_to_password === '') {
6562
-            $model_with_password = $this;
6563
-        } else {
6564
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6565
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6566
-            } else {
6567
-                $last_model_in_chain = $this->model_chain_to_password;
6568
-            }
6569
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6570
-        }
6571
-
6572
-        $password_field = $model_with_password->getPasswordField();
6573
-        if ($password_field instanceof EE_Password_Field) {
6574
-            $password_field_name = $password_field->get_name();
6575
-        } else {
6576
-            throw new ModelConfigurationException(
6577
-                $this,
6578
-                sprintf(
6579
-                    esc_html_x(
6580
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6581
-                        '1: model name, 2: special string',
6582
-                        'event_espresso'
6583
-                    ),
6584
-                    $model_with_password->get_this_model_name(),
6585
-                    $this->model_chain_to_password
6586
-                )
6587
-            );
6588
-        }
6589
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6590
-    }
6591
-
6592
-
6593
-    /**
6594
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6595
-     * or if this model itself has a password affecting access to some of its other fields.
6596
-     *
6597
-     * @return boolean
6598
-     * @since 4.9.74.p
6599
-     */
6600
-    public function restrictedByRelatedModelPassword()
6601
-    {
6602
-        return $this->model_chain_to_password !== null;
6603
-    }
3873
+		}
3874
+		return $null_friendly_where_conditions;
3875
+	}
3876
+
3877
+
3878
+	/**
3879
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3880
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3881
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3882
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3883
+	 *
3884
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3885
+	 * @return array
3886
+	 * @throws EE_Error
3887
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3888
+	 */
3889
+	private function _get_default_where_conditions($model_relation_path = '')
3890
+	{
3891
+		if ($this->_ignore_where_strategy) {
3892
+			return [];
3893
+		}
3894
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3895
+	}
3896
+
3897
+
3898
+	/**
3899
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3900
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3901
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3902
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3903
+	 * Similar to _get_default_where_conditions
3904
+	 *
3905
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3906
+	 * @return array
3907
+	 * @throws EE_Error
3908
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3909
+	 */
3910
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3911
+	{
3912
+		if ($this->_ignore_where_strategy) {
3913
+			return [];
3914
+		}
3915
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3916
+	}
3917
+
3918
+
3919
+	/**
3920
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3921
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3922
+	 *
3923
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3924
+	 * @return string
3925
+	 * @throws EE_Error
3926
+	 */
3927
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3928
+	{
3929
+		$selects = $this->_get_columns_to_select_for_this_model();
3930
+		foreach (
3931
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3932
+		) {
3933
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3934
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3935
+			foreach ($other_model_selects as $value) {
3936
+				$selects[] = $value;
3937
+			}
3938
+		}
3939
+		return implode(", ", $selects);
3940
+	}
3941
+
3942
+
3943
+	/**
3944
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3945
+	 * So that's going to be the columns for all the fields on the model
3946
+	 *
3947
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3948
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3949
+	 */
3950
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3951
+	{
3952
+		$fields                                       = $this->field_settings();
3953
+		$selects                                      = [];
3954
+		$table_alias_with_model_relation_chain_prefix =
3955
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3956
+				$model_relation_chain,
3957
+				$this->get_this_model_name()
3958
+			);
3959
+		foreach ($fields as $field_obj) {
3960
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3961
+						 . $field_obj->get_table_alias()
3962
+						 . "."
3963
+						 . $field_obj->get_table_column()
3964
+						 . " AS '"
3965
+						 . $table_alias_with_model_relation_chain_prefix
3966
+						 . $field_obj->get_table_alias()
3967
+						 . "."
3968
+						 . $field_obj->get_table_column()
3969
+						 . "'";
3970
+		}
3971
+		// make sure we are also getting the PKs of each table
3972
+		$tables = $this->get_tables();
3973
+		if (count($tables) > 1) {
3974
+			foreach ($tables as $table_obj) {
3975
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3976
+									   . $table_obj->get_fully_qualified_pk_column();
3977
+				if (! in_array($qualified_pk_column, $selects)) {
3978
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3979
+				}
3980
+			}
3981
+		}
3982
+		return $selects;
3983
+	}
3984
+
3985
+
3986
+	/**
3987
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3988
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3989
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3990
+	 * SQL for joining, and the data types
3991
+	 *
3992
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3993
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3994
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3995
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3996
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3997
+	 *                                                          or 'Registration's
3998
+	 * @param string|null                 $original_query_param what it originally was (eg
3999
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4000
+	 *                                                          matches $query_param
4001
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4002
+	 * @throws EE_Error
4003
+	 */
4004
+	private function _extract_related_model_info_from_query_param(
4005
+		$query_param,
4006
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4007
+		$query_param_type,
4008
+		$original_query_param = null
4009
+	) {
4010
+		if ($original_query_param === null) {
4011
+			$original_query_param = $query_param;
4012
+		}
4013
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4014
+		// whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4015
+		$allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4016
+		$allow_fields             = in_array(
4017
+			$query_param_type,
4018
+			['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4019
+			true
4020
+		);
4021
+		// check to see if we have a field on this model
4022
+		$this_model_fields = $this->field_settings(true);
4023
+		if (array_key_exists($query_param, $this_model_fields)) {
4024
+			if ($allow_fields) {
4025
+				return;
4026
+			}
4027
+			throw new EE_Error(
4028
+				sprintf(
4029
+					esc_html__(
4030
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4031
+						"event_espresso"
4032
+					),
4033
+					$query_param,
4034
+					get_class($this),
4035
+					$query_param_type,
4036
+					$original_query_param
4037
+				)
4038
+			);
4039
+		}
4040
+		// check if this is a special logic query param
4041
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4042
+			if ($allow_logic_query_params) {
4043
+				return;
4044
+			}
4045
+			throw new EE_Error(
4046
+				sprintf(
4047
+					esc_html__(
4048
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4049
+						'event_espresso'
4050
+					),
4051
+					implode('", "', $this->_logic_query_param_keys),
4052
+					$query_param,
4053
+					get_class($this),
4054
+					'<br />',
4055
+					"\t"
4056
+					. ' $passed_in_query_info = <pre>'
4057
+					. print_r($passed_in_query_info, true)
4058
+					. '</pre>'
4059
+					. "\n\t"
4060
+					. ' $query_param_type = '
4061
+					. $query_param_type
4062
+					. "\n\t"
4063
+					. ' $original_query_param = '
4064
+					. $original_query_param
4065
+				)
4066
+			);
4067
+		}
4068
+		// check if it's a custom selection
4069
+		if (
4070
+			$this->_custom_selections instanceof CustomSelects
4071
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4072
+		) {
4073
+			return;
4074
+		}
4075
+		// check if has a model name at the beginning
4076
+		// and
4077
+		// check if it's a field on a related model
4078
+		if (
4079
+		$this->extractJoinModelFromQueryParams(
4080
+			$passed_in_query_info,
4081
+			$query_param,
4082
+			$original_query_param,
4083
+			$query_param_type
4084
+		)
4085
+		) {
4086
+			return;
4087
+		}
4088
+
4089
+		// ok so $query_param didn't start with a model name
4090
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4091
+		// it's wack, that's what it is
4092
+		throw new EE_Error(
4093
+			sprintf(
4094
+				esc_html__(
4095
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4096
+					"event_espresso"
4097
+				),
4098
+				$query_param,
4099
+				get_class($this),
4100
+				$query_param_type,
4101
+				$original_query_param
4102
+			)
4103
+		);
4104
+	}
4105
+
4106
+
4107
+	/**
4108
+	 * Extracts any possible join model information from the provided possible_join_string.
4109
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4110
+	 * join
4111
+	 * parts that should be added to the query.
4112
+	 *
4113
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4115
+	 * @param null|string                 $original_query_param
4116
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4117
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4118
+	 *                                                           etc.)
4119
+	 * @return bool  returns true if a join was added and false if not.
4120
+	 * @throws EE_Error
4121
+	 */
4122
+	private function extractJoinModelFromQueryParams(
4123
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4124
+		$possible_join_string,
4125
+		$original_query_param,
4126
+		$query_parameter_type
4127
+	) {
4128
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4129
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4130
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4131
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4132
+				if ($possible_join_string === '') {
4133
+					// nothing left to $query_param
4134
+					// we should actually end in a field name, not a model like this!
4135
+					throw new EE_Error(
4136
+						sprintf(
4137
+							esc_html__(
4138
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4139
+								"event_espresso"
4140
+							),
4141
+							$possible_join_string,
4142
+							$query_parameter_type,
4143
+							get_class($this),
4144
+							$valid_related_model_name
4145
+						)
4146
+					);
4147
+				}
4148
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4149
+				$related_model_obj->_extract_related_model_info_from_query_param(
4150
+					$possible_join_string,
4151
+					$query_info_carrier,
4152
+					$query_parameter_type,
4153
+					$original_query_param
4154
+				);
4155
+				return true;
4156
+			}
4157
+			if ($possible_join_string === $valid_related_model_name) {
4158
+				$this->_add_join_to_model(
4159
+					$valid_related_model_name,
4160
+					$query_info_carrier,
4161
+					$original_query_param
4162
+				);
4163
+				return true;
4164
+			}
4165
+		}
4166
+		return false;
4167
+	}
4168
+
4169
+
4170
+	/**
4171
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4172
+	 *
4173
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4174
+	 * @throws EE_Error
4175
+	 */
4176
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4177
+	{
4178
+		if (
4179
+			$this->_custom_selections instanceof CustomSelects
4180
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4181
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4182
+			)
4183
+		) {
4184
+			$original_selects = $this->_custom_selections->originalSelects();
4185
+			foreach ($original_selects as $select_configuration) {
4186
+				$this->extractJoinModelFromQueryParams(
4187
+					$query_info_carrier,
4188
+					$select_configuration[0],
4189
+					$select_configuration[0],
4190
+					'custom_selects'
4191
+				);
4192
+			}
4193
+		}
4194
+	}
4195
+
4196
+
4197
+	/**
4198
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4199
+	 * and store it on $passed_in_query_info
4200
+	 *
4201
+	 * @param string                      $model_name
4202
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4203
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4204
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4205
+	 *                                                          and are adding a join to 'Payment' with the original
4206
+	 *                                                          query param key
4207
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4208
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4209
+	 *                                                          Payment wants to add default query params so that it
4210
+	 *                                                          will know what models to prepend onto its default query
4211
+	 *                                                          params or in case it wants to rename tables (in case
4212
+	 *                                                          there are multiple joins to the same table)
4213
+	 * @return void
4214
+	 * @throws EE_Error
4215
+	 */
4216
+	private function _add_join_to_model(
4217
+		$model_name,
4218
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4219
+		$original_query_param
4220
+	) {
4221
+		$relation_obj         = $this->related_settings_for($model_name);
4222
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4223
+		// check if the relation is HABTM, because then we're essentially doing two joins
4224
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4225
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4226
+			$join_model_obj = $relation_obj->get_join_model();
4227
+			// replace the model specified with the join model for this relation chain, whi
4228
+			$relation_chain_to_join_model =
4229
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4230
+					$model_name,
4231
+					$join_model_obj->get_this_model_name(),
4232
+					$model_relation_chain
4233
+				);
4234
+			$passed_in_query_info->merge(
4235
+				new EE_Model_Query_Info_Carrier(
4236
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4237
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4238
+				)
4239
+			);
4240
+		}
4241
+		// now just join to the other table pointed to by the relation object, and add its data types
4242
+		$passed_in_query_info->merge(
4243
+			new EE_Model_Query_Info_Carrier(
4244
+				[$model_relation_chain => $model_name],
4245
+				$relation_obj->get_join_statement($model_relation_chain)
4246
+			)
4247
+		);
4248
+	}
4249
+
4250
+
4251
+	/**
4252
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4253
+	 *
4254
+	 * @param array $where_params
4255
+	 * @return string of SQL
4256
+	 * @throws EE_Error
4257
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4258
+	 */
4259
+	private function _construct_where_clause($where_params)
4260
+	{
4261
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4262
+		if ($SQL) {
4263
+			return " WHERE " . $SQL;
4264
+		}
4265
+		return '';
4266
+	}
4267
+
4268
+
4269
+	/**
4270
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4271
+	 * and should be passed HAVING parameters, not WHERE parameters
4272
+	 *
4273
+	 * @param array $having_params
4274
+	 * @return string
4275
+	 * @throws EE_Error
4276
+	 */
4277
+	private function _construct_having_clause($having_params)
4278
+	{
4279
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4280
+		if ($SQL) {
4281
+			return " HAVING " . $SQL;
4282
+		}
4283
+		return '';
4284
+	}
4285
+
4286
+
4287
+	/**
4288
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4289
+	 * Event_Meta.meta_value = 'foo'))"
4290
+	 *
4291
+	 * @param array  $where_params
4292
+	 * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4293
+	 * @return string of SQL
4294
+	 * @throws EE_Error
4295
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4296
+	 */
4297
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4298
+	{
4299
+		$where_clauses = [];
4300
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4301
+			$query_param =
4302
+				$this->_remove_stars_and_anything_after_from_condition_query_param_key(
4303
+					$query_param
4304
+				);// str_replace("*",'',$query_param);
4305
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4306
+				switch ($query_param) {
4307
+					case 'not':
4308
+					case 'NOT':
4309
+						$where_clauses[] = "! ("
4310
+										   . $this->_construct_condition_clause_recursive(
4311
+								$op_and_value_or_sub_condition,
4312
+								$glue
4313
+							)
4314
+										   . ")";
4315
+						break;
4316
+					case 'and':
4317
+					case 'AND':
4318
+						$where_clauses[] = " ("
4319
+										   . $this->_construct_condition_clause_recursive(
4320
+								$op_and_value_or_sub_condition,
4321
+								' AND '
4322
+							)
4323
+										   . ")";
4324
+						break;
4325
+					case 'or':
4326
+					case 'OR':
4327
+						$where_clauses[] = " ("
4328
+										   . $this->_construct_condition_clause_recursive(
4329
+								$op_and_value_or_sub_condition,
4330
+								' OR '
4331
+							)
4332
+										   . ")";
4333
+						break;
4334
+				}
4335
+			} else {
4336
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4337
+				// if it's not a normal field, maybe it's a custom selection?
4338
+				if (! $field_obj) {
4339
+					if ($this->_custom_selections instanceof CustomSelects) {
4340
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4341
+					} else {
4342
+						throw new EE_Error(
4343
+							sprintf(
4344
+								esc_html__(
4345
+									"%s is neither a valid model field name, nor a custom selection",
4346
+									"event_espresso"
4347
+								),
4348
+								$query_param
4349
+							)
4350
+						);
4351
+					}
4352
+				}
4353
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4354
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4355
+			}
4356
+		}
4357
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4358
+	}
4359
+
4360
+
4361
+	/**
4362
+	 * Takes the input parameter and extract the table name (alias) and column name
4363
+	 *
4364
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4365
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4366
+	 * @throws EE_Error
4367
+	 */
4368
+	private function _deduce_column_name_from_query_param($query_param)
4369
+	{
4370
+		$field = $this->_deduce_field_from_query_param($query_param);
4371
+		if ($field) {
4372
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4373
+				$field->get_model_name(),
4374
+				$query_param
4375
+			);
4376
+			return $table_alias_prefix . $field->get_qualified_column();
4377
+		}
4378
+		if (
4379
+			$this->_custom_selections instanceof CustomSelects
4380
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4381
+		) {
4382
+			// maybe it's custom selection item?
4383
+			// if so, just use it as the "column name"
4384
+			return $query_param;
4385
+		}
4386
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4387
+			? implode(',', $this->_custom_selections->columnAliases())
4388
+			: '';
4389
+		throw new EE_Error(
4390
+			sprintf(
4391
+				esc_html__(
4392
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4393
+					"event_espresso"
4394
+				),
4395
+				$query_param,
4396
+				$custom_select_aliases
4397
+			)
4398
+		);
4399
+	}
4400
+
4401
+
4402
+	/**
4403
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4404
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4405
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4406
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4407
+	 *
4408
+	 * @param string $condition_query_param_key
4409
+	 * @return string
4410
+	 */
4411
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4412
+	{
4413
+		$pos_of_star = strpos($condition_query_param_key, '*');
4414
+		if ($pos_of_star === false) {
4415
+			return $condition_query_param_key;
4416
+		}
4417
+		return substr($condition_query_param_key, 0, $pos_of_star);
4418
+	}
4419
+
4420
+
4421
+	/**
4422
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4423
+	 *
4424
+	 * @param mixed      array | string    $op_and_value
4425
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4426
+	 * @return string
4427
+	 * @throws EE_Error
4428
+	 */
4429
+	private function _construct_op_and_value($op_and_value, $field_obj)
4430
+	{
4431
+		if (is_array($op_and_value)) {
4432
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4433
+			if (! $operator) {
4434
+				$php_array_like_string = [];
4435
+				foreach ($op_and_value as $key => $value) {
4436
+					$php_array_like_string[] = "$key=>$value";
4437
+				}
4438
+				throw new EE_Error(
4439
+					sprintf(
4440
+						esc_html__(
4441
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4442
+							"event_espresso"
4443
+						),
4444
+						implode(",", $php_array_like_string)
4445
+					)
4446
+				);
4447
+			}
4448
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4449
+		} else {
4450
+			$operator = '=';
4451
+			$value    = $op_and_value;
4452
+		}
4453
+		// check to see if the value is actually another field
4454
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4455
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4456
+		}
4457
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4458
+			// in this case, the value should be an array, or at least a comma-separated list
4459
+			// it will need to handle a little differently
4460
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4461
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4462
+			return $operator . SP . $cleaned_value;
4463
+		}
4464
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4465
+			// the value should be an array with count of two.
4466
+			if (count($value) !== 2) {
4467
+				throw new EE_Error(
4468
+					sprintf(
4469
+						esc_html__(
4470
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4471
+							'event_espresso'
4472
+						),
4473
+						"BETWEEN"
4474
+					)
4475
+				);
4476
+			}
4477
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4478
+			return $operator . SP . $cleaned_value;
4479
+		}
4480
+		if (in_array($operator, $this->valid_null_style_operators())) {
4481
+			if ($value !== null) {
4482
+				throw new EE_Error(
4483
+					sprintf(
4484
+						esc_html__(
4485
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4486
+							"event_espresso"
4487
+						),
4488
+						$value,
4489
+						$operator
4490
+					)
4491
+				);
4492
+			}
4493
+			return $operator;
4494
+		}
4495
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4496
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4497
+			// remove other junk. So just treat it as a string.
4498
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4499
+		}
4500
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4502
+		}
4503
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4504
+			throw new EE_Error(
4505
+				sprintf(
4506
+					esc_html__(
4507
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4508
+						'event_espresso'
4509
+					),
4510
+					$operator,
4511
+					$operator
4512
+				)
4513
+			);
4514
+		}
4515
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4516
+			throw new EE_Error(
4517
+				sprintf(
4518
+					esc_html__(
4519
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4520
+						'event_espresso'
4521
+					),
4522
+					$operator,
4523
+					$operator
4524
+				)
4525
+			);
4526
+		}
4527
+		throw new EE_Error(
4528
+			sprintf(
4529
+				esc_html__(
4530
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4531
+					"event_espresso"
4532
+				),
4533
+				http_build_query($op_and_value)
4534
+			)
4535
+		);
4536
+	}
4537
+
4538
+
4539
+	/**
4540
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4541
+	 *
4542
+	 * @param array                      $values
4543
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4544
+	 *                                              '%s'
4545
+	 * @return string
4546
+	 * @throws EE_Error
4547
+	 */
4548
+	public function _construct_between_value($values, $field_obj)
4549
+	{
4550
+		$cleaned_values = [];
4551
+		foreach ($values as $value) {
4552
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4553
+		}
4554
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4555
+	}
4556
+
4557
+
4558
+	/**
4559
+	 * Takes an array or a comma-separated list of $values and cleans them
4560
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4561
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4562
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4563
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4564
+	 *
4565
+	 * @param mixed                      $values    array or comma-separated string
4566
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4567
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4568
+	 * @throws EE_Error
4569
+	 */
4570
+	public function _construct_in_value($values, $field_obj)
4571
+	{
4572
+		// check if the value is a CSV list
4573
+		if (is_string($values)) {
4574
+			// in which case, turn it into an array
4575
+			$values = explode(",", $values);
4576
+		}
4577
+		$cleaned_values = [];
4578
+		foreach ($values as $value) {
4579
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4580
+		}
4581
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4582
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4583
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4584
+		if (empty($cleaned_values)) {
4585
+			$all_fields       = $this->field_settings();
4586
+			$a_field          = array_shift($all_fields);
4587
+			$main_table       = $this->_get_main_table();
4588
+			$cleaned_values[] = "SELECT "
4589
+								. $a_field->get_table_column()
4590
+								. " FROM "
4591
+								. $main_table->get_table_name()
4592
+								. " WHERE FALSE";
4593
+		}
4594
+		return "(" . implode(",", $cleaned_values) . ")";
4595
+	}
4596
+
4597
+
4598
+	/**
4599
+	 * @param mixed                      $value
4600
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4601
+	 * @return string
4602
+	 * @throws EE_Error
4603
+	 */
4604
+	private function _wpdb_prepare_using_field($value, $field_obj)
4605
+	{
4606
+		global $wpdb;
4607
+		if ($field_obj instanceof EE_Model_Field_Base) {
4608
+			return $wpdb->prepare(
4609
+				$field_obj->get_wpdb_data_type(),
4610
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4611
+			);
4612
+		} //$field_obj should really just be a data type
4613
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4614
+			throw new EE_Error(
4615
+				sprintf(
4616
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4617
+					$field_obj,
4618
+					implode(",", $this->_valid_wpdb_data_types)
4619
+				)
4620
+			);
4621
+		}
4622
+		return $wpdb->prepare($field_obj, $value);
4623
+	}
4624
+
4625
+
4626
+	/**
4627
+	 * Takes the input parameter and finds the model field that it indicates.
4628
+	 *
4629
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4630
+	 * @return EE_Model_Field_Base
4631
+	 * @throws EE_Error
4632
+	 */
4633
+	protected function _deduce_field_from_query_param($query_param_name)
4634
+	{
4635
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4636
+		// which will help us find the database table and column
4637
+		$query_param_parts = explode(".", $query_param_name);
4638
+		if (empty($query_param_parts)) {
4639
+			throw new EE_Error(
4640
+				sprintf(
4641
+					esc_html__(
4642
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4643
+						'event_espresso'
4644
+					),
4645
+					$query_param_name
4646
+				)
4647
+			);
4648
+		}
4649
+		$number_of_parts       = count($query_param_parts);
4650
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4651
+		$field_name = $last_query_param_part;
4652
+		$model_obj  = $number_of_parts === 1
4653
+			? $this
4654
+			// $number_of_parts >= 2, the last part is the column name, and there are only 2parts. therefore...
4655
+			: $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4656
+		try {
4657
+			return $model_obj->field_settings_for($field_name);
4658
+		} catch (EE_Error $e) {
4659
+			return null;
4660
+		}
4661
+	}
4662
+
4663
+
4664
+	/**
4665
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4666
+	 * alias and column which corresponds to it
4667
+	 *
4668
+	 * @param string $field_name
4669
+	 * @return string
4670
+	 * @throws EE_Error
4671
+	 */
4672
+	public function _get_qualified_column_for_field($field_name)
4673
+	{
4674
+		$all_fields = $this->field_settings();
4675
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4676
+		if ($field) {
4677
+			return $field->get_qualified_column();
4678
+		}
4679
+		throw new EE_Error(
4680
+			sprintf(
4681
+				esc_html__(
4682
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4683
+					'event_espresso'
4684
+				),
4685
+				$field_name,
4686
+				get_class($this)
4687
+			)
4688
+		);
4689
+	}
4690
+
4691
+
4692
+	/**
4693
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4694
+	 * Example usage:
4695
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4696
+	 *      array(),
4697
+	 *      ARRAY_A,
4698
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4699
+	 *  );
4700
+	 * is equivalent to
4701
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4702
+	 * and
4703
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4704
+	 *      array(
4705
+	 *          array(
4706
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4707
+	 *          ),
4708
+	 *          ARRAY_A,
4709
+	 *          implode(
4710
+	 *              ', ',
4711
+	 *              array_merge(
4712
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4713
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4714
+	 *              )
4715
+	 *          )
4716
+	 *      )
4717
+	 *  );
4718
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4719
+	 *
4720
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4721
+	 *                                            and the one whose fields you are selecting for example: when querying
4722
+	 *                                            tickets model and selecting fields from the tickets model you would
4723
+	 *                                            leave this parameter empty, because no models are needed to join
4724
+	 *                                            between the queried model and the selected one. Likewise when
4725
+	 *                                            querying the datetime model and selecting fields from the tickets
4726
+	 *                                            model, it would also be left empty, because there is a direct
4727
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4728
+	 *                                            them together. However, when querying from the event model and
4729
+	 *                                            selecting fields from the ticket model, you should provide the string
4730
+	 *                                            'Datetime', indicating that the event model must first join to the
4731
+	 *                                            datetime model in order to find its relation to ticket model.
4732
+	 *                                            Also, when querying from the venue model and selecting fields from
4733
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4734
+	 *                                            indicating you need to join the venue model to the event model,
4735
+	 *                                            to the datetime model, in order to find its relation to the ticket
4736
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4737
+	 *                                            the models' tables qualified columns
4738
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4739
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4740
+	 *                                            qualified column names
4741
+	 * @return array|string
4742
+	 */
4743
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4744
+	{
4745
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4746
+		$qualified_columns = [];
4747
+		foreach ($this->field_settings() as $field) {
4748
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4749
+		}
4750
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4751
+	}
4752
+
4753
+
4754
+	/**
4755
+	 * constructs the select use on special limit joins
4756
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4757
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4758
+	 * (as that is typically where the limits would be set).
4759
+	 *
4760
+	 * @param string       $table_alias The table the select is being built for
4761
+	 * @param mixed|string $limit       The limit for this select
4762
+	 * @return string                The final select join element for the query.
4763
+	 * @throws EE_Error
4764
+	 */
4765
+	public function _construct_limit_join_select($table_alias, $limit)
4766
+	{
4767
+		$SQL = '';
4768
+		foreach ($this->_tables as $table_obj) {
4769
+			if ($table_obj instanceof EE_Primary_Table) {
4770
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4771
+					? $table_obj->get_select_join_limit($limit)
4772
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4773
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4774
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4775
+					? $table_obj->get_select_join_limit_join($limit)
4776
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4777
+			}
4778
+		}
4779
+		return $SQL;
4780
+	}
4781
+
4782
+
4783
+	/**
4784
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4785
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4786
+	 *
4787
+	 * @return string SQL
4788
+	 * @throws EE_Error
4789
+	 */
4790
+	public function _construct_internal_join()
4791
+	{
4792
+		$SQL = $this->_get_main_table()->get_table_sql();
4793
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4794
+		return $SQL;
4795
+	}
4796
+
4797
+
4798
+	/**
4799
+	 * Constructs the SQL for joining all the tables on this model.
4800
+	 * Normally $alias should be the primary table's alias, but in cases where
4801
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4802
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4803
+	 * alias, this will construct SQL like:
4804
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4805
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4806
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4807
+	 *
4808
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4809
+	 * @return string
4810
+	 * @throws EE_Error
4811
+	 */
4812
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4813
+	{
4814
+		$SQL               = '';
4815
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4816
+		foreach ($this->_tables as $table_obj) {
4817
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4818
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4819
+					// so we're joining to this table, meaning the table is already in
4820
+					// the FROM statement, BUT the primary table isn't. So we want
4821
+					// to add the inverse join sql
4822
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4823
+				} else {
4824
+					// just add a regular JOIN to this table from the primary table
4825
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4826
+				}
4827
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4828
+		}
4829
+		return $SQL;
4830
+	}
4831
+
4832
+
4833
+	/**
4834
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4835
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4836
+	 * their data type (eg, '%s', '%d', etc)
4837
+	 *
4838
+	 * @return array
4839
+	 */
4840
+	public function _get_data_types()
4841
+	{
4842
+		$data_types = [];
4843
+		foreach ($this->field_settings() as $field_obj) {
4844
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4845
+			/** @var $field_obj EE_Model_Field_Base */
4846
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4847
+		}
4848
+		return $data_types;
4849
+	}
4850
+
4851
+
4852
+	/**
4853
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4854
+	 *
4855
+	 * @param string $model_name
4856
+	 * @return EEM_Base
4857
+	 * @throws EE_Error
4858
+	 */
4859
+	public function get_related_model_obj($model_name)
4860
+	{
4861
+		$model_classname = "EEM_" . $model_name;
4862
+		if (! class_exists($model_classname)) {
4863
+			throw new EE_Error(
4864
+				sprintf(
4865
+					esc_html__(
4866
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4867
+						'event_espresso'
4868
+					),
4869
+					$model_name,
4870
+					$model_classname
4871
+				)
4872
+			);
4873
+		}
4874
+		return call_user_func($model_classname . "::instance");
4875
+	}
4876
+
4877
+
4878
+	/**
4879
+	 * Returns the array of EE_ModelRelations for this model.
4880
+	 *
4881
+	 * @return EE_Model_Relation_Base[]
4882
+	 */
4883
+	public function relation_settings()
4884
+	{
4885
+		return $this->_model_relations;
4886
+	}
4887
+
4888
+
4889
+	/**
4890
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4891
+	 * because without THOSE models, this model probably doesn't have much purpose.
4892
+	 * (Eg, without an event, datetimes have little purpose.)
4893
+	 *
4894
+	 * @return EE_Belongs_To_Relation[]
4895
+	 */
4896
+	public function belongs_to_relations()
4897
+	{
4898
+		$belongs_to_relations = [];
4899
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4900
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4901
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4902
+			}
4903
+		}
4904
+		return $belongs_to_relations;
4905
+	}
4906
+
4907
+
4908
+	/**
4909
+	 * Returns the specified EE_Model_Relation, or throws an exception
4910
+	 *
4911
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4912
+	 * @return EE_Model_Relation_Base
4913
+	 * @throws EE_Error
4914
+	 */
4915
+	public function related_settings_for($relation_name)
4916
+	{
4917
+		$relatedModels = $this->relation_settings();
4918
+		if (! array_key_exists($relation_name, $relatedModels)) {
4919
+			throw new EE_Error(
4920
+				sprintf(
4921
+					esc_html__(
4922
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4923
+						'event_espresso'
4924
+					),
4925
+					$relation_name,
4926
+					$this->_get_class_name(),
4927
+					implode(', ', array_keys($relatedModels))
4928
+				)
4929
+			);
4930
+		}
4931
+		return $relatedModels[ $relation_name ];
4932
+	}
4933
+
4934
+
4935
+	/**
4936
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4937
+	 * fields
4938
+	 *
4939
+	 * @param string  $fieldName
4940
+	 * @param boolean $include_db_only_fields
4941
+	 * @return EE_Model_Field_Base
4942
+	 * @throws EE_Error
4943
+	 */
4944
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4945
+	{
4946
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4947
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4948
+			throw new EE_Error(
4949
+				sprintf(
4950
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4951
+					$fieldName,
4952
+					get_class($this)
4953
+				)
4954
+			);
4955
+		}
4956
+		return $fieldSettings[ $fieldName ];
4957
+	}
4958
+
4959
+
4960
+	/**
4961
+	 * Checks if this field exists on this model
4962
+	 *
4963
+	 * @param string $fieldName a key in the model's _field_settings array
4964
+	 * @return boolean
4965
+	 */
4966
+	public function has_field($fieldName)
4967
+	{
4968
+		$fieldSettings = $this->field_settings(true);
4969
+		if (isset($fieldSettings[ $fieldName ])) {
4970
+			return true;
4971
+		}
4972
+		return false;
4973
+	}
4974
+
4975
+
4976
+	/**
4977
+	 * Returns whether or not this model has a relation to the specified model
4978
+	 *
4979
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4980
+	 * @return boolean
4981
+	 */
4982
+	public function has_relation($relation_name)
4983
+	{
4984
+		$relations = $this->relation_settings();
4985
+		if (isset($relations[ $relation_name ])) {
4986
+			return true;
4987
+		}
4988
+		return false;
4989
+	}
4990
+
4991
+
4992
+	/**
4993
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4994
+	 * Eg, on EE_Answer that would be ANS_ID field object
4995
+	 *
4996
+	 * @param $field_obj
4997
+	 * @return boolean
4998
+	 */
4999
+	public function is_primary_key_field($field_obj)
5000
+	{
5001
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5002
+	}
5003
+
5004
+
5005
+	/**
5006
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5007
+	 * Eg, on EE_Answer that would be ANS_ID field object
5008
+	 *
5009
+	 * @return EE_Model_Field_Base
5010
+	 * @throws EE_Error
5011
+	 */
5012
+	public function get_primary_key_field()
5013
+	{
5014
+		if ($this->_primary_key_field === null) {
5015
+			foreach ($this->field_settings(true) as $field_obj) {
5016
+				if ($this->is_primary_key_field($field_obj)) {
5017
+					$this->_primary_key_field = $field_obj;
5018
+					break;
5019
+				}
5020
+			}
5021
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5022
+				throw new EE_Error(
5023
+					sprintf(
5024
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5025
+						get_class($this)
5026
+					)
5027
+				);
5028
+			}
5029
+		}
5030
+		return $this->_primary_key_field;
5031
+	}
5032
+
5033
+
5034
+	/**
5035
+	 * Returns whether or not not there is a primary key on this model.
5036
+	 * Internally does some caching.
5037
+	 *
5038
+	 * @return boolean
5039
+	 */
5040
+	public function has_primary_key_field()
5041
+	{
5042
+		if ($this->_has_primary_key_field === null) {
5043
+			try {
5044
+				$this->get_primary_key_field();
5045
+				$this->_has_primary_key_field = true;
5046
+			} catch (EE_Error $e) {
5047
+				$this->_has_primary_key_field = false;
5048
+			}
5049
+		}
5050
+		return $this->_has_primary_key_field;
5051
+	}
5052
+
5053
+
5054
+	/**
5055
+	 * Finds the first field of type $field_class_name.
5056
+	 *
5057
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5058
+	 *                                 EE_Foreign_Key_Field, etc
5059
+	 * @return EE_Model_Field_Base or null if none is found
5060
+	 */
5061
+	public function get_a_field_of_type($field_class_name)
5062
+	{
5063
+		foreach ($this->field_settings() as $field) {
5064
+			if ($field instanceof $field_class_name) {
5065
+				return $field;
5066
+			}
5067
+		}
5068
+		return null;
5069
+	}
5070
+
5071
+
5072
+	/**
5073
+	 * Gets a foreign key field pointing to model.
5074
+	 *
5075
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5076
+	 * @return EE_Foreign_Key_Field_Base
5077
+	 * @throws EE_Error
5078
+	 */
5079
+	public function get_foreign_key_to($model_name)
5080
+	{
5081
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5082
+			foreach ($this->field_settings() as $field) {
5083
+				if (
5084
+					$field instanceof EE_Foreign_Key_Field_Base
5085
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5086
+				) {
5087
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5088
+					break;
5089
+				}
5090
+			}
5091
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5092
+				throw new EE_Error(
5093
+					sprintf(
5094
+						esc_html__(
5095
+							"There is no foreign key field pointing to model %s on model %s",
5096
+							'event_espresso'
5097
+						),
5098
+						$model_name,
5099
+						get_class($this)
5100
+					)
5101
+				);
5102
+			}
5103
+		}
5104
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5105
+	}
5106
+
5107
+
5108
+	/**
5109
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5110
+	 *
5111
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5112
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5113
+	 *                            Either one works
5114
+	 * @return string
5115
+	 */
5116
+	public function get_table_for_alias($table_alias)
5117
+	{
5118
+		$table_alias_sans_model_relation_chain_prefix =
5119
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5120
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5121
+	}
5122
+
5123
+
5124
+	/**
5125
+	 * Returns a flat array of all field son this model, instead of organizing them
5126
+	 * by table_alias as they are in the constructor.
5127
+	 *
5128
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5129
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5130
+	 */
5131
+	public function field_settings($include_db_only_fields = false)
5132
+	{
5133
+		if ($include_db_only_fields) {
5134
+			if ($this->_cached_fields === null) {
5135
+				$this->_cached_fields = [];
5136
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5137
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
+						$this->_cached_fields[ $field_name ] = $field_obj;
5139
+					}
5140
+				}
5141
+			}
5142
+			return $this->_cached_fields;
5143
+		}
5144
+		if ($this->_cached_fields_non_db_only === null) {
5145
+			$this->_cached_fields_non_db_only = [];
5146
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5147
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148
+					/** @var $field_obj EE_Model_Field_Base */
5149
+					if (! $field_obj->is_db_only_field()) {
5150
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5151
+					}
5152
+				}
5153
+			}
5154
+		}
5155
+		return $this->_cached_fields_non_db_only;
5156
+	}
5157
+
5158
+
5159
+	/**
5160
+	 *        cycle though array of attendees and create objects out of each item
5161
+	 *
5162
+	 * @access        private
5163
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5164
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5165
+	 *                           numerically indexed)
5166
+	 * @throws EE_Error
5167
+	 * @throws ReflectionException
5168
+	 */
5169
+	protected function _create_objects($rows = [])
5170
+	{
5171
+		$array_of_objects = [];
5172
+		if (empty($rows)) {
5173
+			return [];
5174
+		}
5175
+		$count_if_model_has_no_primary_key = 0;
5176
+		$has_primary_key                   = $this->has_primary_key_field();
5177
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5178
+		foreach ((array)$rows as $row) {
5179
+			if (empty($row)) {
5180
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5181
+				return [];
5182
+			}
5183
+			// check if we've already set this object in the results array,
5184
+			// in which case there's no need to process it further (again)
5185
+			if ($has_primary_key) {
5186
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5187
+					$row,
5188
+					$primary_key_field->get_qualified_column(),
5189
+					$primary_key_field->get_table_column()
5190
+				);
5191
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5192
+					continue;
5193
+				}
5194
+			}
5195
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5196
+			if (! $classInstance) {
5197
+				throw new EE_Error(
5198
+					sprintf(
5199
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5200
+						$this->get_this_model_name(),
5201
+						http_build_query($row)
5202
+					)
5203
+				);
5204
+			}
5205
+			// set the timezone on the instantiated objects
5206
+			$classInstance->set_timezone($this->get_timezone(), true);
5207
+			// make sure if there is any timezone setting present that we set the timezone for the object
5208
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5209
+			$array_of_objects[ $key ] = $classInstance;
5210
+			// also, for all the relations of type BelongsTo, see if we can cache
5211
+			// those related models
5212
+			// (we could do this for other relations too, but if there are conditions
5213
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5214
+			// so it requires a little more thought than just caching them immediately...)
5215
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5216
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5217
+					// check if this model's INFO is present. If so, cache it on the model
5218
+					$other_model           = $relation_obj->get_other_model();
5219
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5220
+					// if we managed to make a model object from the results, cache it on the main model object
5221
+					if ($other_model_obj_maybe) {
5222
+						// set timezone on these other model objects if they are present
5223
+						$other_model_obj_maybe->set_timezone($this->get_timezone(), true);
5224
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5225
+					}
5226
+				}
5227
+			}
5228
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5229
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5230
+			// the field in the CustomSelects object
5231
+			if ($this->_custom_selections instanceof CustomSelects) {
5232
+				$classInstance->setCustomSelectsValues(
5233
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5234
+				);
5235
+			}
5236
+		}
5237
+		return $array_of_objects;
5238
+	}
5239
+
5240
+
5241
+	/**
5242
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5243
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5244
+	 *
5245
+	 * @param array $db_results_row
5246
+	 * @return array
5247
+	 */
5248
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5249
+	{
5250
+		$results = [];
5251
+		if ($this->_custom_selections instanceof CustomSelects) {
5252
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5253
+				if (isset($db_results_row[ $alias ])) {
5254
+					$results[ $alias ] = $this->convertValueToDataType(
5255
+						$db_results_row[ $alias ],
5256
+						$this->_custom_selections->getDataTypeForAlias($alias)
5257
+					);
5258
+				}
5259
+			}
5260
+		}
5261
+		return $results;
5262
+	}
5263
+
5264
+
5265
+	/**
5266
+	 * This will set the value for the given alias
5267
+	 *
5268
+	 * @param string $value
5269
+	 * @param string $datatype (one of %d, %s, %f)
5270
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5271
+	 */
5272
+	protected function convertValueToDataType($value, $datatype)
5273
+	{
5274
+		switch ($datatype) {
5275
+			case '%f':
5276
+				return (float)$value;
5277
+			case '%d':
5278
+				return (int)$value;
5279
+			default:
5280
+				return (string)$value;
5281
+		}
5282
+	}
5283
+
5284
+
5285
+	/**
5286
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5287
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5288
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5289
+	 * object (as set in the model_field!).
5290
+	 *
5291
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5292
+	 * @throws EE_Error
5293
+	 * @throws ReflectionException
5294
+	 */
5295
+	public function create_default_object()
5296
+	{
5297
+		$this_model_fields_and_values = [];
5298
+		// setup the row using default values;
5299
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5300
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5301
+		}
5302
+		$className = $this->_get_class_name();
5303
+		return EE_Registry::instance()->load_class(
5304
+			$className,
5305
+			[$this_model_fields_and_values],
5306
+			false,
5307
+			false
5308
+		);
5309
+	}
5310
+
5311
+
5312
+	/**
5313
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5314
+	 *                             or an stdClass where each property is the name of a column,
5315
+	 * @return EE_Base_Class
5316
+	 * @throws EE_Error
5317
+	 * @throws ReflectionException
5318
+	 */
5319
+	public function instantiate_class_from_array_or_object($cols_n_values)
5320
+	{
5321
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5322
+			$cols_n_values = get_object_vars($cols_n_values);
5323
+		}
5324
+		$primary_key = null;
5325
+		// make sure the array only has keys that are fields/columns on this model
5326
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5327
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5328
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5329
+		}
5330
+		$className = $this->_get_class_name();
5331
+		// check we actually found results that we can use to build our model object
5332
+		// if not, return null
5333
+		if ($this->has_primary_key_field()) {
5334
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5335
+				return null;
5336
+			}
5337
+		} elseif ($this->unique_indexes()) {
5338
+			$first_column = reset($this_model_fields_n_values);
5339
+			if (empty($first_column)) {
5340
+				return null;
5341
+			}
5342
+		}
5343
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5344
+		if ($primary_key) {
5345
+			$classInstance = $this->get_from_entity_map($primary_key);
5346
+			if (! $classInstance) {
5347
+				$classInstance = EE_Registry::instance()->load_class(
5348
+					$className,
5349
+					[$this_model_fields_n_values, $this->get_timezone()],
5350
+					true,
5351
+					false
5352
+				);
5353
+				// add this new object to the entity map
5354
+				$classInstance = $this->add_to_entity_map($classInstance);
5355
+			}
5356
+		} else {
5357
+			$classInstance = EE_Registry::instance()->load_class(
5358
+				$className,
5359
+				[$this_model_fields_n_values, $this->get_timezone()],
5360
+				true,
5361
+				false
5362
+			);
5363
+		}
5364
+		return $classInstance;
5365
+	}
5366
+
5367
+
5368
+	/**
5369
+	 * Gets the model object from the  entity map if it exists
5370
+	 *
5371
+	 * @param int|string $id the ID of the model object
5372
+	 * @return EE_Base_Class
5373
+	 */
5374
+	public function get_from_entity_map($id)
5375
+	{
5376
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5377
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5378
+			: null;
5379
+	}
5380
+
5381
+
5382
+	/**
5383
+	 * add_to_entity_map
5384
+	 * Adds the object to the model's entity mappings
5385
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5386
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5387
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5388
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5389
+	 *        then this method should be called immediately after the update query
5390
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5391
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5392
+	 *
5393
+	 * @param EE_Base_Class $object
5394
+	 * @return EE_Base_Class
5395
+	 * @throws EE_Error
5396
+	 */
5397
+	public function add_to_entity_map(EE_Base_Class $object)
5398
+	{
5399
+		$className = $this->_get_class_name();
5400
+		if (! $object instanceof $className) {
5401
+			throw new EE_Error(
5402
+				sprintf(
5403
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5404
+					is_object($object) ? get_class($object) : $object,
5405
+					$className
5406
+				)
5407
+			);
5408
+		}
5409
+		if (! $object->ID()) {
5410
+			throw new DomainException(
5411
+				sprintf(
5412
+					esc_html__(
5413
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5414
+						"event_espresso"
5415
+					),
5416
+					get_class($this)
5417
+				)
5418
+			);
5419
+		}
5420
+		// double check it's not already there
5421
+		$classInstance = $this->get_from_entity_map($object->ID());
5422
+		if ($classInstance) {
5423
+			return $classInstance;
5424
+		}
5425
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5426
+		return $object;
5427
+	}
5428
+
5429
+
5430
+	/**
5431
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5432
+	 * if no identifier is provided, then the entire entity map is emptied
5433
+	 *
5434
+	 * @param int|string $id the ID of the model object
5435
+	 * @return boolean
5436
+	 */
5437
+	public function clear_entity_map($id = null)
5438
+	{
5439
+		if (empty($id)) {
5440
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5441
+			return true;
5442
+		}
5443
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5444
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5445
+			return true;
5446
+		}
5447
+		return false;
5448
+	}
5449
+
5450
+
5451
+	/**
5452
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5453
+	 * Given an array where keys are column (or column alias) names and values,
5454
+	 * returns an array of their corresponding field names and database values
5455
+	 *
5456
+	 * @param array $cols_n_values
5457
+	 * @return array
5458
+	 * @throws EE_Error
5459
+	 * @throws ReflectionException
5460
+	 */
5461
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5462
+	{
5463
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5464
+	}
5465
+
5466
+
5467
+	/**
5468
+	 * _deduce_fields_n_values_from_cols_n_values
5469
+	 * Given an array where keys are column (or column alias) names and values,
5470
+	 * returns an array of their corresponding field names and database values
5471
+	 *
5472
+	 * @param array $cols_n_values
5473
+	 * @return array
5474
+	 * @throws EE_Error
5475
+	 * @throws ReflectionException
5476
+	 */
5477
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5478
+	{
5479
+		$this_model_fields_n_values = [];
5480
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5481
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5482
+				$cols_n_values,
5483
+				$table_obj->get_fully_qualified_pk_column(),
5484
+				$table_obj->get_pk_column()
5485
+			);
5486
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5487
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5488
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5489
+					if (! $field_obj->is_db_only_field()) {
5490
+						// prepare field as if its coming from db
5491
+						$prepared_value                            =
5492
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5493
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5494
+					}
5495
+				}
5496
+			} else {
5497
+				// the table's rows existed. Use their values
5498
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5499
+					if (! $field_obj->is_db_only_field()) {
5500
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5501
+							$cols_n_values,
5502
+							$field_obj->get_qualified_column(),
5503
+							$field_obj->get_table_column()
5504
+						);
5505
+					}
5506
+				}
5507
+			}
5508
+		}
5509
+		return $this_model_fields_n_values;
5510
+	}
5511
+
5512
+
5513
+	/**
5514
+	 * @param array  $cols_n_values
5515
+	 * @param string $qualified_column
5516
+	 * @param string $regular_column
5517
+	 * @return null
5518
+	 * @throws EE_Error
5519
+	 * @throws ReflectionException
5520
+	 */
5521
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5522
+	{
5523
+		$value = null;
5524
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5525
+		// does the field on the model relate to this column retrieved from the db?
5526
+		// or is it a db-only field? (not relating to the model)
5527
+		if (isset($cols_n_values[ $qualified_column ])) {
5528
+			$value = $cols_n_values[ $qualified_column ];
5529
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5530
+			$value = $cols_n_values[ $regular_column ];
5531
+		} elseif (! empty($this->foreign_key_aliases)) {
5532
+			// no PK?  ok check if there is a foreign key alias set for this table
5533
+			// then check if that alias exists in the incoming data
5534
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5535
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5536
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5537
+					$value = $cols_n_values[ $FK_alias ];
5538
+					[$pk_class] = explode('.', $PK_column);
5539
+					$pk_model_name = "EEM_{$pk_class}";
5540
+					/** @var EEM_Base $pk_model */
5541
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5542
+					if ($pk_model instanceof EEM_Base) {
5543
+						// make sure object is pulled from db and added to entity map
5544
+						$pk_model->get_one_by_ID($value);
5545
+					}
5546
+					break;
5547
+				}
5548
+			}
5549
+		}
5550
+		return $value;
5551
+	}
5552
+
5553
+
5554
+	/**
5555
+	 * refresh_entity_map_from_db
5556
+	 * Makes sure the model object in the entity map at $id assumes the values
5557
+	 * of the database (opposite of EE_base_Class::save())
5558
+	 *
5559
+	 * @param int|string $id
5560
+	 * @return EE_Base_Class
5561
+	 * @throws EE_Error
5562
+	 * @throws ReflectionException
5563
+	 */
5564
+	public function refresh_entity_map_from_db($id)
5565
+	{
5566
+		$obj_in_map = $this->get_from_entity_map($id);
5567
+		if ($obj_in_map) {
5568
+			$wpdb_results = $this->_get_all_wpdb_results(
5569
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5570
+			);
5571
+			if ($wpdb_results && is_array($wpdb_results)) {
5572
+				$one_row = reset($wpdb_results);
5573
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5574
+					$obj_in_map->set_from_db($field_name, $db_value);
5575
+				}
5576
+				// clear the cache of related model objects
5577
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5578
+					$obj_in_map->clear_cache($relation_name, null, true);
5579
+				}
5580
+			}
5581
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5582
+			return $obj_in_map;
5583
+		}
5584
+		return $this->get_one_by_ID($id);
5585
+	}
5586
+
5587
+
5588
+	/**
5589
+	 * refresh_entity_map_with
5590
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5591
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5592
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5593
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5594
+	 *
5595
+	 * @param int|string    $id
5596
+	 * @param EE_Base_Class $replacing_model_obj
5597
+	 * @return EE_Base_Class
5598
+	 * @throws EE_Error
5599
+	 * @throws ReflectionException
5600
+	 */
5601
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5602
+	{
5603
+		$obj_in_map = $this->get_from_entity_map($id);
5604
+		if ($obj_in_map) {
5605
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5606
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5607
+					$obj_in_map->set($field_name, $value);
5608
+				}
5609
+				// make the model object in the entity map's cache match the $replacing_model_obj
5610
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5611
+					$obj_in_map->clear_cache($relation_name, null, true);
5612
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5613
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5614
+					}
5615
+				}
5616
+			}
5617
+			return $obj_in_map;
5618
+		}
5619
+		$this->add_to_entity_map($replacing_model_obj);
5620
+		return $replacing_model_obj;
5621
+	}
5622
+
5623
+
5624
+	/**
5625
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5626
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5627
+	 * require_once($this->_getClassName().".class.php");
5628
+	 *
5629
+	 * @return string
5630
+	 */
5631
+	private function _get_class_name()
5632
+	{
5633
+		return "EE_" . $this->get_this_model_name();
5634
+	}
5635
+
5636
+
5637
+	/**
5638
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5639
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5640
+	 * it would be 'Events'.
5641
+	 *
5642
+	 * @param int $quantity
5643
+	 * @return string
5644
+	 */
5645
+	public function item_name($quantity = 1)
5646
+	{
5647
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5648
+	}
5649
+
5650
+
5651
+	/**
5652
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5653
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5654
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5655
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5656
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5657
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5658
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5659
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5660
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5661
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5662
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5663
+	 *        return $previousReturnValue.$returnString;
5664
+	 * }
5665
+	 * require('EEM_Answer.model.php');
5666
+	 * $answer=EEM_Answer::instance();
5667
+	 * echo $answer->my_callback('monkeys',100);
5668
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5669
+	 *
5670
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5671
+	 * @param array  $args       array of original arguments passed to the function
5672
+	 * @return mixed whatever the plugin which calls add_filter decides
5673
+	 * @throws EE_Error
5674
+	 */
5675
+	public function __call($methodName, $args)
5676
+	{
5677
+		$className = get_class($this);
5678
+		$tagName   = "FHEE__{$className}__{$methodName}";
5679
+		if (! has_filter($tagName)) {
5680
+			throw new EE_Error(
5681
+				sprintf(
5682
+					esc_html__(
5683
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5684
+						'event_espresso'
5685
+					),
5686
+					$methodName,
5687
+					$className,
5688
+					$tagName,
5689
+					'<br />'
5690
+				)
5691
+			);
5692
+		}
5693
+		return apply_filters($tagName, null, $this, $args);
5694
+	}
5695
+
5696
+
5697
+	/**
5698
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5699
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5700
+	 *
5701
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5702
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5703
+	 *                                                       the object's class name
5704
+	 *                                                       or object's ID
5705
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5706
+	 *                                                       exists in the database. If it does not, we add it
5707
+	 * @return EE_Base_Class
5708
+	 * @throws EE_Error
5709
+	 * @throws ReflectionException
5710
+	 */
5711
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5712
+	{
5713
+		$className = $this->_get_class_name();
5714
+		if ($base_class_obj_or_id instanceof $className) {
5715
+			$model_object = $base_class_obj_or_id;
5716
+		} else {
5717
+			$primary_key_field = $this->get_primary_key_field();
5718
+			if (
5719
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5720
+				&& (
5721
+					is_int($base_class_obj_or_id)
5722
+					|| is_string($base_class_obj_or_id)
5723
+				)
5724
+			) {
5725
+				// assume it's an ID.
5726
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5727
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5728
+			} elseif (
5729
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5730
+				&& is_string($base_class_obj_or_id)
5731
+			) {
5732
+				// assume its a string representation of the object
5733
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5734
+			} else {
5735
+				throw new EE_Error(
5736
+					sprintf(
5737
+						esc_html__(
5738
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5739
+							'event_espresso'
5740
+						),
5741
+						$base_class_obj_or_id,
5742
+						$this->_get_class_name(),
5743
+						print_r($base_class_obj_or_id, true)
5744
+					)
5745
+				);
5746
+			}
5747
+		}
5748
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5749
+			$model_object->save();
5750
+		}
5751
+		return $model_object;
5752
+	}
5753
+
5754
+
5755
+	/**
5756
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5757
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5758
+	 * returns it ID.
5759
+	 *
5760
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5761
+	 * @return int|string depending on the type of this model object's ID
5762
+	 * @throws EE_Error
5763
+	 */
5764
+	public function ensure_is_ID($base_class_obj_or_id)
5765
+	{
5766
+		$className = $this->_get_class_name();
5767
+		if ($base_class_obj_or_id instanceof $className) {
5768
+			$id = $base_class_obj_or_id->ID();
5769
+		} elseif (is_int($base_class_obj_or_id)) {
5770
+			// assume it's an ID
5771
+			$id = $base_class_obj_or_id;
5772
+		} elseif (is_string($base_class_obj_or_id)) {
5773
+			// assume its a string representation of the object
5774
+			$id = $base_class_obj_or_id;
5775
+		} else {
5776
+			throw new EE_Error(
5777
+				sprintf(
5778
+					esc_html__(
5779
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5780
+						'event_espresso'
5781
+					),
5782
+					$base_class_obj_or_id,
5783
+					$this->_get_class_name(),
5784
+					print_r($base_class_obj_or_id, true)
5785
+				)
5786
+			);
5787
+		}
5788
+		return $id;
5789
+	}
5790
+
5791
+
5792
+	/**
5793
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5794
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5795
+	 * been sanitized and converted into the appropriate domain.
5796
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5797
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5798
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5799
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5800
+	 * $EVT = EEM_Event::instance(); $old_setting =
5801
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5802
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5803
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5804
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5805
+	 *
5806
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5807
+	 * @return void
5808
+	 */
5809
+	public function assume_values_already_prepared_by_model_object(
5810
+		$values_already_prepared = self::not_prepared_by_model_object
5811
+	) {
5812
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5813
+	}
5814
+
5815
+
5816
+	/**
5817
+	 * Read comments for assume_values_already_prepared_by_model_object()
5818
+	 *
5819
+	 * @return int
5820
+	 */
5821
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5822
+	{
5823
+		return $this->_values_already_prepared_by_model_object;
5824
+	}
5825
+
5826
+
5827
+	/**
5828
+	 * Gets all the indexes on this model
5829
+	 *
5830
+	 * @return EE_Index[]
5831
+	 */
5832
+	public function indexes()
5833
+	{
5834
+		return $this->_indexes;
5835
+	}
5836
+
5837
+
5838
+	/**
5839
+	 * Gets all the Unique Indexes on this model
5840
+	 *
5841
+	 * @return EE_Unique_Index[]
5842
+	 */
5843
+	public function unique_indexes()
5844
+	{
5845
+		$unique_indexes = [];
5846
+		foreach ($this->_indexes as $name => $index) {
5847
+			if ($index instanceof EE_Unique_Index) {
5848
+				$unique_indexes [ $name ] = $index;
5849
+			}
5850
+		}
5851
+		return $unique_indexes;
5852
+	}
5853
+
5854
+
5855
+	/**
5856
+	 * Gets all the fields which, when combined, make the primary key.
5857
+	 * This is usually just an array with 1 element (the primary key), but in cases
5858
+	 * where there is no primary key, it's a combination of fields as defined
5859
+	 * on a primary index
5860
+	 *
5861
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function get_combined_primary_key_fields()
5865
+	{
5866
+		foreach ($this->indexes() as $index) {
5867
+			if ($index instanceof EE_Primary_Key_Index) {
5868
+				return $index->fields();
5869
+			}
5870
+		}
5871
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5872
+	}
5873
+
5874
+
5875
+	/**
5876
+	 * Used to build a primary key string (when the model has no primary key),
5877
+	 * which can be used a unique string to identify this model object.
5878
+	 *
5879
+	 * @param array $fields_n_values keys are field names, values are their values.
5880
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5881
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5882
+	 *                               before passing it to this function (that will convert it from columns-n-values
5883
+	 *                               to field-names-n-values).
5884
+	 * @return string
5885
+	 * @throws EE_Error
5886
+	 */
5887
+	public function get_index_primary_key_string($fields_n_values)
5888
+	{
5889
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5890
+			$fields_n_values,
5891
+			$this->get_combined_primary_key_fields()
5892
+		);
5893
+		return http_build_query($cols_n_values_for_primary_key_index);
5894
+	}
5895
+
5896
+
5897
+	/**
5898
+	 * Gets the field values from the primary key string
5899
+	 *
5900
+	 * @param string $index_primary_key_string
5901
+	 * @return null|array
5902
+	 * @throws EE_Error
5903
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5904
+	 */
5905
+	public function parse_index_primary_key_string($index_primary_key_string)
5906
+	{
5907
+		$key_fields = $this->get_combined_primary_key_fields();
5908
+		// check all of them are in the $id
5909
+		$key_values_in_combined_pk = [];
5910
+		parse_str($index_primary_key_string, $key_values_in_combined_pk);
5911
+		foreach ($key_fields as $key_field_name => $field_obj) {
5912
+			if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5913
+				return null;
5914
+			}
5915
+		}
5916
+		return $key_values_in_combined_pk;
5917
+	}
5918
+
5919
+
5920
+	/**
5921
+	 * verifies that an array of key-value pairs for model fields has a key
5922
+	 * for each field comprising the primary key index
5923
+	 *
5924
+	 * @param array $key_values
5925
+	 * @return boolean
5926
+	 * @throws EE_Error
5927
+	 */
5928
+	public function has_all_combined_primary_key_fields($key_values)
5929
+	{
5930
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5931
+		foreach ($keys_it_should_have as $key) {
5932
+			if (! isset($key_values[ $key ])) {
5933
+				return false;
5934
+			}
5935
+		}
5936
+		return true;
5937
+	}
5938
+
5939
+
5940
+	/**
5941
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5942
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5943
+	 *
5944
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5945
+	 * @param array               $query_params                     see github link below for more info
5946
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5947
+	 * @throws EE_Error
5948
+	 * @throws ReflectionException
5949
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5950
+	 *                                                              indexed)
5951
+	 */
5952
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5953
+	{
5954
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5955
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5956
+		} elseif (is_array($model_object_or_attributes_array)) {
5957
+			$attributes_array = $model_object_or_attributes_array;
5958
+		} else {
5959
+			throw new EE_Error(
5960
+				sprintf(
5961
+					esc_html__(
5962
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5963
+						"event_espresso"
5964
+					),
5965
+					$model_object_or_attributes_array
5966
+				)
5967
+			);
5968
+		}
5969
+		// even copies obviously won't have the same ID, so remove the primary key
5970
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5971
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5972
+			unset($attributes_array[ $this->primary_key_name() ]);
5973
+		}
5974
+		if (isset($query_params[0])) {
5975
+			$query_params[0] = array_merge($attributes_array, $query_params);
5976
+		} else {
5977
+			$query_params[0] = $attributes_array;
5978
+		}
5979
+		return $this->get_all($query_params);
5980
+	}
5981
+
5982
+
5983
+	/**
5984
+	 * Gets the first copy we find. See get_all_copies for more details
5985
+	 *
5986
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5987
+	 * @param array $query_params
5988
+	 * @return EE_Base_Class
5989
+	 * @throws EE_Error
5990
+	 * @throws ReflectionException
5991
+	 */
5992
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5993
+	{
5994
+		if (! is_array($query_params)) {
5995
+			EE_Error::doing_it_wrong(
5996
+				'EEM_Base::get_one_copy',
5997
+				sprintf(
5998
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5999
+					gettype($query_params)
6000
+				),
6001
+				'4.6.0'
6002
+			);
6003
+			$query_params = [];
6004
+		}
6005
+		$query_params['limit'] = 1;
6006
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6007
+		if (is_array($copies)) {
6008
+			return array_shift($copies);
6009
+		}
6010
+		return null;
6011
+	}
6012
+
6013
+
6014
+	/**
6015
+	 * Updates the item with the specified id. Ignores default query parameters because
6016
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6017
+	 *
6018
+	 * @param array      $fields_n_values keys are field names, values are their new values
6019
+	 * @param int|string $id              the value of the primary key to update
6020
+	 * @return int number of rows updated
6021
+	 * @throws EE_Error
6022
+	 * @throws ReflectionException
6023
+	 */
6024
+	public function update_by_ID($fields_n_values, $id)
6025
+	{
6026
+		$query_params = [
6027
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6028
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6029
+		];
6030
+		return $this->update($fields_n_values, $query_params);
6031
+	}
6032
+
6033
+
6034
+	/**
6035
+	 * Changes an operator which was supplied to the models into one usable in SQL
6036
+	 *
6037
+	 * @param string $operator_supplied
6038
+	 * @return string an operator which can be used in SQL
6039
+	 * @throws EE_Error
6040
+	 */
6041
+	private function _prepare_operator_for_sql($operator_supplied)
6042
+	{
6043
+		$sql_operator =
6044
+			isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6045
+				: null;
6046
+		if ($sql_operator) {
6047
+			return $sql_operator;
6048
+		}
6049
+		throw new EE_Error(
6050
+			sprintf(
6051
+				esc_html__(
6052
+					"The operator '%s' is not in the list of valid operators: %s",
6053
+					"event_espresso"
6054
+				),
6055
+				$operator_supplied,
6056
+				implode(",", array_keys($this->_valid_operators))
6057
+			)
6058
+		);
6059
+	}
6060
+
6061
+
6062
+	/**
6063
+	 * Gets the valid operators
6064
+	 *
6065
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6066
+	 */
6067
+	public function valid_operators()
6068
+	{
6069
+		return $this->_valid_operators;
6070
+	}
6071
+
6072
+
6073
+	/**
6074
+	 * Gets the between-style operators (take 2 arguments).
6075
+	 *
6076
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6077
+	 */
6078
+	public function valid_between_style_operators()
6079
+	{
6080
+		return array_intersect(
6081
+			$this->valid_operators(),
6082
+			$this->_between_style_operators
6083
+		);
6084
+	}
6085
+
6086
+
6087
+	/**
6088
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6089
+	 *
6090
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6091
+	 */
6092
+	public function valid_like_style_operators()
6093
+	{
6094
+		return array_intersect(
6095
+			$this->valid_operators(),
6096
+			$this->_like_style_operators
6097
+		);
6098
+	}
6099
+
6100
+
6101
+	/**
6102
+	 * Gets the "in"-style operators
6103
+	 *
6104
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6105
+	 */
6106
+	public function valid_in_style_operators()
6107
+	{
6108
+		return array_intersect(
6109
+			$this->valid_operators(),
6110
+			$this->_in_style_operators
6111
+		);
6112
+	}
6113
+
6114
+
6115
+	/**
6116
+	 * Gets the "null"-style operators (accept no arguments)
6117
+	 *
6118
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6119
+	 */
6120
+	public function valid_null_style_operators()
6121
+	{
6122
+		return array_intersect(
6123
+			$this->valid_operators(),
6124
+			$this->_null_style_operators
6125
+		);
6126
+	}
6127
+
6128
+
6129
+	/**
6130
+	 * Gets an array where keys are the primary keys and values are their 'names'
6131
+	 * (as determined by the model object's name() function, which is often overridden)
6132
+	 *
6133
+	 * @param array $query_params like get_all's
6134
+	 * @return string[]
6135
+	 * @throws EE_Error
6136
+	 * @throws ReflectionException
6137
+	 */
6138
+	public function get_all_names($query_params = [])
6139
+	{
6140
+		$objs  = $this->get_all($query_params);
6141
+		$names = [];
6142
+		foreach ($objs as $obj) {
6143
+			$names[ $obj->ID() ] = $obj->name();
6144
+		}
6145
+		return $names;
6146
+	}
6147
+
6148
+
6149
+	/**
6150
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6151
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6152
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6153
+	 * array_keys() on $model_objects.
6154
+	 *
6155
+	 * @param EE_Base_Class[] $model_objects
6156
+	 * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6157
+	 *                                               in the returned array
6158
+	 * @return array
6159
+	 * @throws EE_Error
6160
+	 */
6161
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6162
+	{
6163
+		if (! $this->has_primary_key_field()) {
6164
+			if (WP_DEBUG) {
6165
+				EE_Error::add_error(
6166
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6167
+					__FILE__,
6168
+					__FUNCTION__,
6169
+					__LINE__
6170
+				);
6171
+			}
6172
+		}
6173
+		$IDs = [];
6174
+		foreach ($model_objects as $model_object) {
6175
+			$id = $model_object->ID();
6176
+			if (! $id) {
6177
+				if ($filter_out_empty_ids) {
6178
+					continue;
6179
+				}
6180
+				if (WP_DEBUG) {
6181
+					EE_Error::add_error(
6182
+						esc_html__(
6183
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6184
+							'event_espresso'
6185
+						),
6186
+						__FILE__,
6187
+						__FUNCTION__,
6188
+						__LINE__
6189
+					);
6190
+				}
6191
+			}
6192
+			$IDs[] = $id;
6193
+		}
6194
+		return $IDs;
6195
+	}
6196
+
6197
+
6198
+	/**
6199
+	 * Returns the string used in capabilities relating to this model. If there
6200
+	 * are no capabilities that relate to this model returns false
6201
+	 *
6202
+	 * @return string|false
6203
+	 */
6204
+	public function cap_slug()
6205
+	{
6206
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6207
+	}
6208
+
6209
+
6210
+	/**
6211
+	 * Returns the capability-restrictions array (@param string $context
6212
+	 *
6213
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6214
+	 * @throws EE_Error
6215
+	 * @see EEM_Base::_cap_restrictions).
6216
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6217
+	 *      only returns the cap restrictions array in that context (ie, the array
6218
+	 *      at that key)
6219
+	 *
6220
+	 */
6221
+	public function cap_restrictions($context = EEM_Base::caps_read)
6222
+	{
6223
+		EEM_Base::verify_is_valid_cap_context($context);
6224
+		// check if we ought to run the restriction generator first
6225
+		if (
6226
+			isset($this->_cap_restriction_generators[ $context ])
6227
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6228
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6229
+		) {
6230
+			$this->_cap_restrictions[ $context ] = array_merge(
6231
+				$this->_cap_restrictions[ $context ],
6232
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6233
+			);
6234
+		}
6235
+		// and make sure we've finalized the construction of each restriction
6236
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6237
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6238
+				$where_conditions_obj->_finalize_construct($this);
6239
+			}
6240
+		}
6241
+		return $this->_cap_restrictions[ $context ];
6242
+	}
6243
+
6244
+
6245
+	/**
6246
+	 * Indicating whether or not this model thinks its a wp core model
6247
+	 *
6248
+	 * @return boolean
6249
+	 */
6250
+	public function is_wp_core_model()
6251
+	{
6252
+		return $this->_wp_core_model;
6253
+	}
6254
+
6255
+
6256
+	/**
6257
+	 * Gets all the caps that are missing which impose a restriction on
6258
+	 * queries made in this context
6259
+	 *
6260
+	 * @param string $context one of EEM_Base::caps_ constants
6261
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6262
+	 * @throws EE_Error
6263
+	 */
6264
+	public function caps_missing($context = EEM_Base::caps_read)
6265
+	{
6266
+		$missing_caps     = [];
6267
+		$cap_restrictions = $this->cap_restrictions($context);
6268
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6269
+			if (
6270
+			! EE_Capabilities::instance()
6271
+							 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6272
+			) {
6273
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6274
+			}
6275
+		}
6276
+		return $missing_caps;
6277
+	}
6278
+
6279
+
6280
+	/**
6281
+	 * Gets the mapping from capability contexts to action strings used in capability names
6282
+	 *
6283
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6284
+	 * one of 'read', 'edit', or 'delete'
6285
+	 */
6286
+	public function cap_contexts_to_cap_action_map()
6287
+	{
6288
+		return apply_filters(
6289
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6290
+			$this->_cap_contexts_to_cap_action_map,
6291
+			$this
6292
+		);
6293
+	}
6294
+
6295
+
6296
+	/**
6297
+	 * Gets the action string for the specified capability context
6298
+	 *
6299
+	 * @param string $context
6300
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6301
+	 * @throws EE_Error
6302
+	 */
6303
+	public function cap_action_for_context($context)
6304
+	{
6305
+		$mapping = $this->cap_contexts_to_cap_action_map();
6306
+		if (isset($mapping[ $context ])) {
6307
+			return $mapping[ $context ];
6308
+		}
6309
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6310
+			return $action;
6311
+		}
6312
+		throw new EE_Error(
6313
+			sprintf(
6314
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6315
+				$context,
6316
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6317
+			)
6318
+		);
6319
+	}
6320
+
6321
+
6322
+	/**
6323
+	 * Returns all the capability contexts which are valid when querying models
6324
+	 *
6325
+	 * @return array
6326
+	 */
6327
+	public static function valid_cap_contexts()
6328
+	{
6329
+		return apply_filters(
6330
+			'FHEE__EEM_Base__valid_cap_contexts',
6331
+			[
6332
+				self::caps_read,
6333
+				self::caps_read_admin,
6334
+				self::caps_edit,
6335
+				self::caps_delete,
6336
+			]
6337
+		);
6338
+	}
6339
+
6340
+
6341
+	/**
6342
+	 * Returns all valid options for 'default_where_conditions'
6343
+	 *
6344
+	 * @return array
6345
+	 */
6346
+	public static function valid_default_where_conditions()
6347
+	{
6348
+		return [
6349
+			EEM_Base::default_where_conditions_all,
6350
+			EEM_Base::default_where_conditions_this_only,
6351
+			EEM_Base::default_where_conditions_others_only,
6352
+			EEM_Base::default_where_conditions_minimum_all,
6353
+			EEM_Base::default_where_conditions_minimum_others,
6354
+			EEM_Base::default_where_conditions_none,
6355
+		];
6356
+	}
6357
+
6358
+	// public static function default_where_conditions_full
6359
+
6360
+
6361
+	/**
6362
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6363
+	 *
6364
+	 * @param string $context
6365
+	 * @return bool
6366
+	 * @throws EE_Error
6367
+	 */
6368
+	public static function verify_is_valid_cap_context($context)
6369
+	{
6370
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6371
+		if (in_array($context, $valid_cap_contexts)) {
6372
+			return true;
6373
+		}
6374
+		throw new EE_Error(
6375
+			sprintf(
6376
+				esc_html__(
6377
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6378
+					'event_espresso'
6379
+				),
6380
+				$context,
6381
+				'EEM_Base',
6382
+				implode(',', $valid_cap_contexts)
6383
+			)
6384
+		);
6385
+	}
6386
+
6387
+
6388
+	/**
6389
+	 * Clears all the models field caches. This is only useful when a sub-class
6390
+	 * might have added a field or something and these caches might be invalidated
6391
+	 */
6392
+	protected function _invalidate_field_caches()
6393
+	{
6394
+		$this->_cache_foreign_key_to_fields = [];
6395
+		$this->_cached_fields               = null;
6396
+		$this->_cached_fields_non_db_only   = null;
6397
+	}
6398
+
6399
+
6400
+	/**
6401
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6402
+	 * (eg "and", "or", "not").
6403
+	 *
6404
+	 * @return array
6405
+	 */
6406
+	public function logic_query_param_keys()
6407
+	{
6408
+		return $this->_logic_query_param_keys;
6409
+	}
6410
+
6411
+
6412
+	/**
6413
+	 * Determines whether or not the where query param array key is for a logic query param.
6414
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6415
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6416
+	 *
6417
+	 * @param $query_param_key
6418
+	 * @return bool
6419
+	 */
6420
+	public function is_logic_query_param_key($query_param_key)
6421
+	{
6422
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6423
+			if (
6424
+				$query_param_key === $logic_query_param_key
6425
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6426
+			) {
6427
+				return true;
6428
+			}
6429
+		}
6430
+		return false;
6431
+	}
6432
+
6433
+
6434
+	/**
6435
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6436
+	 *
6437
+	 * @return boolean
6438
+	 * @since 4.9.74.p
6439
+	 */
6440
+	public function hasPassword()
6441
+	{
6442
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6443
+		if ($this->has_password_field === null) {
6444
+			$password_field           = $this->getPasswordField();
6445
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6446
+		}
6447
+		return $this->has_password_field;
6448
+	}
6449
+
6450
+
6451
+	/**
6452
+	 * Returns the password field on this model, if there is one
6453
+	 *
6454
+	 * @return EE_Password_Field|null
6455
+	 * @since 4.9.74.p
6456
+	 */
6457
+	public function getPasswordField()
6458
+	{
6459
+		// if we definitely already know there is a password field or not (because has_password_field is true or false)
6460
+		// there's no need to search for it. If we don't know yet, then find out
6461
+		if ($this->has_password_field === null && $this->password_field === null) {
6462
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6463
+		}
6464
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6465
+		return $this->password_field;
6466
+	}
6467
+
6468
+
6469
+	/**
6470
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6471
+	 *
6472
+	 * @return EE_Model_Field_Base[]
6473
+	 * @throws EE_Error
6474
+	 * @since 4.9.74.p
6475
+	 */
6476
+	public function getPasswordProtectedFields()
6477
+	{
6478
+		$password_field = $this->getPasswordField();
6479
+		$fields         = [];
6480
+		if ($password_field instanceof EE_Password_Field) {
6481
+			$field_names = $password_field->protectedFields();
6482
+			foreach ($field_names as $field_name) {
6483
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6484
+			}
6485
+		}
6486
+		return $fields;
6487
+	}
6488
+
6489
+
6490
+	/**
6491
+	 * Checks if the current user can perform the requested action on this model
6492
+	 *
6493
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6494
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6495
+	 * @return bool
6496
+	 * @throws EE_Error
6497
+	 * @throws InvalidArgumentException
6498
+	 * @throws InvalidDataTypeException
6499
+	 * @throws InvalidInterfaceException
6500
+	 * @throws ReflectionException
6501
+	 * @throws UnexpectedEntityException
6502
+	 * @since 4.9.74.p
6503
+	 */
6504
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6505
+	{
6506
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6507
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6508
+		}
6509
+		if (! is_array($model_obj_or_fields_n_values)) {
6510
+			throw new UnexpectedEntityException(
6511
+				$model_obj_or_fields_n_values,
6512
+				'EE_Base_Class',
6513
+				sprintf(
6514
+					esc_html__(
6515
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6516
+						'event_espresso'
6517
+					),
6518
+					__FUNCTION__
6519
+				)
6520
+			);
6521
+		}
6522
+		return $this->exists(
6523
+			$this->alter_query_params_to_restrict_by_ID(
6524
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6525
+				[
6526
+					'default_where_conditions' => 'none',
6527
+					'caps'                     => $cap_to_check,
6528
+				]
6529
+			)
6530
+		);
6531
+	}
6532
+
6533
+
6534
+	/**
6535
+	 * Returns the query param where conditions key to the password affecting this model.
6536
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6537
+	 *
6538
+	 * @return null|string
6539
+	 * @throws EE_Error
6540
+	 * @throws InvalidArgumentException
6541
+	 * @throws InvalidDataTypeException
6542
+	 * @throws InvalidInterfaceException
6543
+	 * @throws ModelConfigurationException
6544
+	 * @throws ReflectionException
6545
+	 * @since 4.9.74.p
6546
+	 */
6547
+	public function modelChainAndPassword()
6548
+	{
6549
+		if ($this->model_chain_to_password === null) {
6550
+			throw new ModelConfigurationException(
6551
+				$this,
6552
+				esc_html_x(
6553
+				// @codingStandardsIgnoreStart
6554
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6555
+					// @codingStandardsIgnoreEnd
6556
+					'1: model name',
6557
+					'event_espresso'
6558
+				)
6559
+			);
6560
+		}
6561
+		if ($this->model_chain_to_password === '') {
6562
+			$model_with_password = $this;
6563
+		} else {
6564
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6565
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6566
+			} else {
6567
+				$last_model_in_chain = $this->model_chain_to_password;
6568
+			}
6569
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6570
+		}
6571
+
6572
+		$password_field = $model_with_password->getPasswordField();
6573
+		if ($password_field instanceof EE_Password_Field) {
6574
+			$password_field_name = $password_field->get_name();
6575
+		} else {
6576
+			throw new ModelConfigurationException(
6577
+				$this,
6578
+				sprintf(
6579
+					esc_html_x(
6580
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6581
+						'1: model name, 2: special string',
6582
+						'event_espresso'
6583
+					),
6584
+					$model_with_password->get_this_model_name(),
6585
+					$this->model_chain_to_password
6586
+				)
6587
+			);
6588
+		}
6589
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6590
+	}
6591
+
6592
+
6593
+	/**
6594
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6595
+	 * or if this model itself has a password affecting access to some of its other fields.
6596
+	 *
6597
+	 * @return boolean
6598
+	 * @since 4.9.74.p
6599
+	 */
6600
+	public function restrictedByRelatedModelPassword()
6601
+	{
6602
+		return $this->model_chain_to_password !== null;
6603
+	}
6604 6604
 }
Please login to merge, or discard this patch.
Spacing   +248 added lines, -248 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = '')
568 568
     {
569 569
         // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
570
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
571 571
             throw new EE_Error(
572 572
                 sprintf(
573 573
                     esc_html__(
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          *
591 591
          * @var EE_Table_Base[] $_tables
592 592
          */
593
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
593
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
594 594
         foreach ($this->_tables as $table_alias => $table_obj) {
595 595
             /** @var $table_obj EE_Table_Base */
596 596
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -605,10 +605,10 @@  discard block
 block discarded – undo
605 605
          *
606 606
          * @param EE_Model_Field_Base[] $_fields
607 607
          */
608
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
609 609
         $this->_invalidate_field_caches();
610 610
         foreach ($this->_fields as $table_alias => $fields_for_table) {
611
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
612 612
                 throw new EE_Error(
613 613
                     sprintf(
614 614
                         esc_html__(
@@ -644,8 +644,8 @@  discard block
 block discarded – undo
644 644
          *
645 645
          * @param EE_Model_Relation_Base[] $_model_relations
646 646
          */
647
-        $this->_model_relations = (array)apply_filters(
648
-            'FHEE__' . get_class($this) . '__construct__model_relations',
647
+        $this->_model_relations = (array) apply_filters(
648
+            'FHEE__'.get_class($this).'__construct__model_relations',
649 649
             $this->_model_relations
650 650
         );
651 651
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -657,12 +657,12 @@  discard block
 block discarded – undo
657 657
         }
658 658
         $this->set_timezone($timezone);
659 659
         // finalize default where condition strategy, or set default
660
-        if (! $this->_default_where_conditions_strategy) {
660
+        if ( ! $this->_default_where_conditions_strategy) {
661 661
             // nothing was set during child constructor, so set default
662 662
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
663 663
         }
664 664
         $this->_default_where_conditions_strategy->_finalize_construct($this);
665
-        if (! $this->_minimum_where_conditions_strategy) {
665
+        if ( ! $this->_minimum_where_conditions_strategy) {
666 666
             // nothing was set during child constructor, so set default
667 667
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
668 668
         }
@@ -673,10 +673,10 @@  discard block
 block discarded – undo
673 673
             $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
674 674
         }
675 675
         // initialize the standard cap restriction generators if none were specified by the child constructor
676
-        if (! empty($this->_cap_restriction_generators)) {
676
+        if ( ! empty($this->_cap_restriction_generators)) {
677 677
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
678
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
679
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
678
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
679
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
680 680
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
681 681
                         new EE_Restriction_Generator_Protected(),
682 682
                         $cap_context,
@@ -688,10 +688,10 @@  discard block
 block discarded – undo
688 688
         // if ($this->_cap_restriction_generators !== false) {
689 689
         // if there are cap restriction generators, use them to make the default cap restrictions
690 690
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
691
-                if (! $generator_object) {
691
+                if ( ! $generator_object) {
692 692
                     continue;
693 693
                 }
694
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
695 695
                     throw new EE_Error(
696 696
                         sprintf(
697 697
                             esc_html__(
@@ -704,12 +704,12 @@  discard block
 block discarded – undo
704 704
                     );
705 705
                 }
706 706
                 $action = $this->cap_action_for_context($context);
707
-                if (! $generator_object->construction_finalized()) {
707
+                if ( ! $generator_object->construction_finalized()) {
708 708
                     $generator_object->_construct_finalize($this, $action);
709 709
                 }
710 710
             }
711 711
         }
712
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
+        do_action('AHEE__'.get_class($this).'__construct__end');
713 713
     }
714 714
 
715 715
 
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
      */
722 722
     public static function set_model_query_blog_id($blog_id = 0)
723 723
     {
724
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
724
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
725 725
     }
726 726
 
727 727
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
     public static function instance($timezone = '')
754 754
     {
755 755
         // check if instance of Espresso_model already exists
756
-        if (! static::$_instance instanceof static) {
756
+        if ( ! static::$_instance instanceof static) {
757 757
             // instantiate Espresso_model
758 758
             static::$_instance = new static(
759 759
                 $timezone,
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
             foreach ($r->getDefaultProperties() as $property => $value) {
790 790
                 // don't set instance to null like it was originally,
791 791
                 // but it's static anyways, and we're ignoring static properties (for now at least)
792
-                if (! isset($static_properties[ $property ])) {
792
+                if ( ! isset($static_properties[$property])) {
793 793
                     static::$_instance->{$property} = $value;
794 794
                 }
795 795
             }
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
      */
814 814
     private static function getLoader()
815 815
     {
816
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
816
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
817 817
             EEM_Base::$loader = LoaderFactory::getLoader();
818 818
         }
819 819
         return EEM_Base::$loader;
@@ -833,15 +833,15 @@  discard block
 block discarded – undo
833 833
      */
834 834
     public function status_array($translated = false)
835 835
     {
836
-        if (! array_key_exists('Status', $this->_model_relations)) {
836
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
837 837
             return [];
838 838
         }
839 839
         $model_name   = $this->get_this_model_name();
840 840
         $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
841
-        $statuses      = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
841
+        $statuses = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
842 842
         $status_array = [];
843 843
         foreach ($statuses as $status) {
844
-            $status_array[ $status->ID() ] = $status->get('STS_code');
844
+            $status_array[$status->ID()] = $status->get('STS_code');
845 845
         }
846 846
         return $translated
847 847
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
     {
905 905
         $wp_user_field_name = $this->wp_user_field_name();
906 906
         if ($wp_user_field_name) {
907
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
907
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
908 908
         }
909 909
         return $query_params;
910 910
     }
@@ -922,17 +922,17 @@  discard block
 block discarded – undo
922 922
     public function wp_user_field_name()
923 923
     {
924 924
         try {
925
-            if (! empty($this->_model_chain_to_wp_user)) {
925
+            if ( ! empty($this->_model_chain_to_wp_user)) {
926 926
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
927 927
                 $last_model_name              = end($models_to_follow_to_wp_users);
928 928
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
929
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
929
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
930 930
             } else {
931 931
                 $model_with_fk_to_wp_users = $this;
932 932
                 $model_chain_to_wp_user    = '';
933 933
             }
934 934
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
935
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
935
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
936 936
         } catch (EE_Error $e) {
937 937
             return false;
938 938
         }
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
         if ($this->_custom_selections instanceof CustomSelects) {
1009 1009
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1010 1010
             $select_expressions .= $select_expressions
1011
-                ? ', ' . $custom_expressions
1011
+                ? ', '.$custom_expressions
1012 1012
                 : $custom_expressions;
1013 1013
         }
1014 1014
 
1015
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1015
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1016 1016
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1017 1017
     }
1018 1018
 
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
      */
1030 1030
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1031 1031
     {
1032
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1032
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033 1033
             return null;
1034 1034
         }
1035 1035
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
         if (is_array($columns_to_select)) {
1079 1079
             $select_sql_array = [];
1080 1080
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1081
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1081
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
                         )
1091 1091
                     );
1092 1092
                 }
1093
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1093
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094 1094
                     throw new EE_Error(
1095 1095
                         sprintf(
1096 1096
                             esc_html__(
@@ -1169,12 +1169,12 @@  discard block
 block discarded – undo
1169 1169
      */
1170 1170
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1171 1171
     {
1172
-        if (! isset($query_params[0])) {
1172
+        if ( ! isset($query_params[0])) {
1173 1173
             $query_params[0] = [];
1174 1174
         }
1175 1175
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1176 1176
         if ($conditions_from_id === null) {
1177
-            $query_params[0][ $this->primary_key_name() ] = $id;
1177
+            $query_params[0][$this->primary_key_name()] = $id;
1178 1178
         } else {
1179 1179
             // no primary key, so the $id must be from the get_index_primary_key_string()
1180 1180
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1194,7 +1194,7 @@  discard block
 block discarded – undo
1194 1194
      */
1195 1195
     public function get_one(array $query_params = [])
1196 1196
     {
1197
-        if (! is_array($query_params)) {
1197
+        if ( ! is_array($query_params)) {
1198 1198
             EE_Error::doing_it_wrong(
1199 1199
                 'EEM_Base::get_one',
1200 1200
                 sprintf(
@@ -1394,7 +1394,7 @@  discard block
 block discarded – undo
1394 1394
                 return [];
1395 1395
             }
1396 1396
         }
1397
-        if (! is_array($query_params)) {
1397
+        if ( ! is_array($query_params)) {
1398 1398
             EE_Error::doing_it_wrong(
1399 1399
                 'EEM_Base::_get_consecutive',
1400 1400
                 sprintf(
@@ -1406,10 +1406,10 @@  discard block
 block discarded – undo
1406 1406
             $query_params = [];
1407 1407
         }
1408 1408
         // let's add the where query param for consecutive look up.
1409
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1409
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1410 1410
         $query_params['limit']                 = $limit;
1411 1411
         // set direction
1412
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1412
+        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1413 1413
         $query_params['order_by'] = $operand === '>'
1414 1414
             ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1415 1415
             : [$field_to_order_by => 'DESC'] + $incoming_orderby;
@@ -1493,7 +1493,7 @@  discard block
 block discarded – undo
1493 1493
     {
1494 1494
         $field_settings = $this->field_settings_for($field_name);
1495 1495
         // if not a valid EE_Datetime_Field then throw error
1496
-        if (! $field_settings instanceof EE_Datetime_Field) {
1496
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1497 1497
             throw new EE_Error(
1498 1498
                 sprintf(
1499 1499
                     esc_html__(
@@ -1650,7 +1650,7 @@  discard block
 block discarded – undo
1650 1650
      */
1651 1651
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652 1652
     {
1653
-        if (! is_array($query_params)) {
1653
+        if ( ! is_array($query_params)) {
1654 1654
             EE_Error::doing_it_wrong(
1655 1655
                 'EEM_Base::update',
1656 1656
                 sprintf(
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
          * @param array    $query_params
1680 1680
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1681 1681
          */
1682
-        $fields_n_values = (array)apply_filters(
1682
+        $fields_n_values = (array) apply_filters(
1683 1683
             'FHEE__EEM_Base__update__fields_n_values',
1684 1684
             $fields_n_values,
1685 1685
             $this,
@@ -1697,10 +1697,10 @@  discard block
 block discarded – undo
1697 1697
         $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1698 1698
         foreach ($wpdb_select_results as $wpdb_result) {
1699 1699
             // type cast stdClass as array
1700
-            $wpdb_result = (array)$wpdb_result;
1700
+            $wpdb_result = (array) $wpdb_result;
1701 1701
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1702 1702
             if ($this->has_primary_key_field()) {
1703
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1703
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1704 1704
             } else {
1705 1705
                 // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1706 1706
                 $main_table_pk_value = null;
@@ -1716,7 +1716,7 @@  discard block
 block discarded – undo
1716 1716
                     // in this table, right? so insert a row in the current table, using any fields available
1717 1717
                     if (
1718 1718
                     ! (array_key_exists($this_table_pk_column, $wpdb_result)
1719
-                       && $wpdb_result[ $this_table_pk_column ])
1719
+                       && $wpdb_result[$this_table_pk_column])
1720 1720
                     ) {
1721 1721
                         $success = $this->_insert_into_specific_table(
1722 1722
                             $table_obj,
@@ -1724,7 +1724,7 @@  discard block
 block discarded – undo
1724 1724
                             $main_table_pk_value
1725 1725
                         );
1726 1726
                         // if we died here, report the error
1727
-                        if (! $success) {
1727
+                        if ( ! $success) {
1728 1728
                             return false;
1729 1729
                         }
1730 1730
                     }
@@ -1746,10 +1746,10 @@  discard block
 block discarded – undo
1746 1746
                 $model_objs_affected_ids     = [];
1747 1747
                 foreach ($models_affected_key_columns as $row) {
1748 1748
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1749
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1749
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1750 1750
                 }
1751 1751
             }
1752
-            if (! $model_objs_affected_ids) {
1752
+            if ( ! $model_objs_affected_ids) {
1753 1753
                 // wait wait wait- if nothing was affected let's stop here
1754 1754
                 return 0;
1755 1755
             }
@@ -1772,11 +1772,11 @@  discard block
 block discarded – undo
1772 1772
             }
1773 1773
         }
1774 1774
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
-        $SQL              = "UPDATE " . $model_query_info->get_full_join_sql()
1776
-                            . " SET " . $this->_construct_update_sql($fields_n_values)
1775
+        $SQL              = "UPDATE ".$model_query_info->get_full_join_sql()
1776
+                            . " SET ".$this->_construct_update_sql($fields_n_values)
1777 1777
                             . $model_query_info->get_where_sql();
1778 1778
         // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1779
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1779
+        $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1780 1780
         /**
1781 1781
          * Action called after a model update call has been made.
1782 1782
          *
@@ -1787,7 +1787,7 @@  discard block
 block discarded – undo
1787 1787
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1788 1788
          */
1789 1789
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1790
-        return $rows_affected;// how many supposedly got updated
1790
+        return $rows_affected; // how many supposedly got updated
1791 1791
     }
1792 1792
 
1793 1793
 
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
         }
1818 1818
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1819 1819
         $select_expressions = $field->get_qualified_column();
1820
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1820
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1821 1821
         return $this->_do_wpdb_query('get_col', [$SQL]);
1822 1822
     }
1823 1823
 
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
     {
1838 1838
         $query_params['limit'] = 1;
1839 1839
         $col                   = $this->get_col($query_params, $field_to_select);
1840
-        if (! empty($col)) {
1840
+        if ( ! empty($col)) {
1841 1841
             return reset($col);
1842 1842
         }
1843 1843
         return null;
@@ -1867,7 +1867,7 @@  discard block
 block discarded – undo
1867 1867
             $value_sql       = $prepared_value === null
1868 1868
                 ? 'NULL'
1869 1869
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1870
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1870
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1871 1871
         }
1872 1872
         return implode(",", $cols_n_values);
1873 1873
     }
@@ -1997,9 +1997,9 @@  discard block
 block discarded – undo
1997 1997
         if ($deletion_where_query_part) {
1998 1998
             $model_query_info = $this->_create_model_query_info_carrier($query_params);
1999 1999
             $table_aliases    = implode(', ', array_keys($this->_tables));
2000
-            $SQL              = "DELETE " . $table_aliases
2001
-                                . " FROM " . $model_query_info->get_full_join_sql()
2002
-                                . " WHERE " . $deletion_where_query_part;
2000
+            $SQL              = "DELETE ".$table_aliases
2001
+                                . " FROM ".$model_query_info->get_full_join_sql()
2002
+                                . " WHERE ".$deletion_where_query_part;
2003 2003
             $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2004 2004
         } else {
2005 2005
             $rows_deleted = 0;
@@ -2010,12 +2010,12 @@  discard block
 block discarded – undo
2010 2010
         if (
2011 2011
             $this->has_primary_key_field()
2012 2012
             && $rows_deleted !== false
2013
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2013
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2014 2014
         ) {
2015
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2015
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2016 2016
             foreach ($ids_for_removal as $id) {
2017
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2018
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2017
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2018
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2019 2019
                 }
2020 2020
             }
2021 2021
 
@@ -2055,7 +2055,7 @@  discard block
 block discarded – undo
2055 2055
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2056 2056
          */
2057 2057
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;// how many supposedly got deleted
2058
+        return $rows_deleted; // how many supposedly got deleted
2059 2059
     }
2060 2060
 
2061 2061
 
@@ -2151,15 +2151,15 @@  discard block
 block discarded – undo
2151 2151
                 if (
2152 2152
                     $allow_blocking
2153 2153
                     && $this->delete_is_blocked_by_related_models(
2154
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2154
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2155 2155
                     )
2156 2156
                 ) {
2157 2157
                     continue;
2158 2158
                 }
2159 2159
                 // primary table deletes
2160
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2161
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2162
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2160
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2161
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2162
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2163 2163
                 }
2164 2164
             }
2165 2165
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2168,8 +2168,8 @@  discard block
 block discarded – undo
2168 2168
                 $ids_to_delete_indexed_by_column_for_row = [];
2169 2169
                 foreach ($fields as $cpk_field) {
2170 2170
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2171
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2172
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2171
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2172
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2173 2173
                     }
2174 2174
                 }
2175 2175
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2209,7 +2209,7 @@  discard block
 block discarded – undo
2209 2209
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210 2210
                 // make sure we have unique $ids
2211 2211
                 $ids     = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2212
+                $query[] = $column.' IN('.implode(',', $ids).')';
2213 2213
             }
2214 2214
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215 2215
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218 2218
                 $values_for_each_combined_primary_key_for_a_row = [];
2219 2219
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2220
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2221 2221
                 }
2222 2222
                 $value_and_value_and_value = implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2223 2223
                 $ways_to_identify_a_row[]  = "({$value_and_value_and_value})";
@@ -2290,10 +2290,10 @@  discard block
 block discarded – undo
2290 2290
                 $column_to_count = '*';
2291 2291
             }
2292 2292
         }
2293
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2294 2294
         $SQL             =
2295
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2295
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2296
+        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2297 2297
     }
2298 2298
 
2299 2299
 
@@ -2316,7 +2316,7 @@  discard block
 block discarded – undo
2316 2316
             $field_obj = $this->get_primary_key_field();
2317 2317
         }
2318 2318
         $column_to_count = $field_obj->get_qualified_column();
2319
-        $SQL             = "SELECT SUM(" . $column_to_count . ")"
2319
+        $SQL             = "SELECT SUM(".$column_to_count.")"
2320 2320
                            . $this->_construct_2nd_half_of_select_query($model_query_info);
2321 2321
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2322 2322
         // $data_type       = $field_obj->get_wpdb_data_type();
@@ -2324,7 +2324,7 @@  discard block
 block discarded – undo
2324 2324
         //     return (float)$return_value;
2325 2325
         // }
2326 2326
         // must be %f
2327
-        return (float)$return_value;
2327
+        return (float) $return_value;
2328 2328
     }
2329 2329
 
2330 2330
 
@@ -2344,7 +2344,7 @@  discard block
 block discarded – undo
2344 2344
         // if we're in maintenance mode level 2, DON'T run any queries
2345 2345
         // because level 2 indicates the database needs updating and
2346 2346
         // is probably out of sync with the code
2347
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2347
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2348 2348
             throw new EE_Error(
2349 2349
                 esc_html__(
2350 2350
                     'Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.',
@@ -2353,7 +2353,7 @@  discard block
 block discarded – undo
2353 2353
             );
2354 2354
         }
2355 2355
         global $wpdb;
2356
-        if (! method_exists($wpdb, $wpdb_method)) {
2356
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2357 2357
             throw new EE_Error(
2358 2358
                 sprintf(
2359 2359
                     esc_html__(
@@ -2372,7 +2372,7 @@  discard block
 block discarded – undo
2372 2372
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2373 2373
         if (WP_DEBUG) {
2374 2374
             $wpdb->show_errors($old_show_errors_value);
2375
-            if (! empty($wpdb->last_error)) {
2375
+            if ( ! empty($wpdb->last_error)) {
2376 2376
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2377 2377
             }
2378 2378
             if ($result === false) {
@@ -2443,7 +2443,7 @@  discard block
 block discarded – undo
2443 2443
                     // ummmm... you in trouble
2444 2444
                     return $result;
2445 2445
             }
2446
-            if (! empty($error_message)) {
2446
+            if ( ! empty($error_message)) {
2447 2447
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2448 2448
                 trigger_error($error_message);
2449 2449
             }
@@ -2522,11 +2522,11 @@  discard block
 block discarded – undo
2522 2522
      */
2523 2523
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2524 2524
     {
2525
-        return " FROM " . $model_query_info->get_full_join_sql() .
2526
-               $model_query_info->get_where_sql() .
2527
-               $model_query_info->get_group_by_sql() .
2528
-               $model_query_info->get_having_sql() .
2529
-               $model_query_info->get_order_by_sql() .
2525
+        return " FROM ".$model_query_info->get_full_join_sql().
2526
+               $model_query_info->get_where_sql().
2527
+               $model_query_info->get_group_by_sql().
2528
+               $model_query_info->get_having_sql().
2529
+               $model_query_info->get_order_by_sql().
2530 2530
                $model_query_info->get_limit_sql();
2531 2531
     }
2532 2532
 
@@ -2719,12 +2719,12 @@  discard block
 block discarded – undo
2719 2719
         $related_model = $this->get_related_model_obj($model_name);
2720 2720
         // we're just going to use the query params on the related model's normal get_all query,
2721 2721
         // except add a condition to say to match the current mod
2722
-        if (! isset($query_params['default_where_conditions'])) {
2722
+        if ( ! isset($query_params['default_where_conditions'])) {
2723 2723
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2724 2724
         }
2725 2725
         $this_model_name                                                 = $this->get_this_model_name();
2726 2726
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2727
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2727
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2728 2728
         return $related_model->count($query_params, $field_to_count, $distinct);
2729 2729
     }
2730 2730
 
@@ -2745,7 +2745,7 @@  discard block
 block discarded – undo
2745 2745
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2746 2746
     {
2747 2747
         $related_model = $this->get_related_model_obj($model_name);
2748
-        if (! is_array($query_params)) {
2748
+        if ( ! is_array($query_params)) {
2749 2749
             EE_Error::doing_it_wrong(
2750 2750
                 'EEM_Base::sum_related',
2751 2751
                 sprintf(
@@ -2758,12 +2758,12 @@  discard block
 block discarded – undo
2758 2758
         }
2759 2759
         // we're just going to use the query params on the related model's normal get_all query,
2760 2760
         // except add a condition to say to match the current mod
2761
-        if (! isset($query_params['default_where_conditions'])) {
2761
+        if ( ! isset($query_params['default_where_conditions'])) {
2762 2762
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2763 2763
         }
2764 2764
         $this_model_name                                                 = $this->get_this_model_name();
2765 2765
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2766
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2766
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2767 2767
         return $related_model->sum($query_params, $field_to_sum);
2768 2768
     }
2769 2769
 
@@ -2815,7 +2815,7 @@  discard block
 block discarded – undo
2815 2815
                 $field_with_model_name = $field;
2816 2816
             }
2817 2817
         }
2818
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2818
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2819 2819
             throw new EE_Error(
2820 2820
                 sprintf(
2821 2821
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2852,7 +2852,7 @@  discard block
 block discarded – undo
2852 2852
          * @param array    $fields_n_values keys are the fields and values are their new values
2853 2853
          * @param EEM_Base $model           the model used
2854 2854
          */
2855
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2855
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2856 2856
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2857 2857
             $main_table = $this->_get_main_table();
2858 2858
             $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2954,14 +2954,14 @@  discard block
 block discarded – undo
2954 2954
                 || $this->get_primary_key_field()
2955 2955
                    instanceof
2956 2956
                    EE_Primary_Key_String_Field)
2957
-            && isset($fields_n_values[ $this->primary_key_name() ])
2957
+            && isset($fields_n_values[$this->primary_key_name()])
2958 2958
         ) {
2959
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2959
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2960 2960
         }
2961 2961
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2962 2962
             $uniqueness_where_params                              =
2963 2963
                 array_intersect_key($fields_n_values, $unique_index->fields());
2964
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2964
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2965 2965
         }
2966 2966
         // if there is nothing to base this search on, then we shouldn't find anything
2967 2967
         if (empty($query_params)) {
@@ -3039,16 +3039,16 @@  discard block
 block discarded – undo
3039 3039
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3040 3040
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3041 3041
             if ($prepared_value !== null) {
3042
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3042
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3043 3043
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3044 3044
             }
3045 3045
         }
3046 3046
         if ($table instanceof EE_Secondary_Table && $new_id) {
3047 3047
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3048 3048
             // so add the fk to the main table as a column
3049
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3049
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3050 3050
             $format_for_insertion[]                              =
3051
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3051
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3052 3052
         }
3053 3053
         // insert the new entry
3054 3054
         $result = $this->_do_wpdb_query(
@@ -3065,7 +3065,7 @@  discard block
 block discarded – undo
3065 3065
             }
3066 3066
             // it's not an auto-increment primary key, so
3067 3067
             // it must have been supplied
3068
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3068
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3069 3069
         }
3070 3070
         // we can't return a  primary key because there is none. instead return
3071 3071
         // a unique string indicating this model
@@ -3089,14 +3089,14 @@  discard block
 block discarded – undo
3089 3089
         if (
3090 3090
             ! $field_obj->is_nullable()
3091 3091
             && (
3092
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3093
-                || $fields_n_values[ $field_obj->get_name() ] === null
3092
+                ! isset($fields_n_values[$field_obj->get_name()])
3093
+                || $fields_n_values[$field_obj->get_name()] === null
3094 3094
             )
3095 3095
         ) {
3096
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3096
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3097 3097
         }
3098
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3099
-            ? $fields_n_values[ $field_obj->get_name() ]
3098
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3099
+            ? $fields_n_values[$field_obj->get_name()]
3100 3100
             : null;
3101 3101
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3102 3102
     }
@@ -3197,7 +3197,7 @@  discard block
 block discarded – undo
3197 3197
      */
3198 3198
     public function get_table_obj_by_alias($table_alias = '')
3199 3199
     {
3200
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3200
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3201 3201
     }
3202 3202
 
3203 3203
 
@@ -3211,7 +3211,7 @@  discard block
 block discarded – undo
3211 3211
         $other_tables = [];
3212 3212
         foreach ($this->_tables as $table_alias => $table) {
3213 3213
             if ($table instanceof EE_Secondary_Table) {
3214
-                $other_tables[ $table_alias ] = $table;
3214
+                $other_tables[$table_alias] = $table;
3215 3215
             }
3216 3216
         }
3217 3217
         return $other_tables;
@@ -3226,7 +3226,7 @@  discard block
 block discarded – undo
3226 3226
      */
3227 3227
     public function _get_fields_for_table($table_alias)
3228 3228
     {
3229
-        return $this->_fields[ $table_alias ];
3229
+        return $this->_fields[$table_alias];
3230 3230
     }
3231 3231
 
3232 3232
 
@@ -3255,7 +3255,7 @@  discard block
 block discarded – undo
3255 3255
                     $query_info_carrier,
3256 3256
                     'group_by'
3257 3257
                 );
3258
-            } elseif (! empty($query_params['group_by'])) {
3258
+            } elseif ( ! empty($query_params['group_by'])) {
3259 3259
                 $this->_extract_related_model_info_from_query_param(
3260 3260
                     $query_params['group_by'],
3261 3261
                     $query_info_carrier,
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
                     $query_info_carrier,
3278 3278
                     'order_by'
3279 3279
                 );
3280
-            } elseif (! empty($query_params['order_by'])) {
3280
+            } elseif ( ! empty($query_params['order_by'])) {
3281 3281
                 $this->_extract_related_model_info_from_query_param(
3282 3282
                     $query_params['order_by'],
3283 3283
                     $query_info_carrier,
@@ -3311,8 +3311,8 @@  discard block
 block discarded – undo
3311 3311
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312 3312
         $query_param_type
3313 3313
     ) {
3314
-        if (! empty($sub_query_params)) {
3315
-            $sub_query_params = (array)$sub_query_params;
3314
+        if ( ! empty($sub_query_params)) {
3315
+            $sub_query_params = (array) $sub_query_params;
3316 3316
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3317 3317
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3318 3318
                 $this->_extract_related_model_info_from_query_param(
@@ -3327,7 +3327,7 @@  discard block
 block discarded – undo
3327 3327
                 $query_param_sans_stars =
3328 3328
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3329 3329
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3330
-                    if (! is_array($possibly_array_of_params)) {
3330
+                    if ( ! is_array($possibly_array_of_params)) {
3331 3331
                         throw new EE_Error(
3332 3332
                             sprintf(
3333 3333
                                 esc_html__(
@@ -3353,7 +3353,7 @@  discard block
 block discarded – undo
3353 3353
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3354 3354
                     // indicating that $possible_array_of_params[1] is actually a field name,
3355 3355
                     // from which we should extract query parameters!
3356
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3356
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3357 3357
                         throw new EE_Error(
3358 3358
                             sprintf(
3359 3359
                                 esc_html__(
@@ -3391,8 +3391,8 @@  discard block
 block discarded – undo
3391 3391
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3392 3392
         $query_param_type
3393 3393
     ) {
3394
-        if (! empty($sub_query_params)) {
3395
-            if (! is_array($sub_query_params)) {
3394
+        if ( ! empty($sub_query_params)) {
3395
+            if ( ! is_array($sub_query_params)) {
3396 3396
                 throw new EE_Error(
3397 3397
                     sprintf(
3398 3398
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3429,7 +3429,7 @@  discard block
 block discarded – undo
3429 3429
      */
3430 3430
     public function _create_model_query_info_carrier($query_params)
3431 3431
     {
3432
-        if (! is_array($query_params)) {
3432
+        if ( ! is_array($query_params)) {
3433 3433
             EE_Error::doing_it_wrong(
3434 3434
                 'EEM_Base::_create_model_query_info_carrier',
3435 3435
                 sprintf(
@@ -3462,7 +3462,7 @@  discard block
 block discarded – undo
3462 3462
             // only include if related to a cpt where no password has been set
3463 3463
             $query_params[0]['OR*nopassword'] = [
3464 3464
                 $where_param_key_for_password       => '',
3465
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3465
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3466 3466
             ];
3467 3467
         }
3468 3468
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3516,7 +3516,7 @@  discard block
 block discarded – undo
3516 3516
         // set limit
3517 3517
         if (array_key_exists('limit', $query_params)) {
3518 3518
             if (is_array($query_params['limit'])) {
3519
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3519
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3520 3520
                     $e = sprintf(
3521 3521
                         esc_html__(
3522 3522
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3524,12 +3524,12 @@  discard block
 block discarded – undo
3524 3524
                         ),
3525 3525
                         http_build_query($query_params['limit'])
3526 3526
                     );
3527
-                    throw new EE_Error($e . "|" . $e);
3527
+                    throw new EE_Error($e."|".$e);
3528 3528
                 }
3529 3529
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3531
-            } elseif (! empty($query_params['limit'])) {
3532
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3530
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3531
+            } elseif ( ! empty($query_params['limit'])) {
3532
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3533 3533
             }
3534 3534
         }
3535 3535
         // set order by
@@ -3561,10 +3561,10 @@  discard block
 block discarded – undo
3561 3561
                 $order_array = [];
3562 3562
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3563 3563
                     $order         = $this->_extract_order($order);
3564
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3564
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3565 3565
                 }
3566
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3567
-            } elseif (! empty($query_params['order_by'])) {
3566
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3567
+            } elseif ( ! empty($query_params['order_by'])) {
3568 3568
                 $this->_extract_related_model_info_from_query_param(
3569 3569
                     $query_params['order_by'],
3570 3570
                     $query_object,
@@ -3575,7 +3575,7 @@  discard block
 block discarded – undo
3575 3575
                     ? $this->_extract_order($query_params['order'])
3576 3576
                     : 'DESC';
3577 3577
                 $query_object->set_order_by_sql(
3578
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3578
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3579 3579
                 );
3580 3580
             }
3581 3581
         }
@@ -3587,7 +3587,7 @@  discard block
 block discarded – undo
3587 3587
         ) {
3588 3588
             $pk_field = $this->get_primary_key_field();
3589 3589
             $order    = $this->_extract_order($query_params['order']);
3590
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3590
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3591 3591
         }
3592 3592
         // set group by
3593 3593
         if (array_key_exists('group_by', $query_params)) {
@@ -3597,10 +3597,10 @@  discard block
 block discarded – undo
3597 3597
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3598 3598
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3599 3599
                 }
3600
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3601
-            } elseif (! empty($query_params['group_by'])) {
3600
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3601
+            } elseif ( ! empty($query_params['group_by'])) {
3602 3602
                 $query_object->set_group_by_sql(
3603
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3603
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3604 3604
                 );
3605 3605
             }
3606 3606
         }
@@ -3610,7 +3610,7 @@  discard block
 block discarded – undo
3610 3610
         }
3611 3611
         // now, just verify they didn't pass anything wack
3612 3612
         foreach ($query_params as $query_key => $query_value) {
3613
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3613
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3614 3614
                 throw new EE_Error(
3615 3615
                     sprintf(
3616 3616
                         esc_html__(
@@ -3714,7 +3714,7 @@  discard block
 block discarded – undo
3714 3714
         $where_query_params = []
3715 3715
     ) {
3716 3716
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3717
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3717
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3718 3718
             throw new EE_Error(
3719 3719
                 sprintf(
3720 3720
                     esc_html__(
@@ -3744,7 +3744,7 @@  discard block
 block discarded – undo
3744 3744
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3745 3745
                 continue;
3746 3746
             }
3747
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3747
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3748 3748
                 $related_model_universal_where_params,
3749 3749
                 $where_query_params,
3750 3750
                 $related_model,
@@ -3853,19 +3853,19 @@  discard block
 block discarded – undo
3853 3853
     ) {
3854 3854
         $null_friendly_where_conditions = [];
3855 3855
         $none_overridden                = true;
3856
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3856
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3857 3857
         foreach ($default_where_conditions as $key => $val) {
3858
-            if (isset($provided_where_conditions[ $key ])) {
3858
+            if (isset($provided_where_conditions[$key])) {
3859 3859
                 $none_overridden = false;
3860 3860
             } else {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3862 3862
             }
3863 3863
         }
3864 3864
         if ($none_overridden && $default_where_conditions) {
3865 3865
             if ($model->has_primary_key_field()) {
3866
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3866
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3867 3867
                                                                                    . "."
3868
-                                                                                   . $model->primary_key_name() ] =
3868
+                                                                                   . $model->primary_key_name()] =
3869 3869
                     ['IS NULL'];
3870 3870
             }/*else{
3871 3871
                 //@todo NO PK, use other defaults
@@ -3974,7 +3974,7 @@  discard block
 block discarded – undo
3974 3974
             foreach ($tables as $table_obj) {
3975 3975
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3976 3976
                                        . $table_obj->get_fully_qualified_pk_column();
3977
-                if (! in_array($qualified_pk_column, $selects)) {
3977
+                if ( ! in_array($qualified_pk_column, $selects)) {
3978 3978
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3979 3979
                 }
3980 3980
             }
@@ -4126,9 +4126,9 @@  discard block
 block discarded – undo
4126 4126
         $query_parameter_type
4127 4127
     ) {
4128 4128
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4129
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4129
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4130 4130
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4131
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4131
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4132 4132
                 if ($possible_join_string === '') {
4133 4133
                     // nothing left to $query_param
4134 4134
                     // we should actually end in a field name, not a model like this!
@@ -4260,7 +4260,7 @@  discard block
 block discarded – undo
4260 4260
     {
4261 4261
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4262 4262
         if ($SQL) {
4263
-            return " WHERE " . $SQL;
4263
+            return " WHERE ".$SQL;
4264 4264
         }
4265 4265
         return '';
4266 4266
     }
@@ -4278,7 +4278,7 @@  discard block
 block discarded – undo
4278 4278
     {
4279 4279
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4280 4280
         if ($SQL) {
4281
-            return " HAVING " . $SQL;
4281
+            return " HAVING ".$SQL;
4282 4282
         }
4283 4283
         return '';
4284 4284
     }
@@ -4301,7 +4301,7 @@  discard block
 block discarded – undo
4301 4301
             $query_param =
4302 4302
                 $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4303 4303
                     $query_param
4304
-                );// str_replace("*",'',$query_param);
4304
+                ); // str_replace("*",'',$query_param);
4305 4305
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4306 4306
                 switch ($query_param) {
4307 4307
                     case 'not':
@@ -4335,7 +4335,7 @@  discard block
 block discarded – undo
4335 4335
             } else {
4336 4336
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4337 4337
                 // if it's not a normal field, maybe it's a custom selection?
4338
-                if (! $field_obj) {
4338
+                if ( ! $field_obj) {
4339 4339
                     if ($this->_custom_selections instanceof CustomSelects) {
4340 4340
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4341 4341
                     } else {
@@ -4351,7 +4351,7 @@  discard block
 block discarded – undo
4351 4351
                     }
4352 4352
                 }
4353 4353
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4354
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4354
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4355 4355
             }
4356 4356
         }
4357 4357
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4373,7 +4373,7 @@  discard block
 block discarded – undo
4373 4373
                 $field->get_model_name(),
4374 4374
                 $query_param
4375 4375
             );
4376
-            return $table_alias_prefix . $field->get_qualified_column();
4376
+            return $table_alias_prefix.$field->get_qualified_column();
4377 4377
         }
4378 4378
         if (
4379 4379
             $this->_custom_selections instanceof CustomSelects
@@ -4430,7 +4430,7 @@  discard block
 block discarded – undo
4430 4430
     {
4431 4431
         if (is_array($op_and_value)) {
4432 4432
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4433
-            if (! $operator) {
4433
+            if ( ! $operator) {
4434 4434
                 $php_array_like_string = [];
4435 4435
                 foreach ($op_and_value as $key => $value) {
4436 4436
                     $php_array_like_string[] = "$key=>$value";
@@ -4452,14 +4452,14 @@  discard block
 block discarded – undo
4452 4452
         }
4453 4453
         // check to see if the value is actually another field
4454 4454
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4455
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4455
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4456 4456
         }
4457 4457
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4458 4458
             // in this case, the value should be an array, or at least a comma-separated list
4459 4459
             // it will need to handle a little differently
4460 4460
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4461 4461
             // note: $cleaned_value has already been run through $wpdb->prepare()
4462
-            return $operator . SP . $cleaned_value;
4462
+            return $operator.SP.$cleaned_value;
4463 4463
         }
4464 4464
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4465 4465
             // the value should be an array with count of two.
@@ -4475,7 +4475,7 @@  discard block
 block discarded – undo
4475 4475
                 );
4476 4476
             }
4477 4477
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4478
-            return $operator . SP . $cleaned_value;
4478
+            return $operator.SP.$cleaned_value;
4479 4479
         }
4480 4480
         if (in_array($operator, $this->valid_null_style_operators())) {
4481 4481
             if ($value !== null) {
@@ -4495,10 +4495,10 @@  discard block
 block discarded – undo
4495 4495
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4496 4496
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4497 4497
             // remove other junk. So just treat it as a string.
4498
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4498
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4499 4499
         }
4500
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4500
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4501
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4502 4502
         }
4503 4503
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4504 4504
             throw new EE_Error(
@@ -4512,7 +4512,7 @@  discard block
 block discarded – undo
4512 4512
                 )
4513 4513
             );
4514 4514
         }
4515
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4515
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4516 4516
             throw new EE_Error(
4517 4517
                 sprintf(
4518 4518
                     esc_html__(
@@ -4551,7 +4551,7 @@  discard block
 block discarded – undo
4551 4551
         foreach ($values as $value) {
4552 4552
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4553 4553
         }
4554
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4554
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4555 4555
     }
4556 4556
 
4557 4557
 
@@ -4591,7 +4591,7 @@  discard block
 block discarded – undo
4591 4591
                                 . $main_table->get_table_name()
4592 4592
                                 . " WHERE FALSE";
4593 4593
         }
4594
-        return "(" . implode(",", $cleaned_values) . ")";
4594
+        return "(".implode(",", $cleaned_values).")";
4595 4595
     }
4596 4596
 
4597 4597
 
@@ -4610,7 +4610,7 @@  discard block
 block discarded – undo
4610 4610
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4611 4611
             );
4612 4612
         } //$field_obj should really just be a data type
4613
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4613
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4614 4614
             throw new EE_Error(
4615 4615
                 sprintf(
4616 4616
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4647,12 +4647,12 @@  discard block
 block discarded – undo
4647 4647
             );
4648 4648
         }
4649 4649
         $number_of_parts       = count($query_param_parts);
4650
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4650
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4651 4651
         $field_name = $last_query_param_part;
4652 4652
         $model_obj  = $number_of_parts === 1
4653 4653
             ? $this
4654 4654
             // $number_of_parts >= 2, the last part is the column name, and there are only 2parts. therefore...
4655
-            : $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4655
+            : $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4656 4656
         try {
4657 4657
             return $model_obj->field_settings_for($field_name);
4658 4658
         } catch (EE_Error $e) {
@@ -4672,7 +4672,7 @@  discard block
 block discarded – undo
4672 4672
     public function _get_qualified_column_for_field($field_name)
4673 4673
     {
4674 4674
         $all_fields = $this->field_settings();
4675
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4675
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4676 4676
         if ($field) {
4677 4677
             return $field->get_qualified_column();
4678 4678
         }
@@ -4742,10 +4742,10 @@  discard block
 block discarded – undo
4742 4742
      */
4743 4743
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4744 4744
     {
4745
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4745
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4746 4746
         $qualified_columns = [];
4747 4747
         foreach ($this->field_settings() as $field) {
4748
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4748
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4749 4749
         }
4750 4750
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4751 4751
     }
@@ -4769,11 +4769,11 @@  discard block
 block discarded – undo
4769 4769
             if ($table_obj instanceof EE_Primary_Table) {
4770 4770
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4771 4771
                     ? $table_obj->get_select_join_limit($limit)
4772
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4772
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4773 4773
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4774 4774
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4775 4775
                     ? $table_obj->get_select_join_limit_join($limit)
4776
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4776
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4777 4777
             }
4778 4778
         }
4779 4779
         return $SQL;
@@ -4843,7 +4843,7 @@  discard block
 block discarded – undo
4843 4843
         foreach ($this->field_settings() as $field_obj) {
4844 4844
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4845 4845
             /** @var $field_obj EE_Model_Field_Base */
4846
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4846
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4847 4847
         }
4848 4848
         return $data_types;
4849 4849
     }
@@ -4858,8 +4858,8 @@  discard block
 block discarded – undo
4858 4858
      */
4859 4859
     public function get_related_model_obj($model_name)
4860 4860
     {
4861
-        $model_classname = "EEM_" . $model_name;
4862
-        if (! class_exists($model_classname)) {
4861
+        $model_classname = "EEM_".$model_name;
4862
+        if ( ! class_exists($model_classname)) {
4863 4863
             throw new EE_Error(
4864 4864
                 sprintf(
4865 4865
                     esc_html__(
@@ -4871,7 +4871,7 @@  discard block
 block discarded – undo
4871 4871
                 )
4872 4872
             );
4873 4873
         }
4874
-        return call_user_func($model_classname . "::instance");
4874
+        return call_user_func($model_classname."::instance");
4875 4875
     }
4876 4876
 
4877 4877
 
@@ -4898,7 +4898,7 @@  discard block
 block discarded – undo
4898 4898
         $belongs_to_relations = [];
4899 4899
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4900 4900
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4901
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4901
+                $belongs_to_relations[$model_name] = $relation_obj;
4902 4902
             }
4903 4903
         }
4904 4904
         return $belongs_to_relations;
@@ -4915,7 +4915,7 @@  discard block
 block discarded – undo
4915 4915
     public function related_settings_for($relation_name)
4916 4916
     {
4917 4917
         $relatedModels = $this->relation_settings();
4918
-        if (! array_key_exists($relation_name, $relatedModels)) {
4918
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4919 4919
             throw new EE_Error(
4920 4920
                 sprintf(
4921 4921
                     esc_html__(
@@ -4928,7 +4928,7 @@  discard block
 block discarded – undo
4928 4928
                 )
4929 4929
             );
4930 4930
         }
4931
-        return $relatedModels[ $relation_name ];
4931
+        return $relatedModels[$relation_name];
4932 4932
     }
4933 4933
 
4934 4934
 
@@ -4944,7 +4944,7 @@  discard block
 block discarded – undo
4944 4944
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4945 4945
     {
4946 4946
         $fieldSettings = $this->field_settings($include_db_only_fields);
4947
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4947
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4948 4948
             throw new EE_Error(
4949 4949
                 sprintf(
4950 4950
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4953,7 +4953,7 @@  discard block
 block discarded – undo
4953 4953
                 )
4954 4954
             );
4955 4955
         }
4956
-        return $fieldSettings[ $fieldName ];
4956
+        return $fieldSettings[$fieldName];
4957 4957
     }
4958 4958
 
4959 4959
 
@@ -4966,7 +4966,7 @@  discard block
 block discarded – undo
4966 4966
     public function has_field($fieldName)
4967 4967
     {
4968 4968
         $fieldSettings = $this->field_settings(true);
4969
-        if (isset($fieldSettings[ $fieldName ])) {
4969
+        if (isset($fieldSettings[$fieldName])) {
4970 4970
             return true;
4971 4971
         }
4972 4972
         return false;
@@ -4982,7 +4982,7 @@  discard block
 block discarded – undo
4982 4982
     public function has_relation($relation_name)
4983 4983
     {
4984 4984
         $relations = $this->relation_settings();
4985
-        if (isset($relations[ $relation_name ])) {
4985
+        if (isset($relations[$relation_name])) {
4986 4986
             return true;
4987 4987
         }
4988 4988
         return false;
@@ -5018,7 +5018,7 @@  discard block
 block discarded – undo
5018 5018
                     break;
5019 5019
                 }
5020 5020
             }
5021
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5021
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5022 5022
                 throw new EE_Error(
5023 5023
                     sprintf(
5024 5024
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5078,17 +5078,17 @@  discard block
 block discarded – undo
5078 5078
      */
5079 5079
     public function get_foreign_key_to($model_name)
5080 5080
     {
5081
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5081
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5082 5082
             foreach ($this->field_settings() as $field) {
5083 5083
                 if (
5084 5084
                     $field instanceof EE_Foreign_Key_Field_Base
5085 5085
                     && in_array($model_name, $field->get_model_names_pointed_to())
5086 5086
                 ) {
5087
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5087
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5088 5088
                     break;
5089 5089
                 }
5090 5090
             }
5091
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5091
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5092 5092
                 throw new EE_Error(
5093 5093
                     sprintf(
5094 5094
                         esc_html__(
@@ -5101,7 +5101,7 @@  discard block
 block discarded – undo
5101 5101
                 );
5102 5102
             }
5103 5103
         }
5104
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5104
+        return $this->_cache_foreign_key_to_fields[$model_name];
5105 5105
     }
5106 5106
 
5107 5107
 
@@ -5117,7 +5117,7 @@  discard block
 block discarded – undo
5117 5117
     {
5118 5118
         $table_alias_sans_model_relation_chain_prefix =
5119 5119
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5120
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5120
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5121 5121
     }
5122 5122
 
5123 5123
 
@@ -5135,7 +5135,7 @@  discard block
 block discarded – undo
5135 5135
                 $this->_cached_fields = [];
5136 5136
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5137 5137
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5138
+                        $this->_cached_fields[$field_name] = $field_obj;
5139 5139
                     }
5140 5140
                 }
5141 5141
             }
@@ -5146,8 +5146,8 @@  discard block
 block discarded – undo
5146 5146
             foreach ($this->_fields as $fields_corresponding_to_table) {
5147 5147
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148 5148
                     /** @var $field_obj EE_Model_Field_Base */
5149
-                    if (! $field_obj->is_db_only_field()) {
5150
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5149
+                    if ( ! $field_obj->is_db_only_field()) {
5150
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5151 5151
                     }
5152 5152
                 }
5153 5153
             }
@@ -5175,7 +5175,7 @@  discard block
 block discarded – undo
5175 5175
         $count_if_model_has_no_primary_key = 0;
5176 5176
         $has_primary_key                   = $this->has_primary_key_field();
5177 5177
         $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5178
-        foreach ((array)$rows as $row) {
5178
+        foreach ((array) $rows as $row) {
5179 5179
             if (empty($row)) {
5180 5180
                 // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5181 5181
                 return [];
@@ -5188,12 +5188,12 @@  discard block
 block discarded – undo
5188 5188
                     $primary_key_field->get_qualified_column(),
5189 5189
                     $primary_key_field->get_table_column()
5190 5190
                 );
5191
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5191
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5192 5192
                     continue;
5193 5193
                 }
5194 5194
             }
5195 5195
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5196
-            if (! $classInstance) {
5196
+            if ( ! $classInstance) {
5197 5197
                 throw new EE_Error(
5198 5198
                     sprintf(
5199 5199
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5206,7 +5206,7 @@  discard block
 block discarded – undo
5206 5206
             $classInstance->set_timezone($this->get_timezone(), true);
5207 5207
             // make sure if there is any timezone setting present that we set the timezone for the object
5208 5208
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5209
-            $array_of_objects[ $key ] = $classInstance;
5209
+            $array_of_objects[$key] = $classInstance;
5210 5210
             // also, for all the relations of type BelongsTo, see if we can cache
5211 5211
             // those related models
5212 5212
             // (we could do this for other relations too, but if there are conditions
@@ -5250,9 +5250,9 @@  discard block
 block discarded – undo
5250 5250
         $results = [];
5251 5251
         if ($this->_custom_selections instanceof CustomSelects) {
5252 5252
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5253
-                if (isset($db_results_row[ $alias ])) {
5254
-                    $results[ $alias ] = $this->convertValueToDataType(
5255
-                        $db_results_row[ $alias ],
5253
+                if (isset($db_results_row[$alias])) {
5254
+                    $results[$alias] = $this->convertValueToDataType(
5255
+                        $db_results_row[$alias],
5256 5256
                         $this->_custom_selections->getDataTypeForAlias($alias)
5257 5257
                     );
5258 5258
                 }
@@ -5273,11 +5273,11 @@  discard block
 block discarded – undo
5273 5273
     {
5274 5274
         switch ($datatype) {
5275 5275
             case '%f':
5276
-                return (float)$value;
5276
+                return (float) $value;
5277 5277
             case '%d':
5278
-                return (int)$value;
5278
+                return (int) $value;
5279 5279
             default:
5280
-                return (string)$value;
5280
+                return (string) $value;
5281 5281
         }
5282 5282
     }
5283 5283
 
@@ -5297,7 +5297,7 @@  discard block
 block discarded – undo
5297 5297
         $this_model_fields_and_values = [];
5298 5298
         // setup the row using default values;
5299 5299
         foreach ($this->field_settings() as $field_name => $field_obj) {
5300
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5300
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5301 5301
         }
5302 5302
         $className = $this->_get_class_name();
5303 5303
         return EE_Registry::instance()->load_class(
@@ -5318,20 +5318,20 @@  discard block
 block discarded – undo
5318 5318
      */
5319 5319
     public function instantiate_class_from_array_or_object($cols_n_values)
5320 5320
     {
5321
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5321
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5322 5322
             $cols_n_values = get_object_vars($cols_n_values);
5323 5323
         }
5324 5324
         $primary_key = null;
5325 5325
         // make sure the array only has keys that are fields/columns on this model
5326 5326
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5327
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5328
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5327
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5328
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5329 5329
         }
5330 5330
         $className = $this->_get_class_name();
5331 5331
         // check we actually found results that we can use to build our model object
5332 5332
         // if not, return null
5333 5333
         if ($this->has_primary_key_field()) {
5334
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5334
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5335 5335
                 return null;
5336 5336
             }
5337 5337
         } elseif ($this->unique_indexes()) {
@@ -5343,7 +5343,7 @@  discard block
 block discarded – undo
5343 5343
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5344 5344
         if ($primary_key) {
5345 5345
             $classInstance = $this->get_from_entity_map($primary_key);
5346
-            if (! $classInstance) {
5346
+            if ( ! $classInstance) {
5347 5347
                 $classInstance = EE_Registry::instance()->load_class(
5348 5348
                     $className,
5349 5349
                     [$this_model_fields_n_values, $this->get_timezone()],
@@ -5373,8 +5373,8 @@  discard block
 block discarded – undo
5373 5373
      */
5374 5374
     public function get_from_entity_map($id)
5375 5375
     {
5376
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5377
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]
5376
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5377
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id]
5378 5378
             : null;
5379 5379
     }
5380 5380
 
@@ -5397,7 +5397,7 @@  discard block
 block discarded – undo
5397 5397
     public function add_to_entity_map(EE_Base_Class $object)
5398 5398
     {
5399 5399
         $className = $this->_get_class_name();
5400
-        if (! $object instanceof $className) {
5400
+        if ( ! $object instanceof $className) {
5401 5401
             throw new EE_Error(
5402 5402
                 sprintf(
5403 5403
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5406,7 +5406,7 @@  discard block
 block discarded – undo
5406 5406
                 )
5407 5407
             );
5408 5408
         }
5409
-        if (! $object->ID()) {
5409
+        if ( ! $object->ID()) {
5410 5410
             throw new DomainException(
5411 5411
                 sprintf(
5412 5412
                     esc_html__(
@@ -5422,7 +5422,7 @@  discard block
 block discarded – undo
5422 5422
         if ($classInstance) {
5423 5423
             return $classInstance;
5424 5424
         }
5425
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5425
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5426 5426
         return $object;
5427 5427
     }
5428 5428
 
@@ -5437,11 +5437,11 @@  discard block
 block discarded – undo
5437 5437
     public function clear_entity_map($id = null)
5438 5438
     {
5439 5439
         if (empty($id)) {
5440
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5440
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5441 5441
             return true;
5442 5442
         }
5443
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5444
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5443
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5444
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5445 5445
             return true;
5446 5446
         }
5447 5447
         return false;
@@ -5486,18 +5486,18 @@  discard block
 block discarded – undo
5486 5486
             // there is a primary key on this table and its not set. Use defaults for all its columns
5487 5487
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5488 5488
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5489
-                    if (! $field_obj->is_db_only_field()) {
5489
+                    if ( ! $field_obj->is_db_only_field()) {
5490 5490
                         // prepare field as if its coming from db
5491 5491
                         $prepared_value                            =
5492 5492
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5493
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5493
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5494 5494
                     }
5495 5495
                 }
5496 5496
             } else {
5497 5497
                 // the table's rows existed. Use their values
5498 5498
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5499
-                    if (! $field_obj->is_db_only_field()) {
5500
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5499
+                    if ( ! $field_obj->is_db_only_field()) {
5500
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5501 5501
                             $cols_n_values,
5502 5502
                             $field_obj->get_qualified_column(),
5503 5503
                             $field_obj->get_table_column()
@@ -5524,17 +5524,17 @@  discard block
 block discarded – undo
5524 5524
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5525 5525
         // does the field on the model relate to this column retrieved from the db?
5526 5526
         // or is it a db-only field? (not relating to the model)
5527
-        if (isset($cols_n_values[ $qualified_column ])) {
5528
-            $value = $cols_n_values[ $qualified_column ];
5529
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5530
-            $value = $cols_n_values[ $regular_column ];
5531
-        } elseif (! empty($this->foreign_key_aliases)) {
5527
+        if (isset($cols_n_values[$qualified_column])) {
5528
+            $value = $cols_n_values[$qualified_column];
5529
+        } elseif (isset($cols_n_values[$regular_column])) {
5530
+            $value = $cols_n_values[$regular_column];
5531
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5532 5532
             // no PK?  ok check if there is a foreign key alias set for this table
5533 5533
             // then check if that alias exists in the incoming data
5534 5534
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5535 5535
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5536
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5537
-                    $value = $cols_n_values[ $FK_alias ];
5536
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5537
+                    $value = $cols_n_values[$FK_alias];
5538 5538
                     [$pk_class] = explode('.', $PK_column);
5539 5539
                     $pk_model_name = "EEM_{$pk_class}";
5540 5540
                     /** @var EEM_Base $pk_model */
@@ -5578,7 +5578,7 @@  discard block
 block discarded – undo
5578 5578
                     $obj_in_map->clear_cache($relation_name, null, true);
5579 5579
                 }
5580 5580
             }
5581
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5581
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5582 5582
             return $obj_in_map;
5583 5583
         }
5584 5584
         return $this->get_one_by_ID($id);
@@ -5630,7 +5630,7 @@  discard block
 block discarded – undo
5630 5630
      */
5631 5631
     private function _get_class_name()
5632 5632
     {
5633
-        return "EE_" . $this->get_this_model_name();
5633
+        return "EE_".$this->get_this_model_name();
5634 5634
     }
5635 5635
 
5636 5636
 
@@ -5644,7 +5644,7 @@  discard block
 block discarded – undo
5644 5644
      */
5645 5645
     public function item_name($quantity = 1)
5646 5646
     {
5647
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5647
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5648 5648
     }
5649 5649
 
5650 5650
 
@@ -5676,7 +5676,7 @@  discard block
 block discarded – undo
5676 5676
     {
5677 5677
         $className = get_class($this);
5678 5678
         $tagName   = "FHEE__{$className}__{$methodName}";
5679
-        if (! has_filter($tagName)) {
5679
+        if ( ! has_filter($tagName)) {
5680 5680
             throw new EE_Error(
5681 5681
                 sprintf(
5682 5682
                     esc_html__(
@@ -5845,7 +5845,7 @@  discard block
 block discarded – undo
5845 5845
         $unique_indexes = [];
5846 5846
         foreach ($this->_indexes as $name => $index) {
5847 5847
             if ($index instanceof EE_Unique_Index) {
5848
-                $unique_indexes [ $name ] = $index;
5848
+                $unique_indexes [$name] = $index;
5849 5849
             }
5850 5850
         }
5851 5851
         return $unique_indexes;
@@ -5909,7 +5909,7 @@  discard block
 block discarded – undo
5909 5909
         $key_values_in_combined_pk = [];
5910 5910
         parse_str($index_primary_key_string, $key_values_in_combined_pk);
5911 5911
         foreach ($key_fields as $key_field_name => $field_obj) {
5912
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5912
+            if ( ! isset($key_values_in_combined_pk[$key_field_name])) {
5913 5913
                 return null;
5914 5914
             }
5915 5915
         }
@@ -5929,7 +5929,7 @@  discard block
 block discarded – undo
5929 5929
     {
5930 5930
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5931 5931
         foreach ($keys_it_should_have as $key) {
5932
-            if (! isset($key_values[ $key ])) {
5932
+            if ( ! isset($key_values[$key])) {
5933 5933
                 return false;
5934 5934
             }
5935 5935
         }
@@ -5968,8 +5968,8 @@  discard block
 block discarded – undo
5968 5968
         }
5969 5969
         // even copies obviously won't have the same ID, so remove the primary key
5970 5970
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5971
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5972
-            unset($attributes_array[ $this->primary_key_name() ]);
5971
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5972
+            unset($attributes_array[$this->primary_key_name()]);
5973 5973
         }
5974 5974
         if (isset($query_params[0])) {
5975 5975
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5991,7 +5991,7 @@  discard block
 block discarded – undo
5991 5991
      */
5992 5992
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5993 5993
     {
5994
-        if (! is_array($query_params)) {
5994
+        if ( ! is_array($query_params)) {
5995 5995
             EE_Error::doing_it_wrong(
5996 5996
                 'EEM_Base::get_one_copy',
5997 5997
                 sprintf(
@@ -6041,7 +6041,7 @@  discard block
 block discarded – undo
6041 6041
     private function _prepare_operator_for_sql($operator_supplied)
6042 6042
     {
6043 6043
         $sql_operator =
6044
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6044
+            isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6045 6045
                 : null;
6046 6046
         if ($sql_operator) {
6047 6047
             return $sql_operator;
@@ -6140,7 +6140,7 @@  discard block
 block discarded – undo
6140 6140
         $objs  = $this->get_all($query_params);
6141 6141
         $names = [];
6142 6142
         foreach ($objs as $obj) {
6143
-            $names[ $obj->ID() ] = $obj->name();
6143
+            $names[$obj->ID()] = $obj->name();
6144 6144
         }
6145 6145
         return $names;
6146 6146
     }
@@ -6160,7 +6160,7 @@  discard block
 block discarded – undo
6160 6160
      */
6161 6161
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6162 6162
     {
6163
-        if (! $this->has_primary_key_field()) {
6163
+        if ( ! $this->has_primary_key_field()) {
6164 6164
             if (WP_DEBUG) {
6165 6165
                 EE_Error::add_error(
6166 6166
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6173,7 +6173,7 @@  discard block
 block discarded – undo
6173 6173
         $IDs = [];
6174 6174
         foreach ($model_objects as $model_object) {
6175 6175
             $id = $model_object->ID();
6176
-            if (! $id) {
6176
+            if ( ! $id) {
6177 6177
                 if ($filter_out_empty_ids) {
6178 6178
                     continue;
6179 6179
                 }
@@ -6223,22 +6223,22 @@  discard block
 block discarded – undo
6223 6223
         EEM_Base::verify_is_valid_cap_context($context);
6224 6224
         // check if we ought to run the restriction generator first
6225 6225
         if (
6226
-            isset($this->_cap_restriction_generators[ $context ])
6227
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6228
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6226
+            isset($this->_cap_restriction_generators[$context])
6227
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6228
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6229 6229
         ) {
6230
-            $this->_cap_restrictions[ $context ] = array_merge(
6231
-                $this->_cap_restrictions[ $context ],
6232
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6230
+            $this->_cap_restrictions[$context] = array_merge(
6231
+                $this->_cap_restrictions[$context],
6232
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6233 6233
             );
6234 6234
         }
6235 6235
         // and make sure we've finalized the construction of each restriction
6236
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6236
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6237 6237
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6238 6238
                 $where_conditions_obj->_finalize_construct($this);
6239 6239
             }
6240 6240
         }
6241
-        return $this->_cap_restrictions[ $context ];
6241
+        return $this->_cap_restrictions[$context];
6242 6242
     }
6243 6243
 
6244 6244
 
@@ -6268,9 +6268,9 @@  discard block
 block discarded – undo
6268 6268
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6269 6269
             if (
6270 6270
             ! EE_Capabilities::instance()
6271
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6271
+                             ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6272 6272
             ) {
6273
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6273
+                $missing_caps[$cap] = $restriction_if_no_cap;
6274 6274
             }
6275 6275
         }
6276 6276
         return $missing_caps;
@@ -6303,8 +6303,8 @@  discard block
 block discarded – undo
6303 6303
     public function cap_action_for_context($context)
6304 6304
     {
6305 6305
         $mapping = $this->cap_contexts_to_cap_action_map();
6306
-        if (isset($mapping[ $context ])) {
6307
-            return $mapping[ $context ];
6306
+        if (isset($mapping[$context])) {
6307
+            return $mapping[$context];
6308 6308
         }
6309 6309
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6310 6310
             return $action;
@@ -6422,7 +6422,7 @@  discard block
 block discarded – undo
6422 6422
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6423 6423
             if (
6424 6424
                 $query_param_key === $logic_query_param_key
6425
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6425
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6426 6426
             ) {
6427 6427
                 return true;
6428 6428
             }
@@ -6480,7 +6480,7 @@  discard block
 block discarded – undo
6480 6480
         if ($password_field instanceof EE_Password_Field) {
6481 6481
             $field_names = $password_field->protectedFields();
6482 6482
             foreach ($field_names as $field_name) {
6483
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6483
+                $fields[$field_name] = $this->field_settings_for($field_name);
6484 6484
             }
6485 6485
         }
6486 6486
         return $fields;
@@ -6506,7 +6506,7 @@  discard block
 block discarded – undo
6506 6506
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6507 6507
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6508 6508
         }
6509
-        if (! is_array($model_obj_or_fields_n_values)) {
6509
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6510 6510
             throw new UnexpectedEntityException(
6511 6511
                 $model_obj_or_fields_n_values,
6512 6512
                 'EE_Base_Class',
@@ -6586,7 +6586,7 @@  discard block
 block discarded – undo
6586 6586
                 )
6587 6587
             );
6588 6588
         }
6589
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6589
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6590 6590
     }
6591 6591
 
6592 6592
 
Please login to merge, or discard this patch.
core/db_models/relations/EE_Model_Relation_Base.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -149,9 +149,9 @@  discard block
 block discarded – undo
149 149
 
150 150
     /**
151 151
      * @param        $other_table
152
-     * @param        $other_table_alias
152
+     * @param        string $other_table_alias
153 153
      * @param        $other_table_column
154
-     * @param        $this_table_alias
154
+     * @param        string $this_table_alias
155 155
      * @param        $this_table_join_column
156 156
      * @param string $extra_join_sql
157 157
      * @return string
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
      * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
226 226
      * model objects will only be soft-deleted.
227 227
      *
228
-     * @param EE_Base_Class|int|string $model_object_or_id
228
+     * @param EE_Base_Class|null $model_object_or_id
229 229
      * @param array                    $query_params
230 230
      * @return int of how many related models got deleted
231 231
      * @throws EE_Error
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
      * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
260 260
      * model objects will only be soft-deleted.
261 261
      *
262
-     * @param EE_Base_Class|int|string $model_object_or_id
262
+     * @param EE_Base_Class|null $model_object_or_id
263 263
      * @param array                    $query_params
264 264
      * @return int of how many related models got deleted
265 265
      * @throws EE_Error
Please login to merge, or discard this patch.
Indentation   +507 added lines, -507 removed lines patch added patch discarded remove patch
@@ -16,512 +16,512 @@
 block discarded – undo
16 16
  */
17 17
 abstract class EE_Model_Relation_Base implements HasSchemaInterface
18 18
 {
19
-    /**
20
-     * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
21
-     *
22
-     * @var string eg Event, Question_Group, Registration
23
-     */
24
-    private $_this_model_name;
25
-    /**
26
-     * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
27
-     *
28
-     * @var string eg Event, Question_Group, Registration
29
-     */
30
-    private $_other_model_name;
31
-
32
-    /**
33
-     * this is typically used when calling the relation models to make sure they inherit any set timezone from the
34
-     * initiating model.
35
-     *
36
-     * @var string
37
-     */
38
-    protected $_timezone;
39
-
40
-    /**
41
-     * If you try to delete "this_model", and there are related "other_models",
42
-     * and this isn't null, then abandon the deletion and add this warning.
43
-     * This effectively makes it impossible to delete "this_model" while there are
44
-     * related "other_models" along this relation.
45
-     *
46
-     * @var string (internationalized)
47
-     */
48
-    protected $_blocking_delete_error_message;
49
-
50
-    protected $_blocking_delete = false;
51
-
52
-    /**
53
-     * Object representing the relationship between two models. This knows how to join the models,
54
-     * get related models across the relation, and add-and-remove the relationships.
55
-     *
56
-     * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
57
-     *                                               and add an error) the deletion of this model
58
-     * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
59
-     *                                               default
60
-     */
61
-    public function __construct($block_deletes, $blocking_delete_error_message)
62
-    {
63
-        $this->_blocking_delete               = $block_deletes;
64
-        $this->_blocking_delete_error_message = $blocking_delete_error_message;
65
-    }
66
-
67
-
68
-    /**
69
-     * @param $this_model_name
70
-     * @param $other_model_name
71
-     * @throws EE_Error
72
-     */
73
-    public function _construct_finalize_set_models($this_model_name, $other_model_name)
74
-    {
75
-        $this->_this_model_name  = $this_model_name;
76
-        $this->_other_model_name = $other_model_name;
77
-        if (is_string($this->_blocking_delete)) {
78
-            throw new EE_Error(sprintf(
79
-                esc_html__(
80
-                    "When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
81
-                    "event_espresso"
82
-                ),
83
-                get_class($this),
84
-                $this_model_name,
85
-                $other_model_name,
86
-                $this->_blocking_delete
87
-            ));
88
-        }
89
-    }
90
-
91
-
92
-    /**
93
-     * Gets the model where this relation is defined.
94
-     *
95
-     * @return EEM_Base
96
-     */
97
-    public function get_this_model()
98
-    {
99
-        return $this->_get_model($this->_this_model_name);
100
-    }
101
-
102
-
103
-    /**
104
-     * Gets the model which this relation establishes the relation TO (ie,
105
-     * this relation object was defined on get_this_model(), get_other_model() is the other one)
106
-     *
107
-     * @return EEM_Base
108
-     */
109
-    public function get_other_model()
110
-    {
111
-        return $this->_get_model($this->_other_model_name);
112
-    }
113
-
114
-
115
-    /**
116
-     * Internally used by get_this_model() and get_other_model()
117
-     *
118
-     * @param string $model_name like Event, Question_Group, etc. omit the EEM_
119
-     * @return EEM_Base
120
-     * @throws EE_Error
121
-     * @throws ReflectionException
122
-     */
123
-    protected function _get_model($model_name)
124
-    {
125
-        $modelInstance = EE_Registry::instance()->load_model($model_name);
126
-        // if the timezone is NOT set on the model but IS set for this relation
127
-        // (which seems really unlikely to ever happen, but whatever)
128
-        // make sure the model timezone is set
129
-        if ($this->_timezone && ! $modelInstance->get_timezone()) {
130
-            $modelInstance->set_timezone($this->_timezone);
131
-        }
132
-        return $modelInstance;
133
-    }
134
-
135
-
136
-    /**
137
-     * entirely possible that relations may be called from a model and we need to make sure those relations have their
138
-     * timezone set correctly.
139
-     *
140
-     * @param string $timezone timezone to set.
141
-     */
142
-    public function set_timezone($timezone)
143
-    {
144
-        if (! empty($timezone)) {
145
-            $this->_timezone = $timezone;
146
-        }
147
-    }
148
-
149
-
150
-    /**
151
-     * @param        $other_table
152
-     * @param        $other_table_alias
153
-     * @param        $other_table_column
154
-     * @param        $this_table_alias
155
-     * @param        $this_table_join_column
156
-     * @param string $extra_join_sql
157
-     * @return string
158
-     */
159
-    protected function _left_join(
160
-        $other_table,
161
-        $other_table_alias,
162
-        $other_table_column,
163
-        $this_table_alias,
164
-        $this_table_join_column,
165
-        $extra_join_sql = ''
166
-    ) {
167
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
168
-    }
169
-
170
-
171
-    /**
172
-     * Gets all the model objects of type of other model related to $model_object,
173
-     * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
174
-     * For both of those child classes, $model_object must be saved so that it has an ID before querying,
175
-     * otherwise an error will be thrown. Note: by default we disable default_where_conditions
176
-     * EE_Belongs_To_Relation doesn't need to be saved before querying.
177
-     *
178
-     * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
179
-     * @param array             $query_params                            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
180
-     * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
181
-     * @return EE_Base_Class[]
182
-     * @throws EE_Error
183
-     * @throws ReflectionException
184
-     */
185
-    public function get_all_related(
186
-        $model_object_or_id,
187
-        $query_params = array(),
188
-        $values_already_prepared_by_model_object = false
189
-    ) {
190
-        if ($values_already_prepared_by_model_object !== false) {
191
-            EE_Error::doing_it_wrong(
192
-                'EE_Model_Relation_Base::get_all_related',
193
-                esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
194
-                '4.8.1'
195
-            );
196
-        }
197
-        $query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
198
-        $query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
199
-                                                             . "."
200
-                                                             . $this->get_this_model()->get_primary_key_field()->get_name();
201
-        $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
202
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
203
-        return $this->get_other_model()->get_all($query_params);
204
-    }
205
-
206
-
207
-    /**
208
-     * Alters the $query_params to disable default where conditions, unless otherwise specified
209
-     *
210
-     * @param array $query_params
211
-     * @return array
212
-     */
213
-    protected function _disable_default_where_conditions_on_query_param($query_params)
214
-    {
215
-        if (! isset($query_params['default_where_conditions'])) {
216
-            $query_params['default_where_conditions'] = 'none';
217
-        }
218
-        return $query_params;
219
-    }
220
-
221
-
222
-    /**
223
-     * Deletes the related model objects which meet the query parameters. If no
224
-     * parameters are specified, then all related model objects will be deleted.
225
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
226
-     * model objects will only be soft-deleted.
227
-     *
228
-     * @param EE_Base_Class|int|string $model_object_or_id
229
-     * @param array                    $query_params
230
-     * @return int of how many related models got deleted
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function delete_all_related($model_object_or_id, $query_params = array())
235
-    {
236
-        // for each thing we would delete,
237
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
238
-        // determine if it's blocked by anything else before it can be deleted
239
-        $deleted_count = 0;
240
-        foreach ($related_model_objects as $related_model_object) {
241
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
242
-                $related_model_object,
243
-                $model_object_or_id
244
-            );
245
-            /* @var $model_object_or_id EE_Base_Class */
246
-            if (! $delete_is_blocked) {
247
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
248
-                $related_model_object->delete();
249
-                $deleted_count++;
250
-            }
251
-        }
252
-        return $deleted_count;
253
-    }
254
-
255
-
256
-    /**
257
-     * Deletes the related model objects which meet the query parameters. If no
258
-     * parameters are specified, then all related model objects will be deleted.
259
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
260
-     * model objects will only be soft-deleted.
261
-     *
262
-     * @param EE_Base_Class|int|string $model_object_or_id
263
-     * @param array                    $query_params
264
-     * @return int of how many related models got deleted
265
-     * @throws EE_Error
266
-     * @throws ReflectionException
267
-     */
268
-    public function delete_related_permanently($model_object_or_id, $query_params = array())
269
-    {
270
-        // for each thing we would delete,
271
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
272
-        // determine if it's blocked by anything else before it can be deleted
273
-        $deleted_count = 0;
274
-        foreach ($related_model_objects as $related_model_object) {
275
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
276
-                $related_model_object,
277
-                $model_object_or_id
278
-            );
279
-            /* @var $model_object_or_id EE_Base_Class */
280
-            if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
281
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
282
-                $deleted_count++;
283
-                if (! $delete_is_blocked) {
284
-                    $related_model_object->delete_permanently();
285
-                } else {
286
-                    // delete is blocked
287
-                    // brent and darren, in this case, wanted to just soft delete it then
288
-                    $related_model_object->delete();
289
-                }
290
-            } else {
291
-                // its not a soft-deletable thing anyways. do the normal logic.
292
-                if (! $delete_is_blocked) {
293
-                    $this->remove_relation_to($model_object_or_id, $related_model_object);
294
-                    $related_model_object->delete();
295
-                    $deleted_count++;
296
-                }
297
-            }
298
-        }
299
-        return $deleted_count;
300
-    }
301
-
302
-
303
-    /**
304
-     * this just returns a model_object_id for incoming item that could be an object or id.
305
-     *
306
-     * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
307
-     * @throws EE_Error
308
-     * @return int
309
-     */
310
-    protected function _get_model_object_id($model_object_or_id)
311
-    {
312
-        $model_object_id = $model_object_or_id;
313
-        if ($model_object_or_id instanceof EE_Base_Class) {
314
-            $model_object_id = $model_object_or_id->ID();
315
-        }
316
-        if (! $model_object_id) {
317
-            throw new EE_Error(sprintf(
318
-                esc_html__(
319
-                    "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
320
-                    "event_espresso"
321
-                ),
322
-                $this->get_other_model()->get_this_model_name(),
323
-                $this->get_this_model()->get_this_model_name()
324
-            ));
325
-        }
326
-        return $model_object_id;
327
-    }
328
-
329
-
330
-    /**
331
-     * Gets the SQL string for performing the join between this model and the other model.
332
-     *
333
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
334
-     * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
335
-     *                other_model_primary_table.fk" etc
336
-     */
337
-    abstract public function get_join_statement($model_relation_chain);
338
-
339
-
340
-    /**
341
-     * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
342
-     * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
343
-     * relationship only allows this model to be related to a single other model of this type)
344
-     *
345
-     * @param       $this_obj_or_id
346
-     * @param       $other_obj_or_id
347
-     * @param array $extra_join_model_fields_n_values
348
-     * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
349
-     *                        $other_obj_or_id)
350
-     */
351
-    abstract public function add_relation_to(
352
-        $this_obj_or_id,
353
-        $other_obj_or_id,
354
-        $extra_join_model_fields_n_values = array()
355
-    );
356
-
357
-
358
-    /**
359
-     * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
360
-     * model objects
361
-     *
362
-     * @param       $this_obj_or_id
363
-     * @param       $other_obj_or_id
364
-     * @param array $where_query
365
-     * @return bool
366
-     */
367
-    abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
368
-
369
-
370
-    /**
371
-     * Removes ALL relation instances for this relation obj
372
-     *
373
-     * @param EE_Base_Class|int $this_obj_or_id
374
-     * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
375
-     * @return EE_Base_Class[]
376
-     * @throws \EE_Error
377
-     */
378
-    public function remove_relations($this_obj_or_id, $where_query_param = array())
379
-    {
380
-        $related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
381
-        $objs_removed   = array();
382
-        foreach ($related_things as $related_thing) {
383
-            $objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
384
-        }
385
-        return $objs_removed;
386
-    }
387
-
388
-
389
-    /**
390
-     * If you aren't allowed to delete this model when there are related models across this
391
-     * relation object, return true. Otherwise, if you can delete this model even though
392
-     * related objects exist, returns false.
393
-     *
394
-     * @return boolean
395
-     */
396
-    public function block_delete_if_related_models_exist()
397
-    {
398
-        return $this->_blocking_delete;
399
-    }
400
-
401
-
402
-    /**
403
-     * Gets the error message to show
404
-     *
405
-     * @return string
406
-     */
407
-    public function get_deletion_error_message()
408
-    {
409
-        if ($this->_blocking_delete_error_message) {
410
-            return $this->_blocking_delete_error_message;
411
-        } else {
19
+	/**
20
+	 * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
21
+	 *
22
+	 * @var string eg Event, Question_Group, Registration
23
+	 */
24
+	private $_this_model_name;
25
+	/**
26
+	 * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
27
+	 *
28
+	 * @var string eg Event, Question_Group, Registration
29
+	 */
30
+	private $_other_model_name;
31
+
32
+	/**
33
+	 * this is typically used when calling the relation models to make sure they inherit any set timezone from the
34
+	 * initiating model.
35
+	 *
36
+	 * @var string
37
+	 */
38
+	protected $_timezone;
39
+
40
+	/**
41
+	 * If you try to delete "this_model", and there are related "other_models",
42
+	 * and this isn't null, then abandon the deletion and add this warning.
43
+	 * This effectively makes it impossible to delete "this_model" while there are
44
+	 * related "other_models" along this relation.
45
+	 *
46
+	 * @var string (internationalized)
47
+	 */
48
+	protected $_blocking_delete_error_message;
49
+
50
+	protected $_blocking_delete = false;
51
+
52
+	/**
53
+	 * Object representing the relationship between two models. This knows how to join the models,
54
+	 * get related models across the relation, and add-and-remove the relationships.
55
+	 *
56
+	 * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
57
+	 *                                               and add an error) the deletion of this model
58
+	 * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
59
+	 *                                               default
60
+	 */
61
+	public function __construct($block_deletes, $blocking_delete_error_message)
62
+	{
63
+		$this->_blocking_delete               = $block_deletes;
64
+		$this->_blocking_delete_error_message = $blocking_delete_error_message;
65
+	}
66
+
67
+
68
+	/**
69
+	 * @param $this_model_name
70
+	 * @param $other_model_name
71
+	 * @throws EE_Error
72
+	 */
73
+	public function _construct_finalize_set_models($this_model_name, $other_model_name)
74
+	{
75
+		$this->_this_model_name  = $this_model_name;
76
+		$this->_other_model_name = $other_model_name;
77
+		if (is_string($this->_blocking_delete)) {
78
+			throw new EE_Error(sprintf(
79
+				esc_html__(
80
+					"When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
81
+					"event_espresso"
82
+				),
83
+				get_class($this),
84
+				$this_model_name,
85
+				$other_model_name,
86
+				$this->_blocking_delete
87
+			));
88
+		}
89
+	}
90
+
91
+
92
+	/**
93
+	 * Gets the model where this relation is defined.
94
+	 *
95
+	 * @return EEM_Base
96
+	 */
97
+	public function get_this_model()
98
+	{
99
+		return $this->_get_model($this->_this_model_name);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Gets the model which this relation establishes the relation TO (ie,
105
+	 * this relation object was defined on get_this_model(), get_other_model() is the other one)
106
+	 *
107
+	 * @return EEM_Base
108
+	 */
109
+	public function get_other_model()
110
+	{
111
+		return $this->_get_model($this->_other_model_name);
112
+	}
113
+
114
+
115
+	/**
116
+	 * Internally used by get_this_model() and get_other_model()
117
+	 *
118
+	 * @param string $model_name like Event, Question_Group, etc. omit the EEM_
119
+	 * @return EEM_Base
120
+	 * @throws EE_Error
121
+	 * @throws ReflectionException
122
+	 */
123
+	protected function _get_model($model_name)
124
+	{
125
+		$modelInstance = EE_Registry::instance()->load_model($model_name);
126
+		// if the timezone is NOT set on the model but IS set for this relation
127
+		// (which seems really unlikely to ever happen, but whatever)
128
+		// make sure the model timezone is set
129
+		if ($this->_timezone && ! $modelInstance->get_timezone()) {
130
+			$modelInstance->set_timezone($this->_timezone);
131
+		}
132
+		return $modelInstance;
133
+	}
134
+
135
+
136
+	/**
137
+	 * entirely possible that relations may be called from a model and we need to make sure those relations have their
138
+	 * timezone set correctly.
139
+	 *
140
+	 * @param string $timezone timezone to set.
141
+	 */
142
+	public function set_timezone($timezone)
143
+	{
144
+		if (! empty($timezone)) {
145
+			$this->_timezone = $timezone;
146
+		}
147
+	}
148
+
149
+
150
+	/**
151
+	 * @param        $other_table
152
+	 * @param        $other_table_alias
153
+	 * @param        $other_table_column
154
+	 * @param        $this_table_alias
155
+	 * @param        $this_table_join_column
156
+	 * @param string $extra_join_sql
157
+	 * @return string
158
+	 */
159
+	protected function _left_join(
160
+		$other_table,
161
+		$other_table_alias,
162
+		$other_table_column,
163
+		$this_table_alias,
164
+		$this_table_join_column,
165
+		$extra_join_sql = ''
166
+	) {
167
+		return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
168
+	}
169
+
170
+
171
+	/**
172
+	 * Gets all the model objects of type of other model related to $model_object,
173
+	 * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
174
+	 * For both of those child classes, $model_object must be saved so that it has an ID before querying,
175
+	 * otherwise an error will be thrown. Note: by default we disable default_where_conditions
176
+	 * EE_Belongs_To_Relation doesn't need to be saved before querying.
177
+	 *
178
+	 * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
179
+	 * @param array             $query_params                            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
180
+	 * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
181
+	 * @return EE_Base_Class[]
182
+	 * @throws EE_Error
183
+	 * @throws ReflectionException
184
+	 */
185
+	public function get_all_related(
186
+		$model_object_or_id,
187
+		$query_params = array(),
188
+		$values_already_prepared_by_model_object = false
189
+	) {
190
+		if ($values_already_prepared_by_model_object !== false) {
191
+			EE_Error::doing_it_wrong(
192
+				'EE_Model_Relation_Base::get_all_related',
193
+				esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
194
+				'4.8.1'
195
+			);
196
+		}
197
+		$query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
198
+		$query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
199
+															 . "."
200
+															 . $this->get_this_model()->get_primary_key_field()->get_name();
201
+		$model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
202
+		$query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
203
+		return $this->get_other_model()->get_all($query_params);
204
+	}
205
+
206
+
207
+	/**
208
+	 * Alters the $query_params to disable default where conditions, unless otherwise specified
209
+	 *
210
+	 * @param array $query_params
211
+	 * @return array
212
+	 */
213
+	protected function _disable_default_where_conditions_on_query_param($query_params)
214
+	{
215
+		if (! isset($query_params['default_where_conditions'])) {
216
+			$query_params['default_where_conditions'] = 'none';
217
+		}
218
+		return $query_params;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Deletes the related model objects which meet the query parameters. If no
224
+	 * parameters are specified, then all related model objects will be deleted.
225
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
226
+	 * model objects will only be soft-deleted.
227
+	 *
228
+	 * @param EE_Base_Class|int|string $model_object_or_id
229
+	 * @param array                    $query_params
230
+	 * @return int of how many related models got deleted
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function delete_all_related($model_object_or_id, $query_params = array())
235
+	{
236
+		// for each thing we would delete,
237
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
238
+		// determine if it's blocked by anything else before it can be deleted
239
+		$deleted_count = 0;
240
+		foreach ($related_model_objects as $related_model_object) {
241
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
242
+				$related_model_object,
243
+				$model_object_or_id
244
+			);
245
+			/* @var $model_object_or_id EE_Base_Class */
246
+			if (! $delete_is_blocked) {
247
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
248
+				$related_model_object->delete();
249
+				$deleted_count++;
250
+			}
251
+		}
252
+		return $deleted_count;
253
+	}
254
+
255
+
256
+	/**
257
+	 * Deletes the related model objects which meet the query parameters. If no
258
+	 * parameters are specified, then all related model objects will be deleted.
259
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
260
+	 * model objects will only be soft-deleted.
261
+	 *
262
+	 * @param EE_Base_Class|int|string $model_object_or_id
263
+	 * @param array                    $query_params
264
+	 * @return int of how many related models got deleted
265
+	 * @throws EE_Error
266
+	 * @throws ReflectionException
267
+	 */
268
+	public function delete_related_permanently($model_object_or_id, $query_params = array())
269
+	{
270
+		// for each thing we would delete,
271
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
272
+		// determine if it's blocked by anything else before it can be deleted
273
+		$deleted_count = 0;
274
+		foreach ($related_model_objects as $related_model_object) {
275
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
276
+				$related_model_object,
277
+				$model_object_or_id
278
+			);
279
+			/* @var $model_object_or_id EE_Base_Class */
280
+			if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
281
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
282
+				$deleted_count++;
283
+				if (! $delete_is_blocked) {
284
+					$related_model_object->delete_permanently();
285
+				} else {
286
+					// delete is blocked
287
+					// brent and darren, in this case, wanted to just soft delete it then
288
+					$related_model_object->delete();
289
+				}
290
+			} else {
291
+				// its not a soft-deletable thing anyways. do the normal logic.
292
+				if (! $delete_is_blocked) {
293
+					$this->remove_relation_to($model_object_or_id, $related_model_object);
294
+					$related_model_object->delete();
295
+					$deleted_count++;
296
+				}
297
+			}
298
+		}
299
+		return $deleted_count;
300
+	}
301
+
302
+
303
+	/**
304
+	 * this just returns a model_object_id for incoming item that could be an object or id.
305
+	 *
306
+	 * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
307
+	 * @throws EE_Error
308
+	 * @return int
309
+	 */
310
+	protected function _get_model_object_id($model_object_or_id)
311
+	{
312
+		$model_object_id = $model_object_or_id;
313
+		if ($model_object_or_id instanceof EE_Base_Class) {
314
+			$model_object_id = $model_object_or_id->ID();
315
+		}
316
+		if (! $model_object_id) {
317
+			throw new EE_Error(sprintf(
318
+				esc_html__(
319
+					"Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
320
+					"event_espresso"
321
+				),
322
+				$this->get_other_model()->get_this_model_name(),
323
+				$this->get_this_model()->get_this_model_name()
324
+			));
325
+		}
326
+		return $model_object_id;
327
+	}
328
+
329
+
330
+	/**
331
+	 * Gets the SQL string for performing the join between this model and the other model.
332
+	 *
333
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
334
+	 * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
335
+	 *                other_model_primary_table.fk" etc
336
+	 */
337
+	abstract public function get_join_statement($model_relation_chain);
338
+
339
+
340
+	/**
341
+	 * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
342
+	 * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
343
+	 * relationship only allows this model to be related to a single other model of this type)
344
+	 *
345
+	 * @param       $this_obj_or_id
346
+	 * @param       $other_obj_or_id
347
+	 * @param array $extra_join_model_fields_n_values
348
+	 * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
349
+	 *                        $other_obj_or_id)
350
+	 */
351
+	abstract public function add_relation_to(
352
+		$this_obj_or_id,
353
+		$other_obj_or_id,
354
+		$extra_join_model_fields_n_values = array()
355
+	);
356
+
357
+
358
+	/**
359
+	 * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
360
+	 * model objects
361
+	 *
362
+	 * @param       $this_obj_or_id
363
+	 * @param       $other_obj_or_id
364
+	 * @param array $where_query
365
+	 * @return bool
366
+	 */
367
+	abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
368
+
369
+
370
+	/**
371
+	 * Removes ALL relation instances for this relation obj
372
+	 *
373
+	 * @param EE_Base_Class|int $this_obj_or_id
374
+	 * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
375
+	 * @return EE_Base_Class[]
376
+	 * @throws \EE_Error
377
+	 */
378
+	public function remove_relations($this_obj_or_id, $where_query_param = array())
379
+	{
380
+		$related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
381
+		$objs_removed   = array();
382
+		foreach ($related_things as $related_thing) {
383
+			$objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
384
+		}
385
+		return $objs_removed;
386
+	}
387
+
388
+
389
+	/**
390
+	 * If you aren't allowed to delete this model when there are related models across this
391
+	 * relation object, return true. Otherwise, if you can delete this model even though
392
+	 * related objects exist, returns false.
393
+	 *
394
+	 * @return boolean
395
+	 */
396
+	public function block_delete_if_related_models_exist()
397
+	{
398
+		return $this->_blocking_delete;
399
+	}
400
+
401
+
402
+	/**
403
+	 * Gets the error message to show
404
+	 *
405
+	 * @return string
406
+	 */
407
+	public function get_deletion_error_message()
408
+	{
409
+		if ($this->_blocking_delete_error_message) {
410
+			return $this->_blocking_delete_error_message;
411
+		} else {
412 412
 //          return sprintf(__('Cannot delete %1$s when there are related %2$s', "event_espresso"),$this->get_this_model()->item_name(2),$this->get_other_model()->item_name(2));
413
-            return sprintf(
414
-                esc_html__(
415
-                    'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
416
-                    "event_espresso"
417
-                ),
418
-                $this->get_this_model()->item_name(1),
419
-                $this->get_other_model()->item_name(1),
420
-                $this->get_other_model()->item_name(2)
421
-            );
422
-        }
423
-    }
424
-
425
-    /**
426
-     * Returns whatever is set as the nicename for the object.
427
-     *
428
-     * @return string
429
-     */
430
-    public function getSchemaDescription()
431
-    {
432
-        $description = $this instanceof EE_Belongs_To_Relation
433
-            ? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
434
-            : esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
435
-        return sprintf(
436
-            $description,
437
-            $this->get_other_model()->get_this_model_name(),
438
-            $this->get_this_model()->get_this_model_name()
439
-        );
440
-    }
441
-
442
-    /**
443
-     * Returns whatever is set as the $_schema_type property for the object.
444
-     * Note: this will automatically add 'null' to the schema if the object is_nullable()
445
-     *
446
-     * @return string|array
447
-     */
448
-    public function getSchemaType()
449
-    {
450
-        return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
451
-    }
452
-
453
-    /**
454
-     * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
455
-     * this method and return the properties for the schema.
456
-     * The reason this is not a property on the class is because there may be filters set on the values for the property
457
-     * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
458
-     *
459
-     * @return array
460
-     */
461
-    public function getSchemaProperties()
462
-    {
463
-        return array();
464
-    }
465
-
466
-    /**
467
-     * If a child class has enum values, they should override this method and provide a simple array
468
-     * of the enum values.
469
-     * The reason this is not a property on the class is because there may be filterable enum values that
470
-     * are set on the instantiated object that could be filtered after construct.
471
-     *
472
-     * @return array
473
-     */
474
-    public function getSchemaEnum()
475
-    {
476
-        return array();
477
-    }
478
-
479
-    /**
480
-     * This returns the value of the $_schema_format property on the object.
481
-     *
482
-     * @return string
483
-     */
484
-    public function getSchemaFormat()
485
-    {
486
-        return array();
487
-    }
488
-
489
-    /**
490
-     * This returns the value of the $_schema_readonly property on the object.
491
-     *
492
-     * @return bool
493
-     */
494
-    public function getSchemaReadonly()
495
-    {
496
-        return true;
497
-    }
498
-
499
-    /**
500
-     * This returns elements used to represent this field in the json schema.
501
-     *
502
-     * @link http://json-schema.org/
503
-     * @return array
504
-     */
505
-    public function getSchema()
506
-    {
507
-        $schema = array(
508
-            'description' => $this->getSchemaDescription(),
509
-            'type' => $this->getSchemaType(),
510
-            'relation' => true,
511
-            'relation_type' => get_class($this),
512
-            'readonly' => $this->getSchemaReadonly()
513
-        );
514
-
515
-        if ($this instanceof EE_HABTM_Relation) {
516
-            $schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
517
-        }
518
-
519
-        if ($this->getSchemaType() === 'array') {
520
-            $schema['items'] = array(
521
-                'type' => 'object'
522
-            );
523
-        }
524
-
525
-        return $schema;
526
-    }
413
+			return sprintf(
414
+				esc_html__(
415
+					'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
416
+					"event_espresso"
417
+				),
418
+				$this->get_this_model()->item_name(1),
419
+				$this->get_other_model()->item_name(1),
420
+				$this->get_other_model()->item_name(2)
421
+			);
422
+		}
423
+	}
424
+
425
+	/**
426
+	 * Returns whatever is set as the nicename for the object.
427
+	 *
428
+	 * @return string
429
+	 */
430
+	public function getSchemaDescription()
431
+	{
432
+		$description = $this instanceof EE_Belongs_To_Relation
433
+			? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
434
+			: esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
435
+		return sprintf(
436
+			$description,
437
+			$this->get_other_model()->get_this_model_name(),
438
+			$this->get_this_model()->get_this_model_name()
439
+		);
440
+	}
441
+
442
+	/**
443
+	 * Returns whatever is set as the $_schema_type property for the object.
444
+	 * Note: this will automatically add 'null' to the schema if the object is_nullable()
445
+	 *
446
+	 * @return string|array
447
+	 */
448
+	public function getSchemaType()
449
+	{
450
+		return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
451
+	}
452
+
453
+	/**
454
+	 * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
455
+	 * this method and return the properties for the schema.
456
+	 * The reason this is not a property on the class is because there may be filters set on the values for the property
457
+	 * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
458
+	 *
459
+	 * @return array
460
+	 */
461
+	public function getSchemaProperties()
462
+	{
463
+		return array();
464
+	}
465
+
466
+	/**
467
+	 * If a child class has enum values, they should override this method and provide a simple array
468
+	 * of the enum values.
469
+	 * The reason this is not a property on the class is because there may be filterable enum values that
470
+	 * are set on the instantiated object that could be filtered after construct.
471
+	 *
472
+	 * @return array
473
+	 */
474
+	public function getSchemaEnum()
475
+	{
476
+		return array();
477
+	}
478
+
479
+	/**
480
+	 * This returns the value of the $_schema_format property on the object.
481
+	 *
482
+	 * @return string
483
+	 */
484
+	public function getSchemaFormat()
485
+	{
486
+		return array();
487
+	}
488
+
489
+	/**
490
+	 * This returns the value of the $_schema_readonly property on the object.
491
+	 *
492
+	 * @return bool
493
+	 */
494
+	public function getSchemaReadonly()
495
+	{
496
+		return true;
497
+	}
498
+
499
+	/**
500
+	 * This returns elements used to represent this field in the json schema.
501
+	 *
502
+	 * @link http://json-schema.org/
503
+	 * @return array
504
+	 */
505
+	public function getSchema()
506
+	{
507
+		$schema = array(
508
+			'description' => $this->getSchemaDescription(),
509
+			'type' => $this->getSchemaType(),
510
+			'relation' => true,
511
+			'relation_type' => get_class($this),
512
+			'readonly' => $this->getSchemaReadonly()
513
+		);
514
+
515
+		if ($this instanceof EE_HABTM_Relation) {
516
+			$schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
517
+		}
518
+
519
+		if ($this->getSchemaType() === 'array') {
520
+			$schema['items'] = array(
521
+				'type' => 'object'
522
+			);
523
+		}
524
+
525
+		return $schema;
526
+	}
527 527
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
      */
142 142
     public function set_timezone($timezone)
143 143
     {
144
-        if (! empty($timezone)) {
144
+        if ( ! empty($timezone)) {
145 145
             $this->_timezone = $timezone;
146 146
         }
147 147
     }
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
         $this_table_join_column,
165 165
         $extra_join_sql = ''
166 166
     ) {
167
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
167
+        return " LEFT JOIN ".$other_table." AS ".$other_table_alias." ON ".$other_table_alias.".".$other_table_column."=".$this_table_alias.".".$this_table_join_column.($extra_join_sql ? " AND $extra_join_sql" : '');
168 168
     }
169 169
 
170 170
 
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
                                                              . "."
200 200
                                                              . $this->get_this_model()->get_primary_key_field()->get_name();
201 201
         $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
202
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
202
+        $query_params[0][$query_param_where_this_model_pk] = $model_object_id;
203 203
         return $this->get_other_model()->get_all($query_params);
204 204
     }
205 205
 
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
      */
213 213
     protected function _disable_default_where_conditions_on_query_param($query_params)
214 214
     {
215
-        if (! isset($query_params['default_where_conditions'])) {
215
+        if ( ! isset($query_params['default_where_conditions'])) {
216 216
             $query_params['default_where_conditions'] = 'none';
217 217
         }
218 218
         return $query_params;
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
                 $model_object_or_id
244 244
             );
245 245
             /* @var $model_object_or_id EE_Base_Class */
246
-            if (! $delete_is_blocked) {
246
+            if ( ! $delete_is_blocked) {
247 247
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
248 248
                 $related_model_object->delete();
249 249
                 $deleted_count++;
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
             if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
281 281
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
282 282
                 $deleted_count++;
283
-                if (! $delete_is_blocked) {
283
+                if ( ! $delete_is_blocked) {
284 284
                     $related_model_object->delete_permanently();
285 285
                 } else {
286 286
                     // delete is blocked
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
                 }
290 290
             } else {
291 291
                 // its not a soft-deletable thing anyways. do the normal logic.
292
-                if (! $delete_is_blocked) {
292
+                if ( ! $delete_is_blocked) {
293 293
                     $this->remove_relation_to($model_object_or_id, $related_model_object);
294 294
                     $related_model_object->delete();
295 295
                     $deleted_count++;
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
         if ($model_object_or_id instanceof EE_Base_Class) {
314 314
             $model_object_id = $model_object_or_id->ID();
315 315
         }
316
-        if (! $model_object_id) {
316
+        if ( ! $model_object_id) {
317 317
             throw new EE_Error(sprintf(
318 318
                 esc_html__(
319 319
                     "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
Please login to merge, or discard this patch.
core/services/helpers/datetime/PhpCompatLessFiveSixHelper.php 1 patch
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -19,222 +19,222 @@
 block discarded – undo
19 19
 class PhpCompatLessFiveSixHelper extends AbstractHelper
20 20
 {
21 21
 
22
-    /**
23
-     * PhpCompatLessFiveSixHelper constructor.
24
-     *
25
-     * @throws DomainException
26
-     */
27
-    public function __construct()
28
-    {
29
-        if (PHP_VERSION_ID >= 50600) {
30
-            throw new DomainException(
31
-                sprintf(
32
-                    esc_html__(
33
-                        'The %1$s is only usable on php versions less than 5.6.  You\'ll want to use %2$s instead.',
34
-                        'event_espresso'
35
-                    ),
36
-                    __CLASS__,
37
-                    'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper'
38
-                )
39
-            );
40
-        }
41
-        parent::__construct();
42
-    }
22
+	/**
23
+	 * PhpCompatLessFiveSixHelper constructor.
24
+	 *
25
+	 * @throws DomainException
26
+	 */
27
+	public function __construct()
28
+	{
29
+		if (PHP_VERSION_ID >= 50600) {
30
+			throw new DomainException(
31
+				sprintf(
32
+					esc_html__(
33
+						'The %1$s is only usable on php versions less than 5.6.  You\'ll want to use %2$s instead.',
34
+						'event_espresso'
35
+					),
36
+					__CLASS__,
37
+					'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper'
38
+				)
39
+			);
40
+		}
41
+		parent::__construct();
42
+	}
43 43
 
44
-    /**
45
-     * Returns a timezone string for the provided gmt_offset.
46
-     *
47
-     * @param float|string $gmt_offset
48
-     * @return string
49
-     * @throws EE_Error
50
-     */
51
-    public function getTimezoneStringFromGmtOffset($gmt_offset = '')
52
-    {
53
-        $gmt_offset_or_timezone_string = $this->sanitizeInitialIncomingGmtOffsetForGettingTimezoneString($gmt_offset);
54
-        if (is_string($gmt_offset_or_timezone_string)) {
55
-            return $gmt_offset_or_timezone_string;
56
-        }
57
-        // well we know its a float, so let's roll with it.
58
-        $gmt_offset = $gmt_offset_or_timezone_string;
59
-        // convert GMT offset to seconds
60
-        $gmt_offset *= HOUR_IN_SECONDS;
61
-        // although we don't know the TZ abbreviation, we know the UTC offset
62
-        $timezone_string = timezone_name_from_abbr(null, $gmt_offset);
63
-        // only use this timezone_string IF it's current offset matches the given offset
64
-        if (! empty($timezone_string)) {
65
-            $offset = null;
66
-            try {
67
-                $offset = $this->getTimezoneOffset(new DateTimeZone($timezone_string));
68
-                if ($offset !== $gmt_offset) {
69
-                    $timezone_string = false;
70
-                }
71
-            } catch (Exception $e) {
72
-                $timezone_string = false;
73
-            }
74
-        }
75
-        // better have a valid timezone string by now, but if not, sigh... loop thru  the timezone_abbreviations_list()
76
-        // ...
77
-        $timezone_string = $timezone_string !== false
78
-            ? $timezone_string
79
-            : $this->getTimezoneStringFromAbbreviationsList($gmt_offset);
80
-        return $timezone_string;
81
-    }
44
+	/**
45
+	 * Returns a timezone string for the provided gmt_offset.
46
+	 *
47
+	 * @param float|string $gmt_offset
48
+	 * @return string
49
+	 * @throws EE_Error
50
+	 */
51
+	public function getTimezoneStringFromGmtOffset($gmt_offset = '')
52
+	{
53
+		$gmt_offset_or_timezone_string = $this->sanitizeInitialIncomingGmtOffsetForGettingTimezoneString($gmt_offset);
54
+		if (is_string($gmt_offset_or_timezone_string)) {
55
+			return $gmt_offset_or_timezone_string;
56
+		}
57
+		// well we know its a float, so let's roll with it.
58
+		$gmt_offset = $gmt_offset_or_timezone_string;
59
+		// convert GMT offset to seconds
60
+		$gmt_offset *= HOUR_IN_SECONDS;
61
+		// although we don't know the TZ abbreviation, we know the UTC offset
62
+		$timezone_string = timezone_name_from_abbr(null, $gmt_offset);
63
+		// only use this timezone_string IF it's current offset matches the given offset
64
+		if (! empty($timezone_string)) {
65
+			$offset = null;
66
+			try {
67
+				$offset = $this->getTimezoneOffset(new DateTimeZone($timezone_string));
68
+				if ($offset !== $gmt_offset) {
69
+					$timezone_string = false;
70
+				}
71
+			} catch (Exception $e) {
72
+				$timezone_string = false;
73
+			}
74
+		}
75
+		// better have a valid timezone string by now, but if not, sigh... loop thru  the timezone_abbreviations_list()
76
+		// ...
77
+		$timezone_string = $timezone_string !== false
78
+			? $timezone_string
79
+			: $this->getTimezoneStringFromAbbreviationsList($gmt_offset);
80
+		return $timezone_string;
81
+	}
82 82
 
83 83
 
84
-    /**
85
-     * @param int  $gmt_offset
86
-     * @param bool $coerce If true, we attempt to coerce with our adjustment table
87
-     * @see self::adjustInvalidGmtOffset
88
-     * @return string
89
-     * @throws EE_Error
90
-     */
91
-    protected function getTimezoneStringFromAbbreviationsList($gmt_offset = 0, $coerce = true)
92
-    {
93
-        $gmt_offset = (int) $gmt_offset;
94
-        /** @var array[] $abbreviations */
95
-        $abbreviations = DateTimeZone::listAbbreviations();
96
-        foreach ($abbreviations as $abbreviation) {
97
-            foreach ($abbreviation as $timezone) {
98
-                if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
99
-                    try {
100
-                        $offset = $this->getTimezoneOffset(new DateTimeZone($timezone['timezone_id']));
101
-                        if ($offset !== $gmt_offset) {
102
-                            continue;
103
-                        }
104
-                        return $timezone['timezone_id'];
105
-                    } catch (Exception $e) {
106
-                        continue;
107
-                    }
108
-                }
109
-            }
110
-        }
111
-        // if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
112
-        if ($coerce === true) {
113
-            $timezone_string = $this->getTimezoneStringFromAbbreviationsList(
114
-                $this->adjustInvalidGmtOffsets($gmt_offset),
115
-                false
116
-            );
117
-            if ($timezone_string) {
118
-                return $timezone_string;
119
-            }
120
-        }
121
-        throw new EE_Error(
122
-            sprintf(
123
-                esc_html__(
124
-                    'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
125
-                    'event_espresso'
126
-                ),
127
-                $gmt_offset / HOUR_IN_SECONDS,
128
-                '<a href="http://www.php.net/manual/en/timezones.php">',
129
-                '</a>'
130
-            )
131
-        );
132
-    }
84
+	/**
85
+	 * @param int  $gmt_offset
86
+	 * @param bool $coerce If true, we attempt to coerce with our adjustment table
87
+	 * @see self::adjustInvalidGmtOffset
88
+	 * @return string
89
+	 * @throws EE_Error
90
+	 */
91
+	protected function getTimezoneStringFromAbbreviationsList($gmt_offset = 0, $coerce = true)
92
+	{
93
+		$gmt_offset = (int) $gmt_offset;
94
+		/** @var array[] $abbreviations */
95
+		$abbreviations = DateTimeZone::listAbbreviations();
96
+		foreach ($abbreviations as $abbreviation) {
97
+			foreach ($abbreviation as $timezone) {
98
+				if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
99
+					try {
100
+						$offset = $this->getTimezoneOffset(new DateTimeZone($timezone['timezone_id']));
101
+						if ($offset !== $gmt_offset) {
102
+							continue;
103
+						}
104
+						return $timezone['timezone_id'];
105
+					} catch (Exception $e) {
106
+						continue;
107
+					}
108
+				}
109
+			}
110
+		}
111
+		// if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
112
+		if ($coerce === true) {
113
+			$timezone_string = $this->getTimezoneStringFromAbbreviationsList(
114
+				$this->adjustInvalidGmtOffsets($gmt_offset),
115
+				false
116
+			);
117
+			if ($timezone_string) {
118
+				return $timezone_string;
119
+			}
120
+		}
121
+		throw new EE_Error(
122
+			sprintf(
123
+				esc_html__(
124
+					'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
125
+					'event_espresso'
126
+				),
127
+				$gmt_offset / HOUR_IN_SECONDS,
128
+				'<a href="http://www.php.net/manual/en/timezones.php">',
129
+				'</a>'
130
+			)
131
+		);
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * Depending on PHP version,
137
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
138
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
139
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
140
-     *
141
-     * @param int $gmt_offset
142
-     * @return int
143
-     */
144
-    public function adjustInvalidGmtOffsets($gmt_offset = 0)
145
-    {
146
-        // make sure $gmt_offset is int
147
-        $gmt_offset = (int) $gmt_offset;
148
-        switch ($gmt_offset) {
149
-            // -12
150
-            case -43200:
151
-                $gmt_offset = -39600;
152
-                break;
153
-            // -11.5
154
-            case -41400:
155
-                $gmt_offset = -39600;
156
-                break;
157
-            // -10.5
158
-            case -37800:
159
-                $gmt_offset = -39600;
160
-                break;
161
-            // -8.5
162
-            case -30600:
163
-                $gmt_offset = -28800;
164
-                break;
165
-            // -7.5
166
-            case -27000:
167
-                $gmt_offset = -25200;
168
-                break;
169
-            // -6.5
170
-            case -23400:
171
-                $gmt_offset = -21600;
172
-                break;
173
-            // -5.5
174
-            case -19800:
175
-                $gmt_offset = -18000;
176
-                break;
177
-            // -4.5
178
-            case -16200:
179
-                $gmt_offset = -14400;
180
-                break;
181
-            // -3.5
182
-            case -12600:
183
-                $gmt_offset = -10800;
184
-                break;
185
-            // -2.5
186
-            case -9000:
187
-                $gmt_offset = -7200;
188
-                break;
189
-            // -1.5
190
-            case -5400:
191
-                $gmt_offset = -3600;
192
-                break;
193
-            // -0.5
194
-            case -1800:
195
-                $gmt_offset = 0;
196
-                break;
197
-            // .5
198
-            case 1800:
199
-                $gmt_offset = 3600;
200
-                break;
201
-            // 1.5
202
-            case 5400:
203
-                $gmt_offset = 7200;
204
-                break;
205
-            // 2.5
206
-            case 9000:
207
-                $gmt_offset = 10800;
208
-                break;
209
-            // 3.5
210
-            case 12600:
211
-                $gmt_offset = 14400;
212
-                break;
213
-            // 7.5
214
-            case 27000:
215
-                $gmt_offset = 28800;
216
-                break;
217
-            // 8.5
218
-            case 30600:
219
-                $gmt_offset = 31500;
220
-                break;
221
-            // 10.5
222
-            case 37800:
223
-                $gmt_offset = 39600;
224
-                break;
225
-            // 11.5
226
-            case 41400:
227
-                $gmt_offset = 43200;
228
-                break;
229
-            // 12.75
230
-            case 45900:
231
-                $gmt_offset = 46800;
232
-                break;
233
-            // 13.75
234
-            case 49500:
235
-                $gmt_offset = 50400;
236
-                break;
237
-        }
238
-        return $gmt_offset;
239
-    }
135
+	/**
136
+	 * Depending on PHP version,
137
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
138
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
139
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
140
+	 *
141
+	 * @param int $gmt_offset
142
+	 * @return int
143
+	 */
144
+	public function adjustInvalidGmtOffsets($gmt_offset = 0)
145
+	{
146
+		// make sure $gmt_offset is int
147
+		$gmt_offset = (int) $gmt_offset;
148
+		switch ($gmt_offset) {
149
+			// -12
150
+			case -43200:
151
+				$gmt_offset = -39600;
152
+				break;
153
+			// -11.5
154
+			case -41400:
155
+				$gmt_offset = -39600;
156
+				break;
157
+			// -10.5
158
+			case -37800:
159
+				$gmt_offset = -39600;
160
+				break;
161
+			// -8.5
162
+			case -30600:
163
+				$gmt_offset = -28800;
164
+				break;
165
+			// -7.5
166
+			case -27000:
167
+				$gmt_offset = -25200;
168
+				break;
169
+			// -6.5
170
+			case -23400:
171
+				$gmt_offset = -21600;
172
+				break;
173
+			// -5.5
174
+			case -19800:
175
+				$gmt_offset = -18000;
176
+				break;
177
+			// -4.5
178
+			case -16200:
179
+				$gmt_offset = -14400;
180
+				break;
181
+			// -3.5
182
+			case -12600:
183
+				$gmt_offset = -10800;
184
+				break;
185
+			// -2.5
186
+			case -9000:
187
+				$gmt_offset = -7200;
188
+				break;
189
+			// -1.5
190
+			case -5400:
191
+				$gmt_offset = -3600;
192
+				break;
193
+			// -0.5
194
+			case -1800:
195
+				$gmt_offset = 0;
196
+				break;
197
+			// .5
198
+			case 1800:
199
+				$gmt_offset = 3600;
200
+				break;
201
+			// 1.5
202
+			case 5400:
203
+				$gmt_offset = 7200;
204
+				break;
205
+			// 2.5
206
+			case 9000:
207
+				$gmt_offset = 10800;
208
+				break;
209
+			// 3.5
210
+			case 12600:
211
+				$gmt_offset = 14400;
212
+				break;
213
+			// 7.5
214
+			case 27000:
215
+				$gmt_offset = 28800;
216
+				break;
217
+			// 8.5
218
+			case 30600:
219
+				$gmt_offset = 31500;
220
+				break;
221
+			// 10.5
222
+			case 37800:
223
+				$gmt_offset = 39600;
224
+				break;
225
+			// 11.5
226
+			case 41400:
227
+				$gmt_offset = 43200;
228
+				break;
229
+			// 12.75
230
+			case 45900:
231
+				$gmt_offset = 46800;
232
+				break;
233
+			// 13.75
234
+			case 49500:
235
+				$gmt_offset = 50400;
236
+				break;
237
+		}
238
+		return $gmt_offset;
239
+	}
240 240
 }
Please login to merge, or discard this patch.
core/services/helpers/datetime/HelperInterface.php 1 patch
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -16,95 +16,95 @@
 block discarded – undo
16 16
 interface HelperInterface
17 17
 {
18 18
 
19
-    /**
20
-     * Ensures that a valid timezone string is returned.
21
-     *
22
-     * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
23
-     *                                 settings (or derive from set UTC offset).
24
-     * @param bool   $throw_error
25
-     * @return string
26
-     */
27
-    public function getValidTimezoneString($timezone_string = '', $throw_error = false);
28
-
29
-
30
-    /**
31
-     * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
32
-     *
33
-     * @param string $timezone_string
34
-     * @param bool   $throw_error
35
-     * @return bool
36
-     */
37
-    public function validateTimezone($timezone_string, $throw_error = true);
38
-
39
-
40
-    /**
41
-     * Returns a timezone string for the provided gmt_offset.
42
-     * @param float|string $gmt_offset
43
-     * @return string
44
-     */
45
-    public function getTimezoneStringFromGmtOffset($gmt_offset = '');
46
-
47
-
48
-    /**
49
-     * Gets the site's GMT offset based on either the timezone string
50
-     * (in which case the gmt offset will vary depending on the location's
51
-     * observance of daylight savings time) or the gmt_offset wp option
52
-     *
53
-     * @return int  seconds offset
54
-     */
55
-    public function getSiteTimezoneGmtOffset();
56
-
57
-
58
-    /**
59
-     * Get timezone transitions
60
-     * @param DateTimeZone $date_time_zone
61
-     * @param int|null     $time
62
-     * @param bool         $first_only
63
-     * @return array
64
-     */
65
-    public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true);
66
-
67
-
68
-    /**
69
-     * Get Timezone offset for given timezone object
70
-     * @param DateTimeZone $date_time_zone
71
-     * @param null|int         $time
72
-     * @return int
73
-     */
74
-    public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null);
75
-
76
-
77
-    /**
78
-     * Provide a timezone select input
79
-     * @param string $timezone_string
80
-     * @return string
81
-     */
82
-    public function timezoneSelectInput($timezone_string = '');
83
-
84
-
85
-    /**
86
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
87
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
88
-     * the site is used.
89
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
90
-     * computed timestamp (i.e. date_i18n() )
91
-     *
92
-     * @param int    $unix_timestamp    if 0, then time() will be used.
93
-     * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
94
-     *                                site will be used.
95
-     * @return int      unix_timestamp value with the offset applied for the given timezone.
96
-     */
97
-    public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '');
98
-
99
-
100
-    /**
101
-     * Depending on PHP version,
102
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
103
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
104
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
105
-     *
106
-     * @param int $gmt_offset
107
-     * @return int
108
-     */
109
-    public function adjustInvalidGmtOffsets($gmt_offset);
19
+	/**
20
+	 * Ensures that a valid timezone string is returned.
21
+	 *
22
+	 * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
23
+	 *                                 settings (or derive from set UTC offset).
24
+	 * @param bool   $throw_error
25
+	 * @return string
26
+	 */
27
+	public function getValidTimezoneString($timezone_string = '', $throw_error = false);
28
+
29
+
30
+	/**
31
+	 * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
32
+	 *
33
+	 * @param string $timezone_string
34
+	 * @param bool   $throw_error
35
+	 * @return bool
36
+	 */
37
+	public function validateTimezone($timezone_string, $throw_error = true);
38
+
39
+
40
+	/**
41
+	 * Returns a timezone string for the provided gmt_offset.
42
+	 * @param float|string $gmt_offset
43
+	 * @return string
44
+	 */
45
+	public function getTimezoneStringFromGmtOffset($gmt_offset = '');
46
+
47
+
48
+	/**
49
+	 * Gets the site's GMT offset based on either the timezone string
50
+	 * (in which case the gmt offset will vary depending on the location's
51
+	 * observance of daylight savings time) or the gmt_offset wp option
52
+	 *
53
+	 * @return int  seconds offset
54
+	 */
55
+	public function getSiteTimezoneGmtOffset();
56
+
57
+
58
+	/**
59
+	 * Get timezone transitions
60
+	 * @param DateTimeZone $date_time_zone
61
+	 * @param int|null     $time
62
+	 * @param bool         $first_only
63
+	 * @return array
64
+	 */
65
+	public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true);
66
+
67
+
68
+	/**
69
+	 * Get Timezone offset for given timezone object
70
+	 * @param DateTimeZone $date_time_zone
71
+	 * @param null|int         $time
72
+	 * @return int
73
+	 */
74
+	public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null);
75
+
76
+
77
+	/**
78
+	 * Provide a timezone select input
79
+	 * @param string $timezone_string
80
+	 * @return string
81
+	 */
82
+	public function timezoneSelectInput($timezone_string = '');
83
+
84
+
85
+	/**
86
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
87
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
88
+	 * the site is used.
89
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
90
+	 * computed timestamp (i.e. date_i18n() )
91
+	 *
92
+	 * @param int    $unix_timestamp    if 0, then time() will be used.
93
+	 * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
94
+	 *                                site will be used.
95
+	 * @return int      unix_timestamp value with the offset applied for the given timezone.
96
+	 */
97
+	public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '');
98
+
99
+
100
+	/**
101
+	 * Depending on PHP version,
102
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
103
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
104
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
105
+	 *
106
+	 * @param int $gmt_offset
107
+	 * @return int
108
+	 */
109
+	public function adjustInvalidGmtOffsets($gmt_offset);
110 110
 }
Please login to merge, or discard this patch.
core/services/helpers/datetime/PhpCompatGreaterFiveSixHelper.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -9,92 +9,92 @@
 block discarded – undo
9 9
 
10 10
 class PhpCompatGreaterFiveSixHelper extends AbstractHelper
11 11
 {
12
-    /**
13
-     * PhpCompatLessFiveSixHelper constructor.
14
-     *
15
-     * @throws DomainException
16
-     */
17
-    public function __construct()
18
-    {
19
-        if (PHP_VERSION_ID < 50600) {
20
-            throw new DomainException(
21
-                sprintf(
22
-                    esc_html__(
23
-                        'The %1$s is only usable on php versions greater than 5.6.  You\'ll want to use %2$s instead.',
24
-                        'event_espresso'
25
-                    ),
26
-                    __CLASS__,
27
-                    'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
28
-                )
29
-            );
30
-        }
31
-        parent::__construct();
32
-    }
12
+	/**
13
+	 * PhpCompatLessFiveSixHelper constructor.
14
+	 *
15
+	 * @throws DomainException
16
+	 */
17
+	public function __construct()
18
+	{
19
+		if (PHP_VERSION_ID < 50600) {
20
+			throw new DomainException(
21
+				sprintf(
22
+					esc_html__(
23
+						'The %1$s is only usable on php versions greater than 5.6.  You\'ll want to use %2$s instead.',
24
+						'event_espresso'
25
+					),
26
+					__CLASS__,
27
+					'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
28
+				)
29
+			);
30
+		}
31
+		parent::__construct();
32
+	}
33 33
 
34
-    /**
35
-     * Returns a timezone string for the provided gmt_offset.
36
-     * This is a valid timezone string that can be sent into DateTimeZone
37
-     *
38
-     * @param float|string $gmt_offset
39
-     * @return string
40
-     */
41
-    public function getTimezoneStringFromGmtOffset($gmt_offset = '')
42
-    {
43
-        $gmt_offset_or_timezone_string = $this->sanitizeInitialIncomingGmtOffsetForGettingTimezoneString($gmt_offset);
44
-        return is_float($gmt_offset_or_timezone_string)
45
-            ? $this->convertWpGmtOffsetForDateTimeZone($gmt_offset_or_timezone_string)
46
-            : $gmt_offset_or_timezone_string;
47
-    }
34
+	/**
35
+	 * Returns a timezone string for the provided gmt_offset.
36
+	 * This is a valid timezone string that can be sent into DateTimeZone
37
+	 *
38
+	 * @param float|string $gmt_offset
39
+	 * @return string
40
+	 */
41
+	public function getTimezoneStringFromGmtOffset($gmt_offset = '')
42
+	{
43
+		$gmt_offset_or_timezone_string = $this->sanitizeInitialIncomingGmtOffsetForGettingTimezoneString($gmt_offset);
44
+		return is_float($gmt_offset_or_timezone_string)
45
+			? $this->convertWpGmtOffsetForDateTimeZone($gmt_offset_or_timezone_string)
46
+			: $gmt_offset_or_timezone_string;
47
+	}
48 48
 
49 49
 
50 50
 
51
-    /**
52
-     * Returns a formatted offset for use as an argument for constructing DateTimeZone
53
-     * @param float $gmt_offset This should be a float representing the gmt_offset.
54
-     * @return string
55
-     */
56
-    protected function convertWpGmtOffsetForDateTimeZone($gmt_offset)
57
-    {
58
-        $gmt_offset = (float) $gmt_offset;
59
-        $is_negative = $gmt_offset < 0;
60
-        $gmt_offset *= 100;
61
-        $gmt_offset = absint($gmt_offset);
62
-        // negative and need zero padding?
63
-        if (strlen($gmt_offset) < 4) {
64
-            $gmt_offset = str_pad($gmt_offset, 4, '0', STR_PAD_LEFT);
65
-        }
66
-        $gmt_offset = $this->convertToTimeFraction($gmt_offset);
67
-        // return something like -1300, -0200 or +1300, +0200
68
-        return $is_negative ? '-' . $gmt_offset : '+' . $gmt_offset;
69
-    }
51
+	/**
52
+	 * Returns a formatted offset for use as an argument for constructing DateTimeZone
53
+	 * @param float $gmt_offset This should be a float representing the gmt_offset.
54
+	 * @return string
55
+	 */
56
+	protected function convertWpGmtOffsetForDateTimeZone($gmt_offset)
57
+	{
58
+		$gmt_offset = (float) $gmt_offset;
59
+		$is_negative = $gmt_offset < 0;
60
+		$gmt_offset *= 100;
61
+		$gmt_offset = absint($gmt_offset);
62
+		// negative and need zero padding?
63
+		if (strlen($gmt_offset) < 4) {
64
+			$gmt_offset = str_pad($gmt_offset, 4, '0', STR_PAD_LEFT);
65
+		}
66
+		$gmt_offset = $this->convertToTimeFraction($gmt_offset);
67
+		// return something like -1300, -0200 or +1300, +0200
68
+		return $is_negative ? '-' . $gmt_offset : '+' . $gmt_offset;
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * Converts something like `1550` to `1530` or `0275` to `0245`
74
-     * Incoming offset should be a positive value, this will mutate negative values. Be aware!
75
-     * @param int $offset
76
-     * @return mixed
77
-     */
78
-    protected function convertToTimeFraction($offset)
79
-    {
80
-        $first_part = substr($offset, 0, 2);
81
-        $second_part = substr($offset, 2, 2);
82
-        $second_part = str_replace(array('25', '50', '75'), array('15', '30', '45'), $second_part);
83
-        return $first_part . $second_part;
84
-    }
72
+	/**
73
+	 * Converts something like `1550` to `1530` or `0275` to `0245`
74
+	 * Incoming offset should be a positive value, this will mutate negative values. Be aware!
75
+	 * @param int $offset
76
+	 * @return mixed
77
+	 */
78
+	protected function convertToTimeFraction($offset)
79
+	{
80
+		$first_part = substr($offset, 0, 2);
81
+		$second_part = substr($offset, 2, 2);
82
+		$second_part = str_replace(array('25', '50', '75'), array('15', '30', '45'), $second_part);
83
+		return $first_part . $second_part;
84
+	}
85 85
 
86 86
 
87
-    /**
88
-     * Get Timezone offset for given timezone object
89
-     *
90
-     * @param DateTimeZone $date_time_zone
91
-     * @param null|int     $time
92
-     * @return int
93
-     */
94
-    public function getTimezoneOffset(DateTimezone $date_time_zone, $time = null)
95
-    {
96
-        $time = is_int($time) || $time === null ? $time : (int) strtotime($time);
97
-        $time = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
98
-        return $date_time_zone->getOffset(new DateTime('@' . $time));
99
-    }
87
+	/**
88
+	 * Get Timezone offset for given timezone object
89
+	 *
90
+	 * @param DateTimeZone $date_time_zone
91
+	 * @param null|int     $time
92
+	 * @return int
93
+	 */
94
+	public function getTimezoneOffset(DateTimezone $date_time_zone, $time = null)
95
+	{
96
+		$time = is_int($time) || $time === null ? $time : (int) strtotime($time);
97
+		$time = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
98
+		return $date_time_zone->getOffset(new DateTime('@' . $time));
99
+	}
100 100
 }
Please login to merge, or discard this patch.
core/services/helpers/datetime/AbstractHelper.php 2 patches
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -11,195 +11,195 @@  discard block
 block discarded – undo
11 11
 
12 12
 abstract class AbstractHelper implements HelperInterface
13 13
 {
14
-    /**
15
-     * @var string
16
-     */
17
-    private $default_timezone_string = '';
18
-
19
-
20
-    /**
21
-     * AbstractHelper constructor.
22
-     */
23
-    public function __construct()
24
-    {
25
-        add_action('update_option_timezone_string', [$this, 'updateDefaultTimezoneString'], 10, 2);
26
-    }
27
-    /**
28
-     * AbstractHelper destructor.
29
-     */
30
-    public function __destruct()
31
-    {
32
-        remove_action('update_option_timezone_string', [$this, 'updateDefaultTimezoneString']);
33
-    }
34
-
35
-
36
-
37
-
38
-    /**
39
-     * Ensures that a valid timezone string is returned.
40
-     *
41
-     * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
42
-     *                                 settings (or derive from set UTC offset).
43
-     * @param bool   $throw_error
44
-     * @return string
45
-     * @throws EE_Error
46
-     */
47
-    public function getValidTimezoneString($timezone_string = '', $throw_error = false)
48
-    {
49
-        // if a valid TZ is supplied, then just use that, but don't throw errors if it's invalid
50
-        if (! empty($timezone_string) && $this->validateTimezone($timezone_string, $throw_error)) {
51
-            return $timezone_string;
52
-        }
53
-        // cache whatever gets set as the site default
54
-        // no default set yet? then let's get to it!
55
-        if ($this->default_timezone_string === '') {
56
-            // ignore the incoming TZ string because we already know it's invalid
57
-            // and just pull the default set for the site
58
-            $timezone_string = (string) get_option('timezone_string');
59
-            // if the site admin has not set a valid default,
60
-            // then derive the TZ from the UTC offset (and hope that that is set)
61
-            $timezone_string = ! empty($timezone_string)
62
-                ? $timezone_string
63
-                : $this->getTimezoneStringFromGmtOffset();
64
-            // make sure it's all good (and this time blow things up if no TZ can be determined)
65
-            $this->validateTimezone($timezone_string);
66
-            // cache the default so that we don't do this a Brazilian times
67
-            $this->default_timezone_string = $timezone_string;
68
-        }
69
-        return $this->default_timezone_string;
70
-    }
71
-
72
-
73
-    public function resetDefaultTimezoneString()
74
-    {
75
-        $this->default_timezone_string = '';
76
-    }
77
-
78
-
79
-    /**
80
-     * @param $old_value
81
-     * @param $value
82
-     * @throws EE_Error
83
-     * @since   $VID:$
84
-     */
85
-    public function updateDefaultTimezoneString($old_value, $value)
86
-    {
87
-        if ($value && $value !== $old_value && $value !== $this->default_timezone_string) {
88
-            $this->resetDefaultTimezoneString();
89
-            $this->getValidTimezoneString($value);
90
-        }
91
-    }
92
-
93
-    /**
94
-     * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
95
-     *
96
-     * @param string $timezone_string
97
-     * @param bool   $throw_error
98
-     * @return bool
99
-     * @throws EE_Error
100
-     */
101
-    public function validateTimezone($timezone_string, $throw_error = true)
102
-    {
103
-        // easiest way to test a timezone string is just see if it throws an error when you try to create a
104
-        // DateTimeZone object with it
105
-        try {
106
-            new DateTimeZone($timezone_string);
107
-        } catch (Exception $e) {
108
-            // sometimes we take exception to exceptions
109
-            if (! $throw_error) {
110
-                return false;
111
-            }
112
-            throw new EE_Error(
113
-                sprintf(
114
-                    esc_html__(
115
-                        'The timezone given (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
116
-                        'event_espresso'
117
-                    ),
118
-                    $timezone_string,
119
-                    '<a href="http://www.php.net/manual/en/timezones.php">',
120
-                    '</a>'
121
-                )
122
-            );
123
-        }
124
-        return true;
125
-    }
126
-
127
-
128
-    /**
129
-     * Gets the site's GMT offset based on either the timezone string
130
-     * (in which case the gmt offset will vary depending on the location's
131
-     * observance of daylight savings time) or the gmt_offset wp option
132
-     *
133
-     * @return int  seconds offset
134
-     */
135
-    public function getSiteTimezoneGmtOffset()
136
-    {
137
-        $timezone_string = (string) get_option('timezone_string');
138
-        if ($timezone_string) {
139
-            try {
140
-                $timezone = new DateTimeZone($timezone_string);
141
-                return $timezone->getOffset(new DateTime()); // in WordPress DateTime defaults to UTC
142
-            } catch (Exception $e) {
143
-            }
144
-        }
145
-        $offset = get_option('gmt_offset');
146
-        return (int) ($offset * HOUR_IN_SECONDS);
147
-    }
148
-
149
-
150
-    /**
151
-     * Get Timezone offset for given timezone object
152
-     *
153
-     * @param DateTimeZone $date_time_zone
154
-     * @param null|int     $time
155
-     * @return int
156
-     * @throws DomainException
157
-     */
158
-    public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null)
159
-    {
160
-        $transition = $this->getTimezoneTransitions($date_time_zone, $time);
161
-        if (! isset($transition['offset'])) {
162
-            throw new DomainException(
163
-                sprintf(
164
-                    esc_html__('An invalid timezone transition was received %1$s', 'event_espresso'),
165
-                    print_r($transition, true)
166
-                )
167
-            );
168
-        }
169
-        return $transition['offset'];
170
-    }
171
-
172
-
173
-    /**
174
-     * Provide a timezone select input
175
-     *
176
-     * @param string $timezone_string
177
-     * @return string
178
-     * @throws EE_Error
179
-     */
180
-    public function timezoneSelectInput($timezone_string = '')
181
-    {
182
-        // get WP date time format
183
-        $datetime_format = get_option('date_format') . ' ' . get_option('time_format');
184
-        // if passed a value, then use that, else get WP option
185
-        $timezone_string = ! empty($timezone_string) ? $timezone_string : (string) get_option('timezone_string');
186
-        // check if the timezone is valid but don't throw any errors if it isn't
187
-        $timezone_string = $this->validateTimezone($timezone_string, false)
188
-            ? $timezone_string
189
-            : '';
190
-        $gmt_offset      = get_option('gmt_offset');
191
-        $check_zone_info = true;
192
-        if (empty($timezone_string)) {
193
-            // Create a UTC+- zone if no timezone string exists
194
-            $timezone_string = 'UTC';
195
-            $check_zone_info = false;
196
-            if ($gmt_offset > 0) {
197
-                $timezone_string = 'UTC+' . $gmt_offset;
198
-            } elseif ($gmt_offset < 0) {
199
-                $timezone_string = 'UTC' . $gmt_offset;
200
-            }
201
-        }
202
-        ?>
14
+	/**
15
+	 * @var string
16
+	 */
17
+	private $default_timezone_string = '';
18
+
19
+
20
+	/**
21
+	 * AbstractHelper constructor.
22
+	 */
23
+	public function __construct()
24
+	{
25
+		add_action('update_option_timezone_string', [$this, 'updateDefaultTimezoneString'], 10, 2);
26
+	}
27
+	/**
28
+	 * AbstractHelper destructor.
29
+	 */
30
+	public function __destruct()
31
+	{
32
+		remove_action('update_option_timezone_string', [$this, 'updateDefaultTimezoneString']);
33
+	}
34
+
35
+
36
+
37
+
38
+	/**
39
+	 * Ensures that a valid timezone string is returned.
40
+	 *
41
+	 * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
42
+	 *                                 settings (or derive from set UTC offset).
43
+	 * @param bool   $throw_error
44
+	 * @return string
45
+	 * @throws EE_Error
46
+	 */
47
+	public function getValidTimezoneString($timezone_string = '', $throw_error = false)
48
+	{
49
+		// if a valid TZ is supplied, then just use that, but don't throw errors if it's invalid
50
+		if (! empty($timezone_string) && $this->validateTimezone($timezone_string, $throw_error)) {
51
+			return $timezone_string;
52
+		}
53
+		// cache whatever gets set as the site default
54
+		// no default set yet? then let's get to it!
55
+		if ($this->default_timezone_string === '') {
56
+			// ignore the incoming TZ string because we already know it's invalid
57
+			// and just pull the default set for the site
58
+			$timezone_string = (string) get_option('timezone_string');
59
+			// if the site admin has not set a valid default,
60
+			// then derive the TZ from the UTC offset (and hope that that is set)
61
+			$timezone_string = ! empty($timezone_string)
62
+				? $timezone_string
63
+				: $this->getTimezoneStringFromGmtOffset();
64
+			// make sure it's all good (and this time blow things up if no TZ can be determined)
65
+			$this->validateTimezone($timezone_string);
66
+			// cache the default so that we don't do this a Brazilian times
67
+			$this->default_timezone_string = $timezone_string;
68
+		}
69
+		return $this->default_timezone_string;
70
+	}
71
+
72
+
73
+	public function resetDefaultTimezoneString()
74
+	{
75
+		$this->default_timezone_string = '';
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param $old_value
81
+	 * @param $value
82
+	 * @throws EE_Error
83
+	 * @since   $VID:$
84
+	 */
85
+	public function updateDefaultTimezoneString($old_value, $value)
86
+	{
87
+		if ($value && $value !== $old_value && $value !== $this->default_timezone_string) {
88
+			$this->resetDefaultTimezoneString();
89
+			$this->getValidTimezoneString($value);
90
+		}
91
+	}
92
+
93
+	/**
94
+	 * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
95
+	 *
96
+	 * @param string $timezone_string
97
+	 * @param bool   $throw_error
98
+	 * @return bool
99
+	 * @throws EE_Error
100
+	 */
101
+	public function validateTimezone($timezone_string, $throw_error = true)
102
+	{
103
+		// easiest way to test a timezone string is just see if it throws an error when you try to create a
104
+		// DateTimeZone object with it
105
+		try {
106
+			new DateTimeZone($timezone_string);
107
+		} catch (Exception $e) {
108
+			// sometimes we take exception to exceptions
109
+			if (! $throw_error) {
110
+				return false;
111
+			}
112
+			throw new EE_Error(
113
+				sprintf(
114
+					esc_html__(
115
+						'The timezone given (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
116
+						'event_espresso'
117
+					),
118
+					$timezone_string,
119
+					'<a href="http://www.php.net/manual/en/timezones.php">',
120
+					'</a>'
121
+				)
122
+			);
123
+		}
124
+		return true;
125
+	}
126
+
127
+
128
+	/**
129
+	 * Gets the site's GMT offset based on either the timezone string
130
+	 * (in which case the gmt offset will vary depending on the location's
131
+	 * observance of daylight savings time) or the gmt_offset wp option
132
+	 *
133
+	 * @return int  seconds offset
134
+	 */
135
+	public function getSiteTimezoneGmtOffset()
136
+	{
137
+		$timezone_string = (string) get_option('timezone_string');
138
+		if ($timezone_string) {
139
+			try {
140
+				$timezone = new DateTimeZone($timezone_string);
141
+				return $timezone->getOffset(new DateTime()); // in WordPress DateTime defaults to UTC
142
+			} catch (Exception $e) {
143
+			}
144
+		}
145
+		$offset = get_option('gmt_offset');
146
+		return (int) ($offset * HOUR_IN_SECONDS);
147
+	}
148
+
149
+
150
+	/**
151
+	 * Get Timezone offset for given timezone object
152
+	 *
153
+	 * @param DateTimeZone $date_time_zone
154
+	 * @param null|int     $time
155
+	 * @return int
156
+	 * @throws DomainException
157
+	 */
158
+	public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null)
159
+	{
160
+		$transition = $this->getTimezoneTransitions($date_time_zone, $time);
161
+		if (! isset($transition['offset'])) {
162
+			throw new DomainException(
163
+				sprintf(
164
+					esc_html__('An invalid timezone transition was received %1$s', 'event_espresso'),
165
+					print_r($transition, true)
166
+				)
167
+			);
168
+		}
169
+		return $transition['offset'];
170
+	}
171
+
172
+
173
+	/**
174
+	 * Provide a timezone select input
175
+	 *
176
+	 * @param string $timezone_string
177
+	 * @return string
178
+	 * @throws EE_Error
179
+	 */
180
+	public function timezoneSelectInput($timezone_string = '')
181
+	{
182
+		// get WP date time format
183
+		$datetime_format = get_option('date_format') . ' ' . get_option('time_format');
184
+		// if passed a value, then use that, else get WP option
185
+		$timezone_string = ! empty($timezone_string) ? $timezone_string : (string) get_option('timezone_string');
186
+		// check if the timezone is valid but don't throw any errors if it isn't
187
+		$timezone_string = $this->validateTimezone($timezone_string, false)
188
+			? $timezone_string
189
+			: '';
190
+		$gmt_offset      = get_option('gmt_offset');
191
+		$check_zone_info = true;
192
+		if (empty($timezone_string)) {
193
+			// Create a UTC+- zone if no timezone string exists
194
+			$timezone_string = 'UTC';
195
+			$check_zone_info = false;
196
+			if ($gmt_offset > 0) {
197
+				$timezone_string = 'UTC+' . $gmt_offset;
198
+			} elseif ($gmt_offset < 0) {
199
+				$timezone_string = 'UTC' . $gmt_offset;
200
+			}
201
+		}
202
+		?>
203 203
         <p>
204 204
             <label for="timezone_string"><?php _e('timezone', 'event_espresso'); ?></label>
205 205
             <select id="timezone_string" name="timezone_string">
@@ -212,150 +212,150 @@  discard block
 block discarded – undo
212 212
         <p>
213 213
         <span>
214 214
             <?php
215
-            printf(
216
-                __('%1$sUTC%2$s time is %3$s', 'event_espresso'),
217
-                '<abbr title="Coordinated Universal Time">',
218
-                '</abbr>',
219
-                '<code>' . date_i18n($datetime_format, false, true) . '</code>'
220
-            );
221
-            ?></span>
215
+			printf(
216
+				__('%1$sUTC%2$s time is %3$s', 'event_espresso'),
217
+				'<abbr title="Coordinated Universal Time">',
218
+				'</abbr>',
219
+				'<code>' . date_i18n($datetime_format, false, true) . '</code>'
220
+			);
221
+			?></span>
222 222
         <?php
223
-        if (! empty($timezone_string) || ! empty($gmt_offset)) : ?>
223
+		if (! empty($timezone_string) || ! empty($gmt_offset)) : ?>
224 224
         <br/><span><?php printf(__('Local time is %1$s', 'event_espresso'), '<code>' . date_i18n($datetime_format) . '</code>'); ?></span>
225 225
             <?php
226
-        endif; ?>
226
+		endif; ?>
227 227
 
228 228
         <?php
229
-        if ($check_zone_info && $timezone_string) : ?>
229
+		if ($check_zone_info && $timezone_string) : ?>
230 230
         <br/>
231 231
         <span>
232 232
                 <?php
233
-                // Set TZ so localtime works.
234
-                date_default_timezone_set($timezone_string);
235
-                $now = localtime(time(), true);
236
-                if ($now['tm_isdst']) {
237
-                    _e('This timezone is currently in daylight saving time.', 'event_espresso');
238
-                } else {
239
-                    _e('This timezone is currently in standard time.', 'event_espresso');
240
-                }
241
-                ?>
233
+				// Set TZ so localtime works.
234
+				date_default_timezone_set($timezone_string);
235
+				$now = localtime(time(), true);
236
+				if ($now['tm_isdst']) {
237
+					_e('This timezone is currently in daylight saving time.', 'event_espresso');
238
+				} else {
239
+					_e('This timezone is currently in standard time.', 'event_espresso');
240
+				}
241
+				?>
242 242
             <br/>
243 243
             <?php
244
-            if (function_exists('timezone_transitions_get')) {
245
-                $found                   = false;
246
-                $date_time_zone_selected = new DateTimeZone($timezone_string);
247
-                $tz_offset               = timezone_offset_get($date_time_zone_selected, date_create());
248
-                $right_now               = time();
249
-                $tr['isdst']             = false;
250
-                foreach (timezone_transitions_get($date_time_zone_selected) as $tr) {
251
-                    if ($tr['ts'] > $right_now) {
252
-                        $found = true;
253
-                        break;
254
-                    }
255
-                }
256
-                if ($found) {
257
-                    $message = $tr['isdst']
258
-                        ? __(' Daylight saving time begins on: %s.', 'event_espresso')
259
-                        : __(' Standard time begins  on: %s.', 'event_espresso');
260
-                    // Add the difference between the current offset and the new offset to ts to get the correct
261
-                    // transition time from date_i18n().
262
-                    printf(
263
-                        $message,
264
-                        '<code >' . date_i18n($datetime_format, $tr['ts'] + ($tz_offset - $tr['offset'])) . '</code >'
265
-                    );
266
-                } else {
267
-                    _e('This timezone does not observe daylight saving time.', 'event_espresso');
268
-                }
269
-            }
270
-            // Set back to UTC.
271
-            date_default_timezone_set('UTC');
272
-            ?>
244
+			if (function_exists('timezone_transitions_get')) {
245
+				$found                   = false;
246
+				$date_time_zone_selected = new DateTimeZone($timezone_string);
247
+				$tz_offset               = timezone_offset_get($date_time_zone_selected, date_create());
248
+				$right_now               = time();
249
+				$tr['isdst']             = false;
250
+				foreach (timezone_transitions_get($date_time_zone_selected) as $tr) {
251
+					if ($tr['ts'] > $right_now) {
252
+						$found = true;
253
+						break;
254
+					}
255
+				}
256
+				if ($found) {
257
+					$message = $tr['isdst']
258
+						? __(' Daylight saving time begins on: %s.', 'event_espresso')
259
+						: __(' Standard time begins  on: %s.', 'event_espresso');
260
+					// Add the difference between the current offset and the new offset to ts to get the correct
261
+					// transition time from date_i18n().
262
+					printf(
263
+						$message,
264
+						'<code >' . date_i18n($datetime_format, $tr['ts'] + ($tz_offset - $tr['offset'])) . '</code >'
265
+					);
266
+				} else {
267
+					_e('This timezone does not observe daylight saving time.', 'event_espresso');
268
+				}
269
+			}
270
+			// Set back to UTC.
271
+			date_default_timezone_set('UTC');
272
+			?>
273 273
         </span></p>
274 274
             <?php
275
-        endif;
276
-    }
277
-
278
-
279
-    /**
280
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
281
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
282
-     * the site is used.
283
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
284
-     * computed timestamp (i.e. date_i18n() )
285
-     *
286
-     * @param int    $unix_timestamp  if 0, then time() will be used.
287
-     * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
288
-     *                                site will be used.
289
-     * @return int      unix_timestamp value with the offset applied for the given timezone.
290
-     * @throws EE_Error
291
-     */
292
-    public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '')
293
-    {
294
-        $unix_timestamp  = $unix_timestamp === 0 ? time() : (int) $unix_timestamp;
295
-        $timezone_string = $this->getValidTimezoneString($timezone_string);
296
-        $TimeZone        = new DateTimeZone($timezone_string);
297
-        $DateTime        = new DateTime('@' . $unix_timestamp, $TimeZone);
298
-        $offset          = timezone_offset_get($TimeZone, $DateTime);
299
-        return (int) $DateTime->format('U') + (int) $offset;
300
-    }
301
-
302
-
303
-    /**
304
-     * Get Timezone Transitions
305
-     *
306
-     * @param DateTimeZone $date_time_zone
307
-     * @param int|null     $time
308
-     * @param bool         $first_only
309
-     * @return array|mixed
310
-     */
311
-    public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
312
-    {
313
-        $time        = is_int($time) || $time === null ? $time : (int) strtotime($time);
314
-        $time        = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
315
-        $transitions = $date_time_zone->getTransitions($time);
316
-        return $first_only && ! isset($transitions['ts']) ? reset($transitions) : $transitions;
317
-    }
318
-
319
-
320
-
321
-    /**
322
-     * Default to just returning the provided $gmt_offset.  Children can override if adjustment needed.
323
-     *
324
-     * @param int $gmt_offset
325
-     * @return int
326
-     */
327
-    public function adjustInvalidGmtOffsets($gmt_offset = 0)
328
-    {
329
-        return $gmt_offset;
330
-    }
331
-
332
-
333
-
334
-    /**
335
-     * This receives an incoming gmt_offset and santizes it.  If the provide value is an empty string, then this will
336
-     * attempt to get the offset from the timezone string.  If this returns a string, then a timezone string was
337
-     * successfully derived from existing timezone_string in the db.  If not, then a float is returned for the provided
338
-     * offset.
339
-     * @param  float|string $gmt_offset
340
-     * @return float|string
341
-     */
342
-    protected function sanitizeInitialIncomingGmtOffsetForGettingTimezoneString($gmt_offset)
343
-    {
344
-        // if there is no incoming gmt_offset, then because WP hooks in on timezone_string, we need to see if that is
345
-        // set because it will override `gmt_offset` via `pre_get_option` filter.  If that's set, then let's just use
346
-        // that!  Otherwise we'll leave timezone_string at the default of 'UTC' before doing other logic.
347
-        if ($gmt_offset === '') {
348
-            // autoloaded so no need to set to a variable.  There will not be multiple hits to the db.
349
-            if (get_option('timezone_string')) {
350
-                return (string) get_option('timezone_string');
351
-            }
352
-        }
353
-        $gmt_offset = $gmt_offset !== '' ? $gmt_offset : (string) get_option('gmt_offset');
354
-        $gmt_offset = (float) $gmt_offset;
355
-        // if $gmt_offset is 0 or is still an empty string, then just return UTC
356
-        if ($gmt_offset === (float) 0) {
357
-            return 'UTC';
358
-        }
359
-        return $gmt_offset;
360
-    }
275
+		endif;
276
+	}
277
+
278
+
279
+	/**
280
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
281
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
282
+	 * the site is used.
283
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
284
+	 * computed timestamp (i.e. date_i18n() )
285
+	 *
286
+	 * @param int    $unix_timestamp  if 0, then time() will be used.
287
+	 * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
288
+	 *                                site will be used.
289
+	 * @return int      unix_timestamp value with the offset applied for the given timezone.
290
+	 * @throws EE_Error
291
+	 */
292
+	public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '')
293
+	{
294
+		$unix_timestamp  = $unix_timestamp === 0 ? time() : (int) $unix_timestamp;
295
+		$timezone_string = $this->getValidTimezoneString($timezone_string);
296
+		$TimeZone        = new DateTimeZone($timezone_string);
297
+		$DateTime        = new DateTime('@' . $unix_timestamp, $TimeZone);
298
+		$offset          = timezone_offset_get($TimeZone, $DateTime);
299
+		return (int) $DateTime->format('U') + (int) $offset;
300
+	}
301
+
302
+
303
+	/**
304
+	 * Get Timezone Transitions
305
+	 *
306
+	 * @param DateTimeZone $date_time_zone
307
+	 * @param int|null     $time
308
+	 * @param bool         $first_only
309
+	 * @return array|mixed
310
+	 */
311
+	public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
312
+	{
313
+		$time        = is_int($time) || $time === null ? $time : (int) strtotime($time);
314
+		$time        = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
315
+		$transitions = $date_time_zone->getTransitions($time);
316
+		return $first_only && ! isset($transitions['ts']) ? reset($transitions) : $transitions;
317
+	}
318
+
319
+
320
+
321
+	/**
322
+	 * Default to just returning the provided $gmt_offset.  Children can override if adjustment needed.
323
+	 *
324
+	 * @param int $gmt_offset
325
+	 * @return int
326
+	 */
327
+	public function adjustInvalidGmtOffsets($gmt_offset = 0)
328
+	{
329
+		return $gmt_offset;
330
+	}
331
+
332
+
333
+
334
+	/**
335
+	 * This receives an incoming gmt_offset and santizes it.  If the provide value is an empty string, then this will
336
+	 * attempt to get the offset from the timezone string.  If this returns a string, then a timezone string was
337
+	 * successfully derived from existing timezone_string in the db.  If not, then a float is returned for the provided
338
+	 * offset.
339
+	 * @param  float|string $gmt_offset
340
+	 * @return float|string
341
+	 */
342
+	protected function sanitizeInitialIncomingGmtOffsetForGettingTimezoneString($gmt_offset)
343
+	{
344
+		// if there is no incoming gmt_offset, then because WP hooks in on timezone_string, we need to see if that is
345
+		// set because it will override `gmt_offset` via `pre_get_option` filter.  If that's set, then let's just use
346
+		// that!  Otherwise we'll leave timezone_string at the default of 'UTC' before doing other logic.
347
+		if ($gmt_offset === '') {
348
+			// autoloaded so no need to set to a variable.  There will not be multiple hits to the db.
349
+			if (get_option('timezone_string')) {
350
+				return (string) get_option('timezone_string');
351
+			}
352
+		}
353
+		$gmt_offset = $gmt_offset !== '' ? $gmt_offset : (string) get_option('gmt_offset');
354
+		$gmt_offset = (float) $gmt_offset;
355
+		// if $gmt_offset is 0 or is still an empty string, then just return UTC
356
+		if ($gmt_offset === (float) 0) {
357
+			return 'UTC';
358
+		}
359
+		return $gmt_offset;
360
+	}
361 361
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
     public function getValidTimezoneString($timezone_string = '', $throw_error = false)
48 48
     {
49 49
         // if a valid TZ is supplied, then just use that, but don't throw errors if it's invalid
50
-        if (! empty($timezone_string) && $this->validateTimezone($timezone_string, $throw_error)) {
50
+        if ( ! empty($timezone_string) && $this->validateTimezone($timezone_string, $throw_error)) {
51 51
             return $timezone_string;
52 52
         }
53 53
         // cache whatever gets set as the site default
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
             new DateTimeZone($timezone_string);
107 107
         } catch (Exception $e) {
108 108
             // sometimes we take exception to exceptions
109
-            if (! $throw_error) {
109
+            if ( ! $throw_error) {
110 110
                 return false;
111 111
             }
112 112
             throw new EE_Error(
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
     public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null)
159 159
     {
160 160
         $transition = $this->getTimezoneTransitions($date_time_zone, $time);
161
-        if (! isset($transition['offset'])) {
161
+        if ( ! isset($transition['offset'])) {
162 162
             throw new DomainException(
163 163
                 sprintf(
164 164
                     esc_html__('An invalid timezone transition was received %1$s', 'event_espresso'),
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
     public function timezoneSelectInput($timezone_string = '')
181 181
     {
182 182
         // get WP date time format
183
-        $datetime_format = get_option('date_format') . ' ' . get_option('time_format');
183
+        $datetime_format = get_option('date_format').' '.get_option('time_format');
184 184
         // if passed a value, then use that, else get WP option
185 185
         $timezone_string = ! empty($timezone_string) ? $timezone_string : (string) get_option('timezone_string');
186 186
         // check if the timezone is valid but don't throw any errors if it isn't
@@ -194,9 +194,9 @@  discard block
 block discarded – undo
194 194
             $timezone_string = 'UTC';
195 195
             $check_zone_info = false;
196 196
             if ($gmt_offset > 0) {
197
-                $timezone_string = 'UTC+' . $gmt_offset;
197
+                $timezone_string = 'UTC+'.$gmt_offset;
198 198
             } elseif ($gmt_offset < 0) {
199
-                $timezone_string = 'UTC' . $gmt_offset;
199
+                $timezone_string = 'UTC'.$gmt_offset;
200 200
             }
201 201
         }
202 202
         ?>
@@ -216,12 +216,12 @@  discard block
 block discarded – undo
216 216
                 __('%1$sUTC%2$s time is %3$s', 'event_espresso'),
217 217
                 '<abbr title="Coordinated Universal Time">',
218 218
                 '</abbr>',
219
-                '<code>' . date_i18n($datetime_format, false, true) . '</code>'
219
+                '<code>'.date_i18n($datetime_format, false, true).'</code>'
220 220
             );
221 221
             ?></span>
222 222
         <?php
223
-        if (! empty($timezone_string) || ! empty($gmt_offset)) : ?>
224
-        <br/><span><?php printf(__('Local time is %1$s', 'event_espresso'), '<code>' . date_i18n($datetime_format) . '</code>'); ?></span>
223
+        if ( ! empty($timezone_string) || ! empty($gmt_offset)) : ?>
224
+        <br/><span><?php printf(__('Local time is %1$s', 'event_espresso'), '<code>'.date_i18n($datetime_format).'</code>'); ?></span>
225 225
             <?php
226 226
         endif; ?>
227 227
 
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
                     // transition time from date_i18n().
262 262
                     printf(
263 263
                         $message,
264
-                        '<code >' . date_i18n($datetime_format, $tr['ts'] + ($tz_offset - $tr['offset'])) . '</code >'
264
+                        '<code >'.date_i18n($datetime_format, $tr['ts'] + ($tz_offset - $tr['offset'])).'</code >'
265 265
                     );
266 266
                 } else {
267 267
                     _e('This timezone does not observe daylight saving time.', 'event_espresso');
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
         $unix_timestamp  = $unix_timestamp === 0 ? time() : (int) $unix_timestamp;
295 295
         $timezone_string = $this->getValidTimezoneString($timezone_string);
296 296
         $TimeZone        = new DateTimeZone($timezone_string);
297
-        $DateTime        = new DateTime('@' . $unix_timestamp, $TimeZone);
297
+        $DateTime        = new DateTime('@'.$unix_timestamp, $TimeZone);
298 298
         $offset          = timezone_offset_get($TimeZone, $DateTime);
299 299
         return (int) $DateTime->format('U') + (int) $offset;
300 300
     }
Please login to merge, or discard this patch.
core/EE_Registry.core.php 1 patch
Indentation   +1696 added lines, -1696 removed lines patch added patch discarded remove patch
@@ -23,1704 +23,1704 @@
 block discarded – undo
23 23
 class EE_Registry implements ResettableInterface
24 24
 {
25 25
 
26
-    /**
27
-     * @var EE_Registry $_instance
28
-     */
29
-    private static $_instance;
30
-
31
-    /**
32
-     * @var EE_Dependency_Map $_dependency_map
33
-     */
34
-    protected $_dependency_map;
35
-
36
-    /**
37
-     * @var Mirror
38
-     */
39
-    private $mirror;
40
-
41
-    /**
42
-     * @var ClassInterfaceCache $class_cache
43
-     */
44
-    private $class_cache;
45
-
46
-    /**
47
-     * @var array $_class_abbreviations
48
-     */
49
-    protected $_class_abbreviations = array();
50
-
51
-    /**
52
-     * @var CommandBusInterface $BUS
53
-     */
54
-    public $BUS;
55
-
56
-    /**
57
-     * @var EE_Cart $CART
58
-     */
59
-    public $CART;
60
-
61
-    /**
62
-     * @var EE_Config $CFG
63
-     */
64
-    public $CFG;
65
-
66
-    /**
67
-     * @var EE_Network_Config $NET_CFG
68
-     */
69
-    public $NET_CFG;
70
-
71
-    /**
72
-     * StdClass object for storing library classes in
73
-     *
74
-     * @var RegistryContainer $LIB
75
-     */
76
-    public $LIB;
77
-
78
-    /**
79
-     * @var EE_Request_Handler $REQ
80
-     */
81
-    public $REQ;
82
-
83
-    /**
84
-     * @var EE_Session $SSN
85
-     */
86
-    public $SSN;
87
-
88
-    /**
89
-     * @since 4.5.0
90
-     * @var EE_Capabilities $CAP
91
-     */
92
-    public $CAP;
93
-
94
-    /**
95
-     * @since 4.9.0
96
-     * @var EE_Message_Resource_Manager $MRM
97
-     */
98
-    public $MRM;
99
-
100
-    /**
101
-     * @var Registry $AssetsRegistry
102
-     */
103
-    public $AssetsRegistry;
104
-
105
-    /**
106
-     * StdClass object for holding addons which have registered themselves to work with EE core
107
-     *
108
-     * @var EE_Addon[] $addons
109
-     */
110
-    public $addons;
111
-
112
-    /**
113
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
114
-     *
115
-     * @var EEM_Base[] $models
116
-     */
117
-    public $models = array();
118
-
119
-    /**
120
-     * @var EED_Module[] $modules
121
-     */
122
-    public $modules;
123
-
124
-    /**
125
-     * @var EES_Shortcode[] $shortcodes
126
-     */
127
-    public $shortcodes;
128
-
129
-    /**
130
-     * @var WP_Widget[] $widgets
131
-     */
132
-    public $widgets;
133
-
134
-    /**
135
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
136
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
137
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
138
-     * classnames (eg "EEM_Event")
139
-     *
140
-     * @var array $non_abstract_db_models
141
-     */
142
-    public $non_abstract_db_models = array();
143
-
144
-    /**
145
-     * internationalization for JS strings
146
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
147
-     *    in js file:  var translatedString = eei18n.string_key;
148
-     *
149
-     * @var array $i18n_js_strings
150
-     */
151
-    public static $i18n_js_strings = array();
152
-
153
-    /**
154
-     * $main_file - path to espresso.php
155
-     *
156
-     * @var array $main_file
157
-     */
158
-    public $main_file;
159
-
160
-    /**
161
-     * array of ReflectionClass objects where the key is the class name
162
-     *
163
-     * @deprecated 4.9.62.p
164
-     * @var ReflectionClass[] $_reflectors
165
-     */
166
-    public $_reflectors;
167
-
168
-    /**
169
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
170
-     *
171
-     * @var boolean $_cache_on
172
-     */
173
-    protected $_cache_on = true;
174
-
175
-    /**
176
-     * @var ObjectIdentifier
177
-     */
178
-    private $object_identifier;
179
-
180
-
181
-    /**
182
-     * @singleton method used to instantiate class object
183
-     * @param EE_Dependency_Map|null   $dependency_map
184
-     * @param Mirror|null              $mirror
185
-     * @param ClassInterfaceCache|null $class_cache
186
-     * @param ObjectIdentifier|null    $object_identifier
187
-     * @return EE_Registry instance
188
-     */
189
-    public static function instance(
190
-        EE_Dependency_Map $dependency_map = null,
191
-        Mirror $mirror = null,
192
-        ClassInterfaceCache $class_cache = null,
193
-        ObjectIdentifier $object_identifier = null
194
-    ) {
195
-        // check if class object is instantiated
196
-        if (
197
-            ! self::$_instance instanceof EE_Registry
198
-            && $dependency_map instanceof EE_Dependency_Map
199
-            && $mirror instanceof Mirror
200
-            && $class_cache instanceof ClassInterfaceCache
201
-            && $object_identifier instanceof ObjectIdentifier
202
-        ) {
203
-            self::$_instance = new self(
204
-                $dependency_map,
205
-                $mirror,
206
-                $class_cache,
207
-                $object_identifier
208
-            );
209
-        }
210
-        return self::$_instance;
211
-    }
212
-
213
-
214
-    /**
215
-     * protected constructor to prevent direct creation
216
-     *
217
-     * @Constructor
218
-     * @param  EE_Dependency_Map  $dependency_map
219
-     * @param Mirror              $mirror
220
-     * @param ClassInterfaceCache $class_cache
221
-     * @param ObjectIdentifier    $object_identifier
222
-     */
223
-    protected function __construct(
224
-        EE_Dependency_Map $dependency_map,
225
-        Mirror $mirror,
226
-        ClassInterfaceCache $class_cache,
227
-        ObjectIdentifier $object_identifier
228
-    ) {
229
-        $this->_dependency_map = $dependency_map;
230
-        $this->mirror = $mirror;
231
-        $this->class_cache = $class_cache;
232
-        $this->object_identifier = $object_identifier;
233
-        // $registry_container = new RegistryContainer();
234
-        $this->LIB = new RegistryContainer();
235
-        $this->addons = new RegistryContainer();
236
-        $this->modules = new RegistryContainer();
237
-        $this->shortcodes = new RegistryContainer();
238
-        $this->widgets = new RegistryContainer();
239
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
240
-    }
241
-
242
-
243
-    /**
244
-     * initialize
245
-     *
246
-     * @throws OutOfBoundsException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     * @throws ReflectionException
252
-     */
253
-    public function initialize()
254
-    {
255
-        $this->_class_abbreviations = apply_filters(
256
-            'FHEE__EE_Registry____construct___class_abbreviations',
257
-            array(
258
-                'EE_Config'                                       => 'CFG',
259
-                'EE_Session'                                      => 'SSN',
260
-                'EE_Capabilities'                                 => 'CAP',
261
-                'EE_Cart'                                         => 'CART',
262
-                'EE_Network_Config'                               => 'NET_CFG',
263
-                'EE_Request_Handler'                              => 'REQ',
264
-                'EE_Message_Resource_Manager'                     => 'MRM',
265
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
266
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
267
-            )
268
-        );
269
-        $this->load_core('Base', array(), true);
270
-        // add our request and response objects to the cache
271
-        $request_loader = $this->_dependency_map->class_loader(
272
-            'EventEspresso\core\services\request\Request'
273
-        );
274
-        $this->_set_cached_class(
275
-            $request_loader(),
276
-            'EventEspresso\core\services\request\Request'
277
-        );
278
-        $response_loader = $this->_dependency_map->class_loader(
279
-            'EventEspresso\core\services\request\Response'
280
-        );
281
-        $this->_set_cached_class(
282
-            $response_loader(),
283
-            'EventEspresso\core\services\request\Response'
284
-        );
285
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
286
-    }
287
-
288
-
289
-    /**
290
-     * @return void
291
-     */
292
-    public function init()
293
-    {
294
-        // Get current page protocol
295
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
296
-        // Output admin-ajax.php URL with same protocol as current page
297
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
298
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
299
-    }
300
-
301
-
302
-    /**
303
-     * localize_i18n_js_strings
304
-     *
305
-     * @return string
306
-     */
307
-    public static function localize_i18n_js_strings()
308
-    {
309
-        $i18n_js_strings = (array) self::$i18n_js_strings;
310
-        foreach ($i18n_js_strings as $key => $value) {
311
-            if (is_scalar($value)) {
312
-                $i18n_js_strings[ $key ] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
313
-            }
314
-        }
315
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
316
-    }
317
-
318
-
319
-    /**
320
-     * @param mixed string | EED_Module $module
321
-     * @throws OutOfBoundsException
322
-     * @throws InvalidArgumentException
323
-     * @throws InvalidInterfaceException
324
-     * @throws InvalidDataTypeException
325
-     * @throws EE_Error
326
-     * @throws ReflectionException
327
-     */
328
-    public function add_module($module)
329
-    {
330
-        if ($module instanceof EED_Module) {
331
-            $module_class = get_class($module);
332
-            $this->modules->{$module_class} = $module;
333
-        } else {
334
-            if (! class_exists('EE_Module_Request_Router', false)) {
335
-                $this->load_core('Module_Request_Router');
336
-            }
337
-            EE_Module_Request_Router::module_factory($module);
338
-        }
339
-    }
340
-
341
-
342
-    /**
343
-     * @param string $module_name
344
-     * @return mixed EED_Module | NULL
345
-     */
346
-    public function get_module($module_name = '')
347
-    {
348
-        return isset($this->modules->{$module_name})
349
-            ? $this->modules->{$module_name}
350
-            : null;
351
-    }
352
-
353
-
354
-    /**
355
-     * loads core classes - must be singletons
356
-     *
357
-     * @param string $class_name - simple class name ie: session
358
-     * @param mixed  $arguments
359
-     * @param bool   $load_only
360
-     * @return mixed
361
-     * @throws InvalidInterfaceException
362
-     * @throws InvalidDataTypeException
363
-     * @throws EE_Error
364
-     * @throws ReflectionException
365
-     * @throws InvalidArgumentException
366
-     */
367
-    public function load_core($class_name, $arguments = array(), $load_only = false)
368
-    {
369
-        $core_paths = apply_filters(
370
-            'FHEE__EE_Registry__load_core__core_paths',
371
-            array(
372
-                EE_CORE,
373
-                EE_ADMIN,
374
-                EE_CPTS,
375
-                EE_CORE . 'data_migration_scripts/',
376
-                EE_CORE . 'capabilities/',
377
-                EE_CORE . 'request_stack/',
378
-                EE_CORE . 'middleware/',
379
-            )
380
-        );
381
-        // retrieve instantiated class
382
-        return $this->_load(
383
-            $core_paths,
384
-            'EE_',
385
-            $class_name,
386
-            'core',
387
-            $arguments,
388
-            false,
389
-            true,
390
-            $load_only
391
-        );
392
-    }
393
-
394
-
395
-    /**
396
-     * loads service classes
397
-     *
398
-     * @param string $class_name - simple class name ie: session
399
-     * @param mixed  $arguments
400
-     * @param bool   $load_only
401
-     * @return mixed
402
-     * @throws InvalidInterfaceException
403
-     * @throws InvalidDataTypeException
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     * @throws InvalidArgumentException
407
-     */
408
-    public function load_service($class_name, $arguments = array(), $load_only = false)
409
-    {
410
-        $service_paths = apply_filters(
411
-            'FHEE__EE_Registry__load_service__service_paths',
412
-            array(
413
-                EE_CORE . 'services/',
414
-            )
415
-        );
416
-        // retrieve instantiated class
417
-        return $this->_load(
418
-            $service_paths,
419
-            'EE_',
420
-            $class_name,
421
-            'class',
422
-            $arguments,
423
-            false,
424
-            true,
425
-            $load_only
426
-        );
427
-    }
428
-
429
-
430
-    /**
431
-     * loads data_migration_scripts
432
-     *
433
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
434
-     * @param mixed  $arguments
435
-     * @return EE_Data_Migration_Script_Base|mixed
436
-     * @throws InvalidInterfaceException
437
-     * @throws InvalidDataTypeException
438
-     * @throws EE_Error
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     */
442
-    public function load_dms($class_name, $arguments = array())
443
-    {
444
-        // retrieve instantiated class
445
-        return $this->_load(
446
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
447
-            'EE_DMS_',
448
-            $class_name,
449
-            'dms',
450
-            $arguments,
451
-            false,
452
-            false
453
-        );
454
-    }
455
-
456
-
457
-    /**
458
-     * loads object creating classes - must be singletons
459
-     *
460
-     * @param string $class_name - simple class name ie: attendee
461
-     * @param mixed  $arguments  - an array of arguments to pass to the class
462
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
463
-     *                           instantiate
464
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
465
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
466
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
467
-     *                           (default)
468
-     * @return EE_Base_Class | bool
469
-     * @throws InvalidInterfaceException
470
-     * @throws InvalidDataTypeException
471
-     * @throws EE_Error
472
-     * @throws ReflectionException
473
-     * @throws InvalidArgumentException
474
-     */
475
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
476
-    {
477
-        $paths = apply_filters(
478
-            'FHEE__EE_Registry__load_class__paths',
479
-            array(
480
-                EE_CORE,
481
-                EE_CLASSES,
482
-                EE_BUSINESS,
483
-            )
484
-        );
485
-        // retrieve instantiated class
486
-        return $this->_load(
487
-            $paths,
488
-            'EE_',
489
-            $class_name,
490
-            'class',
491
-            $arguments,
492
-            $from_db,
493
-            $cache,
494
-            $load_only
495
-        );
496
-    }
497
-
498
-
499
-    /**
500
-     * loads helper classes - must be singletons
501
-     *
502
-     * @param string $class_name - simple class name ie: price
503
-     * @param mixed  $arguments
504
-     * @param bool   $load_only
505
-     * @return EEH_Base | bool
506
-     * @throws InvalidInterfaceException
507
-     * @throws InvalidDataTypeException
508
-     * @throws EE_Error
509
-     * @throws ReflectionException
510
-     * @throws InvalidArgumentException
511
-     */
512
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
513
-    {
514
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
515
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
516
-        // retrieve instantiated class
517
-        return $this->_load(
518
-            $helper_paths,
519
-            'EEH_',
520
-            $class_name,
521
-            'helper',
522
-            $arguments,
523
-            false,
524
-            true,
525
-            $load_only
526
-        );
527
-    }
528
-
529
-
530
-    /**
531
-     * loads core classes - must be singletons
532
-     *
533
-     * @param string $class_name - simple class name ie: session
534
-     * @param mixed  $arguments
535
-     * @param bool   $load_only
536
-     * @param bool   $cache      whether to cache the object or not.
537
-     * @return mixed
538
-     * @throws InvalidInterfaceException
539
-     * @throws InvalidDataTypeException
540
-     * @throws EE_Error
541
-     * @throws ReflectionException
542
-     * @throws InvalidArgumentException
543
-     */
544
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
545
-    {
546
-        $paths = array(
547
-            EE_LIBRARIES,
548
-            EE_LIBRARIES . 'messages/',
549
-            EE_LIBRARIES . 'shortcodes/',
550
-            EE_LIBRARIES . 'qtips/',
551
-            EE_LIBRARIES . 'payment_methods/',
552
-        );
553
-        // retrieve instantiated class
554
-        return $this->_load(
555
-            $paths,
556
-            'EE_',
557
-            $class_name,
558
-            'lib',
559
-            $arguments,
560
-            false,
561
-            $cache,
562
-            $load_only
563
-        );
564
-    }
565
-
566
-
567
-    /**
568
-     * loads model classes - must be singletons
569
-     *
570
-     * @param string $class_name - simple class name ie: price
571
-     * @param mixed  $arguments
572
-     * @param bool   $load_only
573
-     * @return EEM_Base | bool
574
-     * @throws InvalidInterfaceException
575
-     * @throws InvalidDataTypeException
576
-     * @throws EE_Error
577
-     * @throws ReflectionException
578
-     * @throws InvalidArgumentException
579
-     */
580
-    public function load_model($class_name, $arguments = array(), $load_only = false)
581
-    {
582
-        $paths = apply_filters(
583
-            'FHEE__EE_Registry__load_model__paths',
584
-            array(
585
-                EE_MODELS,
586
-                EE_CORE,
587
-            )
588
-        );
589
-        // retrieve instantiated class
590
-        return $this->_load(
591
-            $paths,
592
-            'EEM_',
593
-            $class_name,
594
-            'model',
595
-            $arguments,
596
-            false,
597
-            true,
598
-            $load_only
599
-        );
600
-    }
601
-
602
-
603
-    /**
604
-     * loads model classes - must be singletons
605
-     *
606
-     * @param string $class_name - simple class name ie: price
607
-     * @param mixed  $arguments
608
-     * @param bool   $load_only
609
-     * @return mixed | bool
610
-     * @throws InvalidInterfaceException
611
-     * @throws InvalidDataTypeException
612
-     * @throws EE_Error
613
-     * @throws ReflectionException
614
-     * @throws InvalidArgumentException
615
-     */
616
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
617
-    {
618
-        $paths = array(
619
-            EE_MODELS . 'fields/',
620
-            EE_MODELS . 'helpers/',
621
-            EE_MODELS . 'relations/',
622
-            EE_MODELS . 'strategies/',
623
-        );
624
-        // retrieve instantiated class
625
-        return $this->_load(
626
-            $paths,
627
-            'EE_',
628
-            $class_name,
629
-            '',
630
-            $arguments,
631
-            false,
632
-            true,
633
-            $load_only
634
-        );
635
-    }
636
-
637
-
638
-    /**
639
-     * Determines if $model_name is the name of an actual EE model.
640
-     *
641
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
642
-     * @return boolean
643
-     */
644
-    public function is_model_name($model_name)
645
-    {
646
-        return isset($this->models[ $model_name ]);
647
-    }
648
-
649
-
650
-    /**
651
-     * generic class loader
652
-     *
653
-     * @param string $path_to_file - directory path to file location, not including filename
654
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
655
-     * @param string $type         - file type - core? class? helper? model?
656
-     * @param mixed  $arguments
657
-     * @param bool   $load_only
658
-     * @return mixed
659
-     * @throws InvalidInterfaceException
660
-     * @throws InvalidDataTypeException
661
-     * @throws EE_Error
662
-     * @throws ReflectionException
663
-     * @throws InvalidArgumentException
664
-     */
665
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
666
-    {
667
-        // retrieve instantiated class
668
-        return $this->_load(
669
-            $path_to_file,
670
-            '',
671
-            $file_name,
672
-            $type,
673
-            $arguments,
674
-            false,
675
-            true,
676
-            $load_only
677
-        );
678
-    }
679
-
680
-
681
-    /**
682
-     * @param string $path_to_file - directory path to file location, not including filename
683
-     * @param string $class_name   - full class name  ie:  My_Class
684
-     * @param string $type         - file type - core? class? helper? model?
685
-     * @param mixed  $arguments
686
-     * @param bool   $load_only
687
-     * @return bool|EE_Addon|object
688
-     * @throws InvalidInterfaceException
689
-     * @throws InvalidDataTypeException
690
-     * @throws EE_Error
691
-     * @throws ReflectionException
692
-     * @throws InvalidArgumentException
693
-     */
694
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
695
-    {
696
-        // retrieve instantiated class
697
-        return $this->_load(
698
-            $path_to_file,
699
-            'addon',
700
-            $class_name,
701
-            $type,
702
-            $arguments,
703
-            false,
704
-            true,
705
-            $load_only
706
-        );
707
-    }
708
-
709
-
710
-    /**
711
-     * instantiates, caches, and automatically resolves dependencies
712
-     * for classes that use a Fully Qualified Class Name.
713
-     * if the class is not capable of being loaded using PSR-4 autoloading,
714
-     * then you need to use one of the existing load_*() methods
715
-     * which can resolve the classname and filepath from the passed arguments
716
-     *
717
-     * @param bool|string $class_name   Fully Qualified Class Name
718
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
719
-     * @param bool        $cache        whether to cache the instantiated object for reuse
720
-     * @param bool        $from_db      some classes are instantiated from the db
721
-     *                                  and thus call a different method to instantiate
722
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
723
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
724
-     * @return bool|null|mixed          null = failure to load or instantiate class object.
725
-     *                                  object = class loaded and instantiated successfully.
726
-     *                                  bool = fail or success when $load_only is true
727
-     * @throws InvalidInterfaceException
728
-     * @throws InvalidDataTypeException
729
-     * @throws EE_Error
730
-     * @throws ReflectionException
731
-     * @throws InvalidArgumentException
732
-     */
733
-    public function create(
734
-        $class_name = false,
735
-        $arguments = array(),
736
-        $cache = false,
737
-        $from_db = false,
738
-        $load_only = false,
739
-        $addon = false
740
-    ) {
741
-        $class_name = ltrim($class_name, '\\');
742
-        $class_name = $this->class_cache->getFqnForAlias($class_name);
743
-        $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
744
-        // if a non-FQCN was passed, then
745
-        // verifyClassExists() might return an object
746
-        // or it could return null if the class just could not be found anywhere
747
-        if ($class_exists instanceof $class_name || $class_exists === null) {
748
-            // either way, return the results
749
-            return $class_exists;
750
-        }
751
-        $class_name = $class_exists;
752
-        // if we're only loading the class and it already exists, then let's just return true immediately
753
-        if ($load_only) {
754
-            return true;
755
-        }
756
-        $addon = $addon ? 'addon' : '';
757
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
758
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
759
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
760
-        if ($this->_cache_on && $cache && ! $load_only) {
761
-            // return object if it's already cached
762
-            $cached_class = $this->_get_cached_class($class_name, $addon, $arguments);
763
-            if ($cached_class !== null) {
764
-                return $cached_class;
765
-            }
766
-        }// obtain the loader method from the dependency map
767
-        $loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
768
-        if ($loader instanceof Closure) {
769
-            $class_obj = $loader($arguments);
770
-        } else {
771
-            if ($loader && method_exists($this, $loader)) {
772
-                $class_obj = $this->{$loader}($class_name, $arguments);
773
-            } else {
774
-                $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
775
-            }
776
-        }
777
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
778
-            // save it for later... kinda like gum  { : $
779
-            $this->_set_cached_class(
780
-                $class_obj,
781
-                $class_name,
782
-                $addon,
783
-                $from_db,
784
-                $arguments
785
-            );
786
-        }
787
-        $this->_cache_on = true;
788
-        return $class_obj;
789
-    }
790
-
791
-
792
-    /**
793
-     * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
794
-     *
795
-     * @param string|object $class_name
796
-     * @param array         $arguments
797
-     * @param int           $attempt
798
-     * @return mixed
799
-     */
800
-    private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1)
801
-    {
802
-        if (is_object($class_name) || class_exists($class_name)) {
803
-            return $class_name;
804
-        }
805
-        switch ($attempt) {
806
-            case 1:
807
-                // if it's a FQCN then maybe the class is registered with a preceding \
808
-                $class_name = strpos($class_name, '\\') !== false
809
-                    ? '\\' . ltrim($class_name, '\\')
810
-                    : $class_name;
811
-                break;
812
-            case 2:
813
-                //
814
-                $loader = $this->_dependency_map->class_loader($class_name);
815
-                if ($loader && method_exists($this, $loader)) {
816
-                    return $this->{$loader}($class_name, $arguments);
817
-                }
818
-                break;
819
-            case 3:
820
-            default:
821
-                return null;
822
-        }
823
-        $attempt++;
824
-        return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
825
-    }
826
-
827
-
828
-    /**
829
-     * instantiates, caches, and injects dependencies for classes
830
-     *
831
-     * @param array       $file_paths   an array of paths to folders to look in
832
-     * @param string      $class_prefix EE  or EEM or... ???
833
-     * @param bool|string $class_name   $class name
834
-     * @param string      $type         file type - core? class? helper? model?
835
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
836
-     * @param bool        $from_db      some classes are instantiated from the db
837
-     *                                  and thus call a different method to instantiate
838
-     * @param bool        $cache        whether to cache the instantiated object for reuse
839
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
840
-     * @return bool|null|object null = failure to load or instantiate class object.
841
-     *                                  object = class loaded and instantiated successfully.
842
-     *                                  bool = fail or success when $load_only is true
843
-     * @throws EE_Error
844
-     * @throws ReflectionException
845
-     * @throws InvalidInterfaceException
846
-     * @throws InvalidDataTypeException
847
-     * @throws InvalidArgumentException
848
-     */
849
-    protected function _load(
850
-        $file_paths = array(),
851
-        $class_prefix = 'EE_',
852
-        $class_name = false,
853
-        $type = 'class',
854
-        $arguments = array(),
855
-        $from_db = false,
856
-        $cache = true,
857
-        $load_only = false
858
-    ) {
859
-        $class_name = ltrim($class_name, '\\');
860
-        // strip php file extension
861
-        $class_name = str_replace('.php', '', trim($class_name));
862
-        // does the class have a prefix ?
863
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
864
-            // make sure $class_prefix is uppercase
865
-            $class_prefix = strtoupper(trim($class_prefix));
866
-            // add class prefix ONCE!!!
867
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
868
-        }
869
-        $class_name = $this->class_cache->getFqnForAlias($class_name);
870
-        $class_exists = class_exists($class_name, false);
871
-        // if we're only loading the class and it already exists, then let's just return true immediately
872
-        if ($load_only && $class_exists) {
873
-            return true;
874
-        }
875
-        $arguments = is_array($arguments) ? $arguments : array($arguments);
876
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
877
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
878
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
879
-        if ($this->_cache_on && $cache && ! $load_only) {
880
-            // return object if it's already cached
881
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix, $arguments);
882
-            if ($cached_class !== null) {
883
-                return $cached_class;
884
-            }
885
-        }
886
-        // if the class doesn't already exist.. then we need to try and find the file and load it
887
-        if (! $class_exists) {
888
-            // get full path to file
889
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
890
-            // load the file
891
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
892
-            // if we are only loading a file but NOT instantiating an object
893
-            // then return boolean for whether class was loaded or not
894
-            if ($load_only) {
895
-                return $loaded;
896
-            }
897
-            // if an object was expected but loading failed, then return nothing
898
-            if (! $loaded) {
899
-                return null;
900
-            }
901
-        }
902
-        // instantiate the requested object
903
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
904
-        if ($this->_cache_on && $cache) {
905
-            // save it for later... kinda like gum  { : $
906
-            $this->_set_cached_class(
907
-                $class_obj,
908
-                $class_name,
909
-                $class_prefix,
910
-                $from_db,
911
-                $arguments
912
-            );
913
-        }
914
-        $this->_cache_on = true;
915
-        return $class_obj;
916
-    }
917
-
918
-
919
-    /**
920
-     * @param string $class_name
921
-     * @param string $default have to specify something, but not anything that will conflict
922
-     * @return mixed|string
923
-     */
924
-    protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
925
-    {
926
-        return isset($this->_class_abbreviations[ $class_name ])
927
-            ? $this->_class_abbreviations[ $class_name ]
928
-            : $default;
929
-    }
930
-
931
-
932
-    /**
933
-     * attempts to find a cached version of the requested class
934
-     * by looking in the following places:
935
-     *        $this->{$class_abbreviation}            ie:    $this->CART
936
-     *        $this->{$class_name}                        ie:    $this->Some_Class
937
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
938
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
939
-     *
940
-     * @param string $class_name
941
-     * @param string $class_prefix
942
-     * @param array  $arguments
943
-     * @return mixed
944
-     */
945
-    protected function _get_cached_class(
946
-        $class_name,
947
-        $class_prefix = '',
948
-        $arguments = array()
949
-    ) {
950
-        if ($class_name === 'EE_Registry') {
951
-            return $this;
952
-        }
953
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
954
-        // check if class has already been loaded, and return it if it has been
955
-        if (isset($this->{$class_abbreviation})) {
956
-            return $this->{$class_abbreviation};
957
-        }
958
-        $class_name = str_replace('\\', '_', $class_name);
959
-        if (isset($this->{$class_name})) {
960
-            return $this->{$class_name};
961
-        }
962
-        if ($class_prefix === 'addon' && isset($this->addons->{$class_name})) {
963
-            return $this->addons->{$class_name};
964
-        }
965
-        $object_identifier = $this->object_identifier->getIdentifier($class_name, $arguments);
966
-        if (isset($this->LIB->{$object_identifier})) {
967
-            return $this->LIB->{$object_identifier};
968
-        }
969
-        foreach ($this->LIB as $key => $object) {
970
-            if (
26
+	/**
27
+	 * @var EE_Registry $_instance
28
+	 */
29
+	private static $_instance;
30
+
31
+	/**
32
+	 * @var EE_Dependency_Map $_dependency_map
33
+	 */
34
+	protected $_dependency_map;
35
+
36
+	/**
37
+	 * @var Mirror
38
+	 */
39
+	private $mirror;
40
+
41
+	/**
42
+	 * @var ClassInterfaceCache $class_cache
43
+	 */
44
+	private $class_cache;
45
+
46
+	/**
47
+	 * @var array $_class_abbreviations
48
+	 */
49
+	protected $_class_abbreviations = array();
50
+
51
+	/**
52
+	 * @var CommandBusInterface $BUS
53
+	 */
54
+	public $BUS;
55
+
56
+	/**
57
+	 * @var EE_Cart $CART
58
+	 */
59
+	public $CART;
60
+
61
+	/**
62
+	 * @var EE_Config $CFG
63
+	 */
64
+	public $CFG;
65
+
66
+	/**
67
+	 * @var EE_Network_Config $NET_CFG
68
+	 */
69
+	public $NET_CFG;
70
+
71
+	/**
72
+	 * StdClass object for storing library classes in
73
+	 *
74
+	 * @var RegistryContainer $LIB
75
+	 */
76
+	public $LIB;
77
+
78
+	/**
79
+	 * @var EE_Request_Handler $REQ
80
+	 */
81
+	public $REQ;
82
+
83
+	/**
84
+	 * @var EE_Session $SSN
85
+	 */
86
+	public $SSN;
87
+
88
+	/**
89
+	 * @since 4.5.0
90
+	 * @var EE_Capabilities $CAP
91
+	 */
92
+	public $CAP;
93
+
94
+	/**
95
+	 * @since 4.9.0
96
+	 * @var EE_Message_Resource_Manager $MRM
97
+	 */
98
+	public $MRM;
99
+
100
+	/**
101
+	 * @var Registry $AssetsRegistry
102
+	 */
103
+	public $AssetsRegistry;
104
+
105
+	/**
106
+	 * StdClass object for holding addons which have registered themselves to work with EE core
107
+	 *
108
+	 * @var EE_Addon[] $addons
109
+	 */
110
+	public $addons;
111
+
112
+	/**
113
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
114
+	 *
115
+	 * @var EEM_Base[] $models
116
+	 */
117
+	public $models = array();
118
+
119
+	/**
120
+	 * @var EED_Module[] $modules
121
+	 */
122
+	public $modules;
123
+
124
+	/**
125
+	 * @var EES_Shortcode[] $shortcodes
126
+	 */
127
+	public $shortcodes;
128
+
129
+	/**
130
+	 * @var WP_Widget[] $widgets
131
+	 */
132
+	public $widgets;
133
+
134
+	/**
135
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
136
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
137
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
138
+	 * classnames (eg "EEM_Event")
139
+	 *
140
+	 * @var array $non_abstract_db_models
141
+	 */
142
+	public $non_abstract_db_models = array();
143
+
144
+	/**
145
+	 * internationalization for JS strings
146
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
147
+	 *    in js file:  var translatedString = eei18n.string_key;
148
+	 *
149
+	 * @var array $i18n_js_strings
150
+	 */
151
+	public static $i18n_js_strings = array();
152
+
153
+	/**
154
+	 * $main_file - path to espresso.php
155
+	 *
156
+	 * @var array $main_file
157
+	 */
158
+	public $main_file;
159
+
160
+	/**
161
+	 * array of ReflectionClass objects where the key is the class name
162
+	 *
163
+	 * @deprecated 4.9.62.p
164
+	 * @var ReflectionClass[] $_reflectors
165
+	 */
166
+	public $_reflectors;
167
+
168
+	/**
169
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
170
+	 *
171
+	 * @var boolean $_cache_on
172
+	 */
173
+	protected $_cache_on = true;
174
+
175
+	/**
176
+	 * @var ObjectIdentifier
177
+	 */
178
+	private $object_identifier;
179
+
180
+
181
+	/**
182
+	 * @singleton method used to instantiate class object
183
+	 * @param EE_Dependency_Map|null   $dependency_map
184
+	 * @param Mirror|null              $mirror
185
+	 * @param ClassInterfaceCache|null $class_cache
186
+	 * @param ObjectIdentifier|null    $object_identifier
187
+	 * @return EE_Registry instance
188
+	 */
189
+	public static function instance(
190
+		EE_Dependency_Map $dependency_map = null,
191
+		Mirror $mirror = null,
192
+		ClassInterfaceCache $class_cache = null,
193
+		ObjectIdentifier $object_identifier = null
194
+	) {
195
+		// check if class object is instantiated
196
+		if (
197
+			! self::$_instance instanceof EE_Registry
198
+			&& $dependency_map instanceof EE_Dependency_Map
199
+			&& $mirror instanceof Mirror
200
+			&& $class_cache instanceof ClassInterfaceCache
201
+			&& $object_identifier instanceof ObjectIdentifier
202
+		) {
203
+			self::$_instance = new self(
204
+				$dependency_map,
205
+				$mirror,
206
+				$class_cache,
207
+				$object_identifier
208
+			);
209
+		}
210
+		return self::$_instance;
211
+	}
212
+
213
+
214
+	/**
215
+	 * protected constructor to prevent direct creation
216
+	 *
217
+	 * @Constructor
218
+	 * @param  EE_Dependency_Map  $dependency_map
219
+	 * @param Mirror              $mirror
220
+	 * @param ClassInterfaceCache $class_cache
221
+	 * @param ObjectIdentifier    $object_identifier
222
+	 */
223
+	protected function __construct(
224
+		EE_Dependency_Map $dependency_map,
225
+		Mirror $mirror,
226
+		ClassInterfaceCache $class_cache,
227
+		ObjectIdentifier $object_identifier
228
+	) {
229
+		$this->_dependency_map = $dependency_map;
230
+		$this->mirror = $mirror;
231
+		$this->class_cache = $class_cache;
232
+		$this->object_identifier = $object_identifier;
233
+		// $registry_container = new RegistryContainer();
234
+		$this->LIB = new RegistryContainer();
235
+		$this->addons = new RegistryContainer();
236
+		$this->modules = new RegistryContainer();
237
+		$this->shortcodes = new RegistryContainer();
238
+		$this->widgets = new RegistryContainer();
239
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
240
+	}
241
+
242
+
243
+	/**
244
+	 * initialize
245
+	 *
246
+	 * @throws OutOfBoundsException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 * @throws ReflectionException
252
+	 */
253
+	public function initialize()
254
+	{
255
+		$this->_class_abbreviations = apply_filters(
256
+			'FHEE__EE_Registry____construct___class_abbreviations',
257
+			array(
258
+				'EE_Config'                                       => 'CFG',
259
+				'EE_Session'                                      => 'SSN',
260
+				'EE_Capabilities'                                 => 'CAP',
261
+				'EE_Cart'                                         => 'CART',
262
+				'EE_Network_Config'                               => 'NET_CFG',
263
+				'EE_Request_Handler'                              => 'REQ',
264
+				'EE_Message_Resource_Manager'                     => 'MRM',
265
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
266
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
267
+			)
268
+		);
269
+		$this->load_core('Base', array(), true);
270
+		// add our request and response objects to the cache
271
+		$request_loader = $this->_dependency_map->class_loader(
272
+			'EventEspresso\core\services\request\Request'
273
+		);
274
+		$this->_set_cached_class(
275
+			$request_loader(),
276
+			'EventEspresso\core\services\request\Request'
277
+		);
278
+		$response_loader = $this->_dependency_map->class_loader(
279
+			'EventEspresso\core\services\request\Response'
280
+		);
281
+		$this->_set_cached_class(
282
+			$response_loader(),
283
+			'EventEspresso\core\services\request\Response'
284
+		);
285
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
286
+	}
287
+
288
+
289
+	/**
290
+	 * @return void
291
+	 */
292
+	public function init()
293
+	{
294
+		// Get current page protocol
295
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
296
+		// Output admin-ajax.php URL with same protocol as current page
297
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
298
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
299
+	}
300
+
301
+
302
+	/**
303
+	 * localize_i18n_js_strings
304
+	 *
305
+	 * @return string
306
+	 */
307
+	public static function localize_i18n_js_strings()
308
+	{
309
+		$i18n_js_strings = (array) self::$i18n_js_strings;
310
+		foreach ($i18n_js_strings as $key => $value) {
311
+			if (is_scalar($value)) {
312
+				$i18n_js_strings[ $key ] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
313
+			}
314
+		}
315
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
316
+	}
317
+
318
+
319
+	/**
320
+	 * @param mixed string | EED_Module $module
321
+	 * @throws OutOfBoundsException
322
+	 * @throws InvalidArgumentException
323
+	 * @throws InvalidInterfaceException
324
+	 * @throws InvalidDataTypeException
325
+	 * @throws EE_Error
326
+	 * @throws ReflectionException
327
+	 */
328
+	public function add_module($module)
329
+	{
330
+		if ($module instanceof EED_Module) {
331
+			$module_class = get_class($module);
332
+			$this->modules->{$module_class} = $module;
333
+		} else {
334
+			if (! class_exists('EE_Module_Request_Router', false)) {
335
+				$this->load_core('Module_Request_Router');
336
+			}
337
+			EE_Module_Request_Router::module_factory($module);
338
+		}
339
+	}
340
+
341
+
342
+	/**
343
+	 * @param string $module_name
344
+	 * @return mixed EED_Module | NULL
345
+	 */
346
+	public function get_module($module_name = '')
347
+	{
348
+		return isset($this->modules->{$module_name})
349
+			? $this->modules->{$module_name}
350
+			: null;
351
+	}
352
+
353
+
354
+	/**
355
+	 * loads core classes - must be singletons
356
+	 *
357
+	 * @param string $class_name - simple class name ie: session
358
+	 * @param mixed  $arguments
359
+	 * @param bool   $load_only
360
+	 * @return mixed
361
+	 * @throws InvalidInterfaceException
362
+	 * @throws InvalidDataTypeException
363
+	 * @throws EE_Error
364
+	 * @throws ReflectionException
365
+	 * @throws InvalidArgumentException
366
+	 */
367
+	public function load_core($class_name, $arguments = array(), $load_only = false)
368
+	{
369
+		$core_paths = apply_filters(
370
+			'FHEE__EE_Registry__load_core__core_paths',
371
+			array(
372
+				EE_CORE,
373
+				EE_ADMIN,
374
+				EE_CPTS,
375
+				EE_CORE . 'data_migration_scripts/',
376
+				EE_CORE . 'capabilities/',
377
+				EE_CORE . 'request_stack/',
378
+				EE_CORE . 'middleware/',
379
+			)
380
+		);
381
+		// retrieve instantiated class
382
+		return $this->_load(
383
+			$core_paths,
384
+			'EE_',
385
+			$class_name,
386
+			'core',
387
+			$arguments,
388
+			false,
389
+			true,
390
+			$load_only
391
+		);
392
+	}
393
+
394
+
395
+	/**
396
+	 * loads service classes
397
+	 *
398
+	 * @param string $class_name - simple class name ie: session
399
+	 * @param mixed  $arguments
400
+	 * @param bool   $load_only
401
+	 * @return mixed
402
+	 * @throws InvalidInterfaceException
403
+	 * @throws InvalidDataTypeException
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 * @throws InvalidArgumentException
407
+	 */
408
+	public function load_service($class_name, $arguments = array(), $load_only = false)
409
+	{
410
+		$service_paths = apply_filters(
411
+			'FHEE__EE_Registry__load_service__service_paths',
412
+			array(
413
+				EE_CORE . 'services/',
414
+			)
415
+		);
416
+		// retrieve instantiated class
417
+		return $this->_load(
418
+			$service_paths,
419
+			'EE_',
420
+			$class_name,
421
+			'class',
422
+			$arguments,
423
+			false,
424
+			true,
425
+			$load_only
426
+		);
427
+	}
428
+
429
+
430
+	/**
431
+	 * loads data_migration_scripts
432
+	 *
433
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
434
+	 * @param mixed  $arguments
435
+	 * @return EE_Data_Migration_Script_Base|mixed
436
+	 * @throws InvalidInterfaceException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws EE_Error
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 */
442
+	public function load_dms($class_name, $arguments = array())
443
+	{
444
+		// retrieve instantiated class
445
+		return $this->_load(
446
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
447
+			'EE_DMS_',
448
+			$class_name,
449
+			'dms',
450
+			$arguments,
451
+			false,
452
+			false
453
+		);
454
+	}
455
+
456
+
457
+	/**
458
+	 * loads object creating classes - must be singletons
459
+	 *
460
+	 * @param string $class_name - simple class name ie: attendee
461
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
462
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
463
+	 *                           instantiate
464
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
465
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
466
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
467
+	 *                           (default)
468
+	 * @return EE_Base_Class | bool
469
+	 * @throws InvalidInterfaceException
470
+	 * @throws InvalidDataTypeException
471
+	 * @throws EE_Error
472
+	 * @throws ReflectionException
473
+	 * @throws InvalidArgumentException
474
+	 */
475
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
476
+	{
477
+		$paths = apply_filters(
478
+			'FHEE__EE_Registry__load_class__paths',
479
+			array(
480
+				EE_CORE,
481
+				EE_CLASSES,
482
+				EE_BUSINESS,
483
+			)
484
+		);
485
+		// retrieve instantiated class
486
+		return $this->_load(
487
+			$paths,
488
+			'EE_',
489
+			$class_name,
490
+			'class',
491
+			$arguments,
492
+			$from_db,
493
+			$cache,
494
+			$load_only
495
+		);
496
+	}
497
+
498
+
499
+	/**
500
+	 * loads helper classes - must be singletons
501
+	 *
502
+	 * @param string $class_name - simple class name ie: price
503
+	 * @param mixed  $arguments
504
+	 * @param bool   $load_only
505
+	 * @return EEH_Base | bool
506
+	 * @throws InvalidInterfaceException
507
+	 * @throws InvalidDataTypeException
508
+	 * @throws EE_Error
509
+	 * @throws ReflectionException
510
+	 * @throws InvalidArgumentException
511
+	 */
512
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
513
+	{
514
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
515
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
516
+		// retrieve instantiated class
517
+		return $this->_load(
518
+			$helper_paths,
519
+			'EEH_',
520
+			$class_name,
521
+			'helper',
522
+			$arguments,
523
+			false,
524
+			true,
525
+			$load_only
526
+		);
527
+	}
528
+
529
+
530
+	/**
531
+	 * loads core classes - must be singletons
532
+	 *
533
+	 * @param string $class_name - simple class name ie: session
534
+	 * @param mixed  $arguments
535
+	 * @param bool   $load_only
536
+	 * @param bool   $cache      whether to cache the object or not.
537
+	 * @return mixed
538
+	 * @throws InvalidInterfaceException
539
+	 * @throws InvalidDataTypeException
540
+	 * @throws EE_Error
541
+	 * @throws ReflectionException
542
+	 * @throws InvalidArgumentException
543
+	 */
544
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
545
+	{
546
+		$paths = array(
547
+			EE_LIBRARIES,
548
+			EE_LIBRARIES . 'messages/',
549
+			EE_LIBRARIES . 'shortcodes/',
550
+			EE_LIBRARIES . 'qtips/',
551
+			EE_LIBRARIES . 'payment_methods/',
552
+		);
553
+		// retrieve instantiated class
554
+		return $this->_load(
555
+			$paths,
556
+			'EE_',
557
+			$class_name,
558
+			'lib',
559
+			$arguments,
560
+			false,
561
+			$cache,
562
+			$load_only
563
+		);
564
+	}
565
+
566
+
567
+	/**
568
+	 * loads model classes - must be singletons
569
+	 *
570
+	 * @param string $class_name - simple class name ie: price
571
+	 * @param mixed  $arguments
572
+	 * @param bool   $load_only
573
+	 * @return EEM_Base | bool
574
+	 * @throws InvalidInterfaceException
575
+	 * @throws InvalidDataTypeException
576
+	 * @throws EE_Error
577
+	 * @throws ReflectionException
578
+	 * @throws InvalidArgumentException
579
+	 */
580
+	public function load_model($class_name, $arguments = array(), $load_only = false)
581
+	{
582
+		$paths = apply_filters(
583
+			'FHEE__EE_Registry__load_model__paths',
584
+			array(
585
+				EE_MODELS,
586
+				EE_CORE,
587
+			)
588
+		);
589
+		// retrieve instantiated class
590
+		return $this->_load(
591
+			$paths,
592
+			'EEM_',
593
+			$class_name,
594
+			'model',
595
+			$arguments,
596
+			false,
597
+			true,
598
+			$load_only
599
+		);
600
+	}
601
+
602
+
603
+	/**
604
+	 * loads model classes - must be singletons
605
+	 *
606
+	 * @param string $class_name - simple class name ie: price
607
+	 * @param mixed  $arguments
608
+	 * @param bool   $load_only
609
+	 * @return mixed | bool
610
+	 * @throws InvalidInterfaceException
611
+	 * @throws InvalidDataTypeException
612
+	 * @throws EE_Error
613
+	 * @throws ReflectionException
614
+	 * @throws InvalidArgumentException
615
+	 */
616
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
617
+	{
618
+		$paths = array(
619
+			EE_MODELS . 'fields/',
620
+			EE_MODELS . 'helpers/',
621
+			EE_MODELS . 'relations/',
622
+			EE_MODELS . 'strategies/',
623
+		);
624
+		// retrieve instantiated class
625
+		return $this->_load(
626
+			$paths,
627
+			'EE_',
628
+			$class_name,
629
+			'',
630
+			$arguments,
631
+			false,
632
+			true,
633
+			$load_only
634
+		);
635
+	}
636
+
637
+
638
+	/**
639
+	 * Determines if $model_name is the name of an actual EE model.
640
+	 *
641
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
642
+	 * @return boolean
643
+	 */
644
+	public function is_model_name($model_name)
645
+	{
646
+		return isset($this->models[ $model_name ]);
647
+	}
648
+
649
+
650
+	/**
651
+	 * generic class loader
652
+	 *
653
+	 * @param string $path_to_file - directory path to file location, not including filename
654
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
655
+	 * @param string $type         - file type - core? class? helper? model?
656
+	 * @param mixed  $arguments
657
+	 * @param bool   $load_only
658
+	 * @return mixed
659
+	 * @throws InvalidInterfaceException
660
+	 * @throws InvalidDataTypeException
661
+	 * @throws EE_Error
662
+	 * @throws ReflectionException
663
+	 * @throws InvalidArgumentException
664
+	 */
665
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
666
+	{
667
+		// retrieve instantiated class
668
+		return $this->_load(
669
+			$path_to_file,
670
+			'',
671
+			$file_name,
672
+			$type,
673
+			$arguments,
674
+			false,
675
+			true,
676
+			$load_only
677
+		);
678
+	}
679
+
680
+
681
+	/**
682
+	 * @param string $path_to_file - directory path to file location, not including filename
683
+	 * @param string $class_name   - full class name  ie:  My_Class
684
+	 * @param string $type         - file type - core? class? helper? model?
685
+	 * @param mixed  $arguments
686
+	 * @param bool   $load_only
687
+	 * @return bool|EE_Addon|object
688
+	 * @throws InvalidInterfaceException
689
+	 * @throws InvalidDataTypeException
690
+	 * @throws EE_Error
691
+	 * @throws ReflectionException
692
+	 * @throws InvalidArgumentException
693
+	 */
694
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
695
+	{
696
+		// retrieve instantiated class
697
+		return $this->_load(
698
+			$path_to_file,
699
+			'addon',
700
+			$class_name,
701
+			$type,
702
+			$arguments,
703
+			false,
704
+			true,
705
+			$load_only
706
+		);
707
+	}
708
+
709
+
710
+	/**
711
+	 * instantiates, caches, and automatically resolves dependencies
712
+	 * for classes that use a Fully Qualified Class Name.
713
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
714
+	 * then you need to use one of the existing load_*() methods
715
+	 * which can resolve the classname and filepath from the passed arguments
716
+	 *
717
+	 * @param bool|string $class_name   Fully Qualified Class Name
718
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
719
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
720
+	 * @param bool        $from_db      some classes are instantiated from the db
721
+	 *                                  and thus call a different method to instantiate
722
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
723
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
724
+	 * @return bool|null|mixed          null = failure to load or instantiate class object.
725
+	 *                                  object = class loaded and instantiated successfully.
726
+	 *                                  bool = fail or success when $load_only is true
727
+	 * @throws InvalidInterfaceException
728
+	 * @throws InvalidDataTypeException
729
+	 * @throws EE_Error
730
+	 * @throws ReflectionException
731
+	 * @throws InvalidArgumentException
732
+	 */
733
+	public function create(
734
+		$class_name = false,
735
+		$arguments = array(),
736
+		$cache = false,
737
+		$from_db = false,
738
+		$load_only = false,
739
+		$addon = false
740
+	) {
741
+		$class_name = ltrim($class_name, '\\');
742
+		$class_name = $this->class_cache->getFqnForAlias($class_name);
743
+		$class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
744
+		// if a non-FQCN was passed, then
745
+		// verifyClassExists() might return an object
746
+		// or it could return null if the class just could not be found anywhere
747
+		if ($class_exists instanceof $class_name || $class_exists === null) {
748
+			// either way, return the results
749
+			return $class_exists;
750
+		}
751
+		$class_name = $class_exists;
752
+		// if we're only loading the class and it already exists, then let's just return true immediately
753
+		if ($load_only) {
754
+			return true;
755
+		}
756
+		$addon = $addon ? 'addon' : '';
757
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
758
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
759
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
760
+		if ($this->_cache_on && $cache && ! $load_only) {
761
+			// return object if it's already cached
762
+			$cached_class = $this->_get_cached_class($class_name, $addon, $arguments);
763
+			if ($cached_class !== null) {
764
+				return $cached_class;
765
+			}
766
+		}// obtain the loader method from the dependency map
767
+		$loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
768
+		if ($loader instanceof Closure) {
769
+			$class_obj = $loader($arguments);
770
+		} else {
771
+			if ($loader && method_exists($this, $loader)) {
772
+				$class_obj = $this->{$loader}($class_name, $arguments);
773
+			} else {
774
+				$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
775
+			}
776
+		}
777
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
778
+			// save it for later... kinda like gum  { : $
779
+			$this->_set_cached_class(
780
+				$class_obj,
781
+				$class_name,
782
+				$addon,
783
+				$from_db,
784
+				$arguments
785
+			);
786
+		}
787
+		$this->_cache_on = true;
788
+		return $class_obj;
789
+	}
790
+
791
+
792
+	/**
793
+	 * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
794
+	 *
795
+	 * @param string|object $class_name
796
+	 * @param array         $arguments
797
+	 * @param int           $attempt
798
+	 * @return mixed
799
+	 */
800
+	private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1)
801
+	{
802
+		if (is_object($class_name) || class_exists($class_name)) {
803
+			return $class_name;
804
+		}
805
+		switch ($attempt) {
806
+			case 1:
807
+				// if it's a FQCN then maybe the class is registered with a preceding \
808
+				$class_name = strpos($class_name, '\\') !== false
809
+					? '\\' . ltrim($class_name, '\\')
810
+					: $class_name;
811
+				break;
812
+			case 2:
813
+				//
814
+				$loader = $this->_dependency_map->class_loader($class_name);
815
+				if ($loader && method_exists($this, $loader)) {
816
+					return $this->{$loader}($class_name, $arguments);
817
+				}
818
+				break;
819
+			case 3:
820
+			default:
821
+				return null;
822
+		}
823
+		$attempt++;
824
+		return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
825
+	}
826
+
827
+
828
+	/**
829
+	 * instantiates, caches, and injects dependencies for classes
830
+	 *
831
+	 * @param array       $file_paths   an array of paths to folders to look in
832
+	 * @param string      $class_prefix EE  or EEM or... ???
833
+	 * @param bool|string $class_name   $class name
834
+	 * @param string      $type         file type - core? class? helper? model?
835
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
836
+	 * @param bool        $from_db      some classes are instantiated from the db
837
+	 *                                  and thus call a different method to instantiate
838
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
839
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
840
+	 * @return bool|null|object null = failure to load or instantiate class object.
841
+	 *                                  object = class loaded and instantiated successfully.
842
+	 *                                  bool = fail or success when $load_only is true
843
+	 * @throws EE_Error
844
+	 * @throws ReflectionException
845
+	 * @throws InvalidInterfaceException
846
+	 * @throws InvalidDataTypeException
847
+	 * @throws InvalidArgumentException
848
+	 */
849
+	protected function _load(
850
+		$file_paths = array(),
851
+		$class_prefix = 'EE_',
852
+		$class_name = false,
853
+		$type = 'class',
854
+		$arguments = array(),
855
+		$from_db = false,
856
+		$cache = true,
857
+		$load_only = false
858
+	) {
859
+		$class_name = ltrim($class_name, '\\');
860
+		// strip php file extension
861
+		$class_name = str_replace('.php', '', trim($class_name));
862
+		// does the class have a prefix ?
863
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
864
+			// make sure $class_prefix is uppercase
865
+			$class_prefix = strtoupper(trim($class_prefix));
866
+			// add class prefix ONCE!!!
867
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
868
+		}
869
+		$class_name = $this->class_cache->getFqnForAlias($class_name);
870
+		$class_exists = class_exists($class_name, false);
871
+		// if we're only loading the class and it already exists, then let's just return true immediately
872
+		if ($load_only && $class_exists) {
873
+			return true;
874
+		}
875
+		$arguments = is_array($arguments) ? $arguments : array($arguments);
876
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
877
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
878
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
879
+		if ($this->_cache_on && $cache && ! $load_only) {
880
+			// return object if it's already cached
881
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix, $arguments);
882
+			if ($cached_class !== null) {
883
+				return $cached_class;
884
+			}
885
+		}
886
+		// if the class doesn't already exist.. then we need to try and find the file and load it
887
+		if (! $class_exists) {
888
+			// get full path to file
889
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
890
+			// load the file
891
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
892
+			// if we are only loading a file but NOT instantiating an object
893
+			// then return boolean for whether class was loaded or not
894
+			if ($load_only) {
895
+				return $loaded;
896
+			}
897
+			// if an object was expected but loading failed, then return nothing
898
+			if (! $loaded) {
899
+				return null;
900
+			}
901
+		}
902
+		// instantiate the requested object
903
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
904
+		if ($this->_cache_on && $cache) {
905
+			// save it for later... kinda like gum  { : $
906
+			$this->_set_cached_class(
907
+				$class_obj,
908
+				$class_name,
909
+				$class_prefix,
910
+				$from_db,
911
+				$arguments
912
+			);
913
+		}
914
+		$this->_cache_on = true;
915
+		return $class_obj;
916
+	}
917
+
918
+
919
+	/**
920
+	 * @param string $class_name
921
+	 * @param string $default have to specify something, but not anything that will conflict
922
+	 * @return mixed|string
923
+	 */
924
+	protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
925
+	{
926
+		return isset($this->_class_abbreviations[ $class_name ])
927
+			? $this->_class_abbreviations[ $class_name ]
928
+			: $default;
929
+	}
930
+
931
+
932
+	/**
933
+	 * attempts to find a cached version of the requested class
934
+	 * by looking in the following places:
935
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
936
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
937
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
938
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
939
+	 *
940
+	 * @param string $class_name
941
+	 * @param string $class_prefix
942
+	 * @param array  $arguments
943
+	 * @return mixed
944
+	 */
945
+	protected function _get_cached_class(
946
+		$class_name,
947
+		$class_prefix = '',
948
+		$arguments = array()
949
+	) {
950
+		if ($class_name === 'EE_Registry') {
951
+			return $this;
952
+		}
953
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
954
+		// check if class has already been loaded, and return it if it has been
955
+		if (isset($this->{$class_abbreviation})) {
956
+			return $this->{$class_abbreviation};
957
+		}
958
+		$class_name = str_replace('\\', '_', $class_name);
959
+		if (isset($this->{$class_name})) {
960
+			return $this->{$class_name};
961
+		}
962
+		if ($class_prefix === 'addon' && isset($this->addons->{$class_name})) {
963
+			return $this->addons->{$class_name};
964
+		}
965
+		$object_identifier = $this->object_identifier->getIdentifier($class_name, $arguments);
966
+		if (isset($this->LIB->{$object_identifier})) {
967
+			return $this->LIB->{$object_identifier};
968
+		}
969
+		foreach ($this->LIB as $key => $object) {
970
+			if (
971 971
 // request does not contain new arguments and therefore no args identifier
972
-                ! $this->object_identifier->hasArguments($object_identifier)
973
-                // but previously cached class with args was found
974
-                && $this->object_identifier->fqcnMatchesObjectIdentifier($class_name, $key)
975
-            ) {
976
-                return $object;
977
-            }
978
-        }
979
-        return null;
980
-    }
981
-
982
-
983
-    /**
984
-     * removes a cached version of the requested class
985
-     *
986
-     * @param string  $class_name
987
-     * @param boolean $addon
988
-     * @param array   $arguments
989
-     * @return boolean
990
-     */
991
-    public function clear_cached_class(
992
-        $class_name,
993
-        $addon = false,
994
-        $arguments = array()
995
-    ) {
996
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
997
-        // check if class has already been loaded, and return it if it has been
998
-        if (isset($this->{$class_abbreviation})) {
999
-            $this->{$class_abbreviation} = null;
1000
-            return true;
1001
-        }
1002
-        $class_name = str_replace('\\', '_', $class_name);
1003
-        if (isset($this->{$class_name})) {
1004
-            $this->{$class_name} = null;
1005
-            return true;
1006
-        }
1007
-        if ($addon && isset($this->addons->{$class_name})) {
1008
-            unset($this->addons->{$class_name});
1009
-            return true;
1010
-        }
1011
-        $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1012
-        if (isset($this->LIB->{$class_name})) {
1013
-            unset($this->LIB->{$class_name});
1014
-            return true;
1015
-        }
1016
-        return false;
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * _set_cached_class
1022
-     * attempts to cache the instantiated class locally
1023
-     * in one of the following places, in the following order:
1024
-     *        $this->{class_abbreviation}   ie:    $this->CART
1025
-     *        $this->{$class_name}          ie:    $this->Some_Class
1026
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1027
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1028
-     *
1029
-     * @param object $class_obj
1030
-     * @param string $class_name
1031
-     * @param string $class_prefix
1032
-     * @param bool   $from_db
1033
-     * @param array  $arguments
1034
-     * @return void
1035
-     */
1036
-    protected function _set_cached_class(
1037
-        $class_obj,
1038
-        $class_name,
1039
-        $class_prefix = '',
1040
-        $from_db = false,
1041
-        $arguments = array()
1042
-    ) {
1043
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1044
-            return;
1045
-        }
1046
-        // return newly instantiated class
1047
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1048
-        if ($class_abbreviation) {
1049
-            $this->{$class_abbreviation} = $class_obj;
1050
-            return;
1051
-        }
1052
-        $class_name = str_replace('\\', '_', $class_name);
1053
-        if (property_exists($this, $class_name)) {
1054
-            $this->{$class_name} = $class_obj;
1055
-            return;
1056
-        }
1057
-        if ($class_prefix === 'addon') {
1058
-            $this->addons->{$class_name} = $class_obj;
1059
-            return;
1060
-        }
1061
-        if (! $from_db) {
1062
-            $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1063
-            $this->LIB->{$class_name} = $class_obj;
1064
-        }
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * attempts to find a full valid filepath for the requested class.
1070
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
1071
-     * then returns that path if the target file has been found and is readable
1072
-     *
1073
-     * @param string $class_name
1074
-     * @param string $type
1075
-     * @param array  $file_paths
1076
-     * @return string | bool
1077
-     */
1078
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
1079
-    {
1080
-        // make sure $file_paths is an array
1081
-        $file_paths = is_array($file_paths)
1082
-            ? $file_paths
1083
-            : array($file_paths);
1084
-        // cycle thru paths
1085
-        foreach ($file_paths as $key => $file_path) {
1086
-            // convert all separators to proper /, if no filepath, then use EE_CLASSES
1087
-            $file_path = $file_path
1088
-                ? str_replace(array('/', '\\'), '/', $file_path)
1089
-                : EE_CLASSES;
1090
-            // prep file type
1091
-            $type = ! empty($type)
1092
-                ? trim($type, '.') . '.'
1093
-                : '';
1094
-            // build full file path
1095
-            $file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1096
-            // does the file exist and can be read ?
1097
-            if (is_readable($file_paths[ $key ])) {
1098
-                return $file_paths[ $key ];
1099
-            }
1100
-        }
1101
-        return false;
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * basically just performs a require_once()
1107
-     * but with some error handling
1108
-     *
1109
-     * @param  string $path
1110
-     * @param  string $class_name
1111
-     * @param  string $type
1112
-     * @param  array  $file_paths
1113
-     * @return bool
1114
-     * @throws EE_Error
1115
-     * @throws ReflectionException
1116
-     */
1117
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
1118
-    {
1119
-        $this->resolve_legacy_class_parent($class_name);
1120
-        // don't give up! you gotta...
1121
-        try {
1122
-            // does the file exist and can it be read ?
1123
-            if (! $path) {
1124
-                // just in case the file has already been autoloaded,
1125
-                // but discrepancies in the naming schema are preventing it from
1126
-                // being loaded via one of the EE_Registry::load_*() methods,
1127
-                // then let's try one last hail mary before throwing an exception
1128
-                // and call class_exists() again, but with autoloading turned ON
1129
-                if (class_exists($class_name)) {
1130
-                    return true;
1131
-                }
1132
-                // so sorry, can't find the file
1133
-                throw new EE_Error(
1134
-                    sprintf(
1135
-                        esc_html__(
1136
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
1137
-                            'event_espresso'
1138
-                        ),
1139
-                        trim($type, '.'),
1140
-                        $class_name,
1141
-                        '<br />' . implode(',<br />', $file_paths)
1142
-                    )
1143
-                );
1144
-            }
1145
-            // get the file
1146
-            require_once($path);
1147
-            // if the class isn't already declared somewhere
1148
-            if (class_exists($class_name, false) === false) {
1149
-                // so sorry, not a class
1150
-                throw new EE_Error(
1151
-                    sprintf(
1152
-                        esc_html__(
1153
-                            'The %s file %s does not appear to contain the %s Class.',
1154
-                            'event_espresso'
1155
-                        ),
1156
-                        $type,
1157
-                        $path,
1158
-                        $class_name
1159
-                    )
1160
-                );
1161
-            }
1162
-        } catch (EE_Error $e) {
1163
-            $e->get_error();
1164
-            return false;
1165
-        }
1166
-        return true;
1167
-    }
1168
-
1169
-
1170
-    /**
1171
-     * Some of our legacy classes that extended a parent class would simply use a require() statement
1172
-     * before their class declaration in order to ensure that the parent class was loaded.
1173
-     * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1174
-     * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1175
-     *
1176
-     * @param string $class_name
1177
-     */
1178
-    protected function resolve_legacy_class_parent($class_name = '')
1179
-    {
1180
-        try {
1181
-            $legacy_parent_class_map = array(
1182
-                'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1183
-            );
1184
-            if (isset($legacy_parent_class_map[ $class_name ])) {
1185
-                require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1186
-            }
1187
-        } catch (Exception $exception) {
1188
-        }
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * _create_object
1194
-     * Attempts to instantiate the requested class via any of the
1195
-     * commonly used instantiation methods employed throughout EE.
1196
-     * The priority for instantiation is as follows:
1197
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1198
-     *        - model objects via their 'new_instance_from_db' method
1199
-     *        - model objects via their 'new_instance' method
1200
-     *        - "singleton" classes" via their 'instance' method
1201
-     *    - standard instantiable classes via their __constructor
1202
-     * Prior to instantiation, if the classname exists in the dependency_map,
1203
-     * then the constructor for the requested class will be examined to determine
1204
-     * if any dependencies exist, and if they can be injected.
1205
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1206
-     *
1207
-     * @param string $class_name
1208
-     * @param array  $arguments
1209
-     * @param string $type
1210
-     * @param bool   $from_db
1211
-     * @return null|object|bool
1212
-     * @throws InvalidArgumentException
1213
-     * @throws InvalidInterfaceException
1214
-     * @throws EE_Error
1215
-     * @throws ReflectionException
1216
-     * @throws InvalidDataTypeException
1217
-     */
1218
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1219
-    {
1220
-        // create reflection
1221
-        $reflector = $this->mirror->getReflectionClass($class_name);
1222
-        // make sure arguments are an array
1223
-        $arguments = is_array($arguments)
1224
-            ? $arguments
1225
-            : array($arguments);
1226
-        // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1227
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
1228
-        $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1229
-            ? $arguments
1230
-            : array($arguments);
1231
-        // attempt to inject dependencies ?
1232
-        if ($this->_dependency_map->has($class_name)) {
1233
-            $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1234
-        }
1235
-        // instantiate the class if possible
1236
-        if ($reflector->isAbstract()) {
1237
-            // nothing to instantiate, loading file was enough
1238
-            // does not throw an exception so $instantiation_mode is unused
1239
-            // $instantiation_mode = "1) no constructor abstract class";
1240
-            return true;
1241
-        }
1242
-        if (
1243
-            empty($arguments)
1244
-            && $this->mirror->getConstructorFromReflection($reflector) === null
1245
-            && $reflector->isInstantiable()
1246
-        ) {
1247
-            // no constructor = static methods only... nothing to instantiate, loading file was enough
1248
-            // $instantiation_mode = "2) no constructor but instantiable";
1249
-            return $reflector->newInstance();
1250
-        }
1251
-        if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1252
-            // $instantiation_mode = "3) new_instance_from_db()";
1253
-            return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1254
-        }
1255
-        if (method_exists($class_name, 'new_instance')) {
1256
-            // $instantiation_mode = "4) new_instance()";
1257
-            return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1258
-        }
1259
-        if (method_exists($class_name, 'instance')) {
1260
-            // $instantiation_mode = "5) instance()";
1261
-            return call_user_func_array(array($class_name, 'instance'), $arguments);
1262
-        }
1263
-        if ($reflector->isInstantiable()) {
1264
-            $args_passed_count = count($arguments);
1265
-            $args_required_count = count($this->mirror->getRequiredParameters($class_name));
1266
-            if ($args_passed_count < $args_required_count) {
1267
-                throw new RuntimeException(
1268
-                    sprintf(
1269
-                        __(
1270
-                            'Invalid arguments supplied for the %1$s class, %2$s were required but %3$s were passed.',
1271
-                            'event_espresso'
1272
-                        ),
1273
-                        $class_name,
1274
-                        $args_required_count,
1275
-                        $args_passed_count
1276
-                    )
1277
-                );
1278
-            }
1279
-            // $instantiation_mode = "6) constructor";
1280
-            return $reflector->newInstanceArgs($arguments);
1281
-        }
1282
-        // heh ? something's not right !
1283
-        throw new EE_Error(
1284
-            sprintf(
1285
-                __('The %s file %s could not be instantiated.', 'event_espresso'),
1286
-                $type,
1287
-                $class_name
1288
-            )
1289
-        );
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1295
-     * @param array $array
1296
-     * @return bool
1297
-     */
1298
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1299
-    {
1300
-        return ! empty($array)
1301
-            ? array_keys($array) === range(0, count($array) - 1)
1302
-            : true;
1303
-    }
1304
-
1305
-
1306
-    /**
1307
-     * _resolve_dependencies
1308
-     * examines the constructor for the requested class to determine
1309
-     * if any dependencies exist, and if they can be injected.
1310
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1311
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1312
-     * For example:
1313
-     *        if attempting to load a class "Foo" with the following constructor:
1314
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1315
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1316
-     *        but only IF they are NOT already present in the incoming arguments array,
1317
-     *        and the correct classes can be loaded
1318
-     *
1319
-     * @param ReflectionClass $reflector
1320
-     * @param string          $class_name
1321
-     * @param array           $arguments
1322
-     * @return array
1323
-     * @throws InvalidArgumentException
1324
-     * @throws InvalidDataTypeException
1325
-     * @throws InvalidInterfaceException
1326
-     * @throws ReflectionException
1327
-     */
1328
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, array $arguments = array())
1329
-    {
1330
-        // let's examine the constructor
1331
-        $constructor = $this->mirror->getConstructorFromReflection($reflector);
1332
-        // whu? huh? nothing?
1333
-        if (! $constructor) {
1334
-            return $arguments;
1335
-        }
1336
-        // get constructor parameters
1337
-        $params = $this->mirror->getParametersFromReflection($reflector);
1338
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1339
-        $argument_keys = array_keys($arguments);
1340
-        // now loop thru all of the constructors expected parameters
1341
-        foreach ($params as $index => $param) {
1342
-            try {
1343
-                // is this a dependency for a specific class ?
1344
-                $param_class = $this->mirror->getParameterClassName($param, $class_name, $index);
1345
-            } catch (ReflectionException $exception) {
1346
-                // uh-oh... most likely a legacy class that has not been autoloaded
1347
-                // let's try to derive the classname from what we have now
1348
-                // and hope that the property var name is close to the class name
1349
-                $param_class = $param->getName();
1350
-                $param_class = str_replace('_', ' ', $param_class);
1351
-                $param_class = ucwords($param_class);
1352
-                $param_class = str_replace(' ', '_', $param_class);
1353
-            }
1354
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1355
-            $param_class = $this->class_cache->isAlias($param_class, $class_name)
1356
-                ? $this->class_cache->getFqnForAlias($param_class, $class_name)
1357
-                : $param_class;
1358
-            if (
972
+				! $this->object_identifier->hasArguments($object_identifier)
973
+				// but previously cached class with args was found
974
+				&& $this->object_identifier->fqcnMatchesObjectIdentifier($class_name, $key)
975
+			) {
976
+				return $object;
977
+			}
978
+		}
979
+		return null;
980
+	}
981
+
982
+
983
+	/**
984
+	 * removes a cached version of the requested class
985
+	 *
986
+	 * @param string  $class_name
987
+	 * @param boolean $addon
988
+	 * @param array   $arguments
989
+	 * @return boolean
990
+	 */
991
+	public function clear_cached_class(
992
+		$class_name,
993
+		$addon = false,
994
+		$arguments = array()
995
+	) {
996
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
997
+		// check if class has already been loaded, and return it if it has been
998
+		if (isset($this->{$class_abbreviation})) {
999
+			$this->{$class_abbreviation} = null;
1000
+			return true;
1001
+		}
1002
+		$class_name = str_replace('\\', '_', $class_name);
1003
+		if (isset($this->{$class_name})) {
1004
+			$this->{$class_name} = null;
1005
+			return true;
1006
+		}
1007
+		if ($addon && isset($this->addons->{$class_name})) {
1008
+			unset($this->addons->{$class_name});
1009
+			return true;
1010
+		}
1011
+		$class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1012
+		if (isset($this->LIB->{$class_name})) {
1013
+			unset($this->LIB->{$class_name});
1014
+			return true;
1015
+		}
1016
+		return false;
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * _set_cached_class
1022
+	 * attempts to cache the instantiated class locally
1023
+	 * in one of the following places, in the following order:
1024
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1025
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1026
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1027
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1028
+	 *
1029
+	 * @param object $class_obj
1030
+	 * @param string $class_name
1031
+	 * @param string $class_prefix
1032
+	 * @param bool   $from_db
1033
+	 * @param array  $arguments
1034
+	 * @return void
1035
+	 */
1036
+	protected function _set_cached_class(
1037
+		$class_obj,
1038
+		$class_name,
1039
+		$class_prefix = '',
1040
+		$from_db = false,
1041
+		$arguments = array()
1042
+	) {
1043
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1044
+			return;
1045
+		}
1046
+		// return newly instantiated class
1047
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1048
+		if ($class_abbreviation) {
1049
+			$this->{$class_abbreviation} = $class_obj;
1050
+			return;
1051
+		}
1052
+		$class_name = str_replace('\\', '_', $class_name);
1053
+		if (property_exists($this, $class_name)) {
1054
+			$this->{$class_name} = $class_obj;
1055
+			return;
1056
+		}
1057
+		if ($class_prefix === 'addon') {
1058
+			$this->addons->{$class_name} = $class_obj;
1059
+			return;
1060
+		}
1061
+		if (! $from_db) {
1062
+			$class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1063
+			$this->LIB->{$class_name} = $class_obj;
1064
+		}
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * attempts to find a full valid filepath for the requested class.
1070
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
1071
+	 * then returns that path if the target file has been found and is readable
1072
+	 *
1073
+	 * @param string $class_name
1074
+	 * @param string $type
1075
+	 * @param array  $file_paths
1076
+	 * @return string | bool
1077
+	 */
1078
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
1079
+	{
1080
+		// make sure $file_paths is an array
1081
+		$file_paths = is_array($file_paths)
1082
+			? $file_paths
1083
+			: array($file_paths);
1084
+		// cycle thru paths
1085
+		foreach ($file_paths as $key => $file_path) {
1086
+			// convert all separators to proper /, if no filepath, then use EE_CLASSES
1087
+			$file_path = $file_path
1088
+				? str_replace(array('/', '\\'), '/', $file_path)
1089
+				: EE_CLASSES;
1090
+			// prep file type
1091
+			$type = ! empty($type)
1092
+				? trim($type, '.') . '.'
1093
+				: '';
1094
+			// build full file path
1095
+			$file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1096
+			// does the file exist and can be read ?
1097
+			if (is_readable($file_paths[ $key ])) {
1098
+				return $file_paths[ $key ];
1099
+			}
1100
+		}
1101
+		return false;
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * basically just performs a require_once()
1107
+	 * but with some error handling
1108
+	 *
1109
+	 * @param  string $path
1110
+	 * @param  string $class_name
1111
+	 * @param  string $type
1112
+	 * @param  array  $file_paths
1113
+	 * @return bool
1114
+	 * @throws EE_Error
1115
+	 * @throws ReflectionException
1116
+	 */
1117
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
1118
+	{
1119
+		$this->resolve_legacy_class_parent($class_name);
1120
+		// don't give up! you gotta...
1121
+		try {
1122
+			// does the file exist and can it be read ?
1123
+			if (! $path) {
1124
+				// just in case the file has already been autoloaded,
1125
+				// but discrepancies in the naming schema are preventing it from
1126
+				// being loaded via one of the EE_Registry::load_*() methods,
1127
+				// then let's try one last hail mary before throwing an exception
1128
+				// and call class_exists() again, but with autoloading turned ON
1129
+				if (class_exists($class_name)) {
1130
+					return true;
1131
+				}
1132
+				// so sorry, can't find the file
1133
+				throw new EE_Error(
1134
+					sprintf(
1135
+						esc_html__(
1136
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
1137
+							'event_espresso'
1138
+						),
1139
+						trim($type, '.'),
1140
+						$class_name,
1141
+						'<br />' . implode(',<br />', $file_paths)
1142
+					)
1143
+				);
1144
+			}
1145
+			// get the file
1146
+			require_once($path);
1147
+			// if the class isn't already declared somewhere
1148
+			if (class_exists($class_name, false) === false) {
1149
+				// so sorry, not a class
1150
+				throw new EE_Error(
1151
+					sprintf(
1152
+						esc_html__(
1153
+							'The %s file %s does not appear to contain the %s Class.',
1154
+							'event_espresso'
1155
+						),
1156
+						$type,
1157
+						$path,
1158
+						$class_name
1159
+					)
1160
+				);
1161
+			}
1162
+		} catch (EE_Error $e) {
1163
+			$e->get_error();
1164
+			return false;
1165
+		}
1166
+		return true;
1167
+	}
1168
+
1169
+
1170
+	/**
1171
+	 * Some of our legacy classes that extended a parent class would simply use a require() statement
1172
+	 * before their class declaration in order to ensure that the parent class was loaded.
1173
+	 * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1174
+	 * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1175
+	 *
1176
+	 * @param string $class_name
1177
+	 */
1178
+	protected function resolve_legacy_class_parent($class_name = '')
1179
+	{
1180
+		try {
1181
+			$legacy_parent_class_map = array(
1182
+				'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1183
+			);
1184
+			if (isset($legacy_parent_class_map[ $class_name ])) {
1185
+				require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1186
+			}
1187
+		} catch (Exception $exception) {
1188
+		}
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * _create_object
1194
+	 * Attempts to instantiate the requested class via any of the
1195
+	 * commonly used instantiation methods employed throughout EE.
1196
+	 * The priority for instantiation is as follows:
1197
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1198
+	 *        - model objects via their 'new_instance_from_db' method
1199
+	 *        - model objects via their 'new_instance' method
1200
+	 *        - "singleton" classes" via their 'instance' method
1201
+	 *    - standard instantiable classes via their __constructor
1202
+	 * Prior to instantiation, if the classname exists in the dependency_map,
1203
+	 * then the constructor for the requested class will be examined to determine
1204
+	 * if any dependencies exist, and if they can be injected.
1205
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1206
+	 *
1207
+	 * @param string $class_name
1208
+	 * @param array  $arguments
1209
+	 * @param string $type
1210
+	 * @param bool   $from_db
1211
+	 * @return null|object|bool
1212
+	 * @throws InvalidArgumentException
1213
+	 * @throws InvalidInterfaceException
1214
+	 * @throws EE_Error
1215
+	 * @throws ReflectionException
1216
+	 * @throws InvalidDataTypeException
1217
+	 */
1218
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1219
+	{
1220
+		// create reflection
1221
+		$reflector = $this->mirror->getReflectionClass($class_name);
1222
+		// make sure arguments are an array
1223
+		$arguments = is_array($arguments)
1224
+			? $arguments
1225
+			: array($arguments);
1226
+		// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1227
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
1228
+		$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1229
+			? $arguments
1230
+			: array($arguments);
1231
+		// attempt to inject dependencies ?
1232
+		if ($this->_dependency_map->has($class_name)) {
1233
+			$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1234
+		}
1235
+		// instantiate the class if possible
1236
+		if ($reflector->isAbstract()) {
1237
+			// nothing to instantiate, loading file was enough
1238
+			// does not throw an exception so $instantiation_mode is unused
1239
+			// $instantiation_mode = "1) no constructor abstract class";
1240
+			return true;
1241
+		}
1242
+		if (
1243
+			empty($arguments)
1244
+			&& $this->mirror->getConstructorFromReflection($reflector) === null
1245
+			&& $reflector->isInstantiable()
1246
+		) {
1247
+			// no constructor = static methods only... nothing to instantiate, loading file was enough
1248
+			// $instantiation_mode = "2) no constructor but instantiable";
1249
+			return $reflector->newInstance();
1250
+		}
1251
+		if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1252
+			// $instantiation_mode = "3) new_instance_from_db()";
1253
+			return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1254
+		}
1255
+		if (method_exists($class_name, 'new_instance')) {
1256
+			// $instantiation_mode = "4) new_instance()";
1257
+			return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1258
+		}
1259
+		if (method_exists($class_name, 'instance')) {
1260
+			// $instantiation_mode = "5) instance()";
1261
+			return call_user_func_array(array($class_name, 'instance'), $arguments);
1262
+		}
1263
+		if ($reflector->isInstantiable()) {
1264
+			$args_passed_count = count($arguments);
1265
+			$args_required_count = count($this->mirror->getRequiredParameters($class_name));
1266
+			if ($args_passed_count < $args_required_count) {
1267
+				throw new RuntimeException(
1268
+					sprintf(
1269
+						__(
1270
+							'Invalid arguments supplied for the %1$s class, %2$s were required but %3$s were passed.',
1271
+							'event_espresso'
1272
+						),
1273
+						$class_name,
1274
+						$args_required_count,
1275
+						$args_passed_count
1276
+					)
1277
+				);
1278
+			}
1279
+			// $instantiation_mode = "6) constructor";
1280
+			return $reflector->newInstanceArgs($arguments);
1281
+		}
1282
+		// heh ? something's not right !
1283
+		throw new EE_Error(
1284
+			sprintf(
1285
+				__('The %s file %s could not be instantiated.', 'event_espresso'),
1286
+				$type,
1287
+				$class_name
1288
+			)
1289
+		);
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1295
+	 * @param array $array
1296
+	 * @return bool
1297
+	 */
1298
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1299
+	{
1300
+		return ! empty($array)
1301
+			? array_keys($array) === range(0, count($array) - 1)
1302
+			: true;
1303
+	}
1304
+
1305
+
1306
+	/**
1307
+	 * _resolve_dependencies
1308
+	 * examines the constructor for the requested class to determine
1309
+	 * if any dependencies exist, and if they can be injected.
1310
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1311
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1312
+	 * For example:
1313
+	 *        if attempting to load a class "Foo" with the following constructor:
1314
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1315
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1316
+	 *        but only IF they are NOT already present in the incoming arguments array,
1317
+	 *        and the correct classes can be loaded
1318
+	 *
1319
+	 * @param ReflectionClass $reflector
1320
+	 * @param string          $class_name
1321
+	 * @param array           $arguments
1322
+	 * @return array
1323
+	 * @throws InvalidArgumentException
1324
+	 * @throws InvalidDataTypeException
1325
+	 * @throws InvalidInterfaceException
1326
+	 * @throws ReflectionException
1327
+	 */
1328
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, array $arguments = array())
1329
+	{
1330
+		// let's examine the constructor
1331
+		$constructor = $this->mirror->getConstructorFromReflection($reflector);
1332
+		// whu? huh? nothing?
1333
+		if (! $constructor) {
1334
+			return $arguments;
1335
+		}
1336
+		// get constructor parameters
1337
+		$params = $this->mirror->getParametersFromReflection($reflector);
1338
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1339
+		$argument_keys = array_keys($arguments);
1340
+		// now loop thru all of the constructors expected parameters
1341
+		foreach ($params as $index => $param) {
1342
+			try {
1343
+				// is this a dependency for a specific class ?
1344
+				$param_class = $this->mirror->getParameterClassName($param, $class_name, $index);
1345
+			} catch (ReflectionException $exception) {
1346
+				// uh-oh... most likely a legacy class that has not been autoloaded
1347
+				// let's try to derive the classname from what we have now
1348
+				// and hope that the property var name is close to the class name
1349
+				$param_class = $param->getName();
1350
+				$param_class = str_replace('_', ' ', $param_class);
1351
+				$param_class = ucwords($param_class);
1352
+				$param_class = str_replace(' ', '_', $param_class);
1353
+			}
1354
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1355
+			$param_class = $this->class_cache->isAlias($param_class, $class_name)
1356
+				? $this->class_cache->getFqnForAlias($param_class, $class_name)
1357
+				: $param_class;
1358
+			if (
1359 1359
 // param is not even a class
1360
-                $param_class === null
1361
-                // and something already exists in the incoming arguments for this param
1362
-                && array_key_exists($index, $argument_keys)
1363
-                && array_key_exists($argument_keys[ $index ], $arguments)
1364
-            ) {
1365
-                // so let's skip this argument and move on to the next
1366
-                continue;
1367
-            }
1368
-            if (
1360
+				$param_class === null
1361
+				// and something already exists in the incoming arguments for this param
1362
+				&& array_key_exists($index, $argument_keys)
1363
+				&& array_key_exists($argument_keys[ $index ], $arguments)
1364
+			) {
1365
+				// so let's skip this argument and move on to the next
1366
+				continue;
1367
+			}
1368
+			if (
1369 1369
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1370
-                $param_class !== null
1371
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
1372
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1373
-            ) {
1374
-                // skip this argument and move on to the next
1375
-                continue;
1376
-            }
1377
-            if (
1370
+				$param_class !== null
1371
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
1372
+				&& $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1373
+			) {
1374
+				// skip this argument and move on to the next
1375
+				continue;
1376
+			}
1377
+			if (
1378 1378
 // parameter is type hinted as a class, and should be injected
1379
-                $param_class !== null
1380
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1381
-            ) {
1382
-                $arguments = $this->_resolve_dependency(
1383
-                    $class_name,
1384
-                    $param_class,
1385
-                    $arguments,
1386
-                    $index
1387
-                );
1388
-            }
1389
-            if (empty($arguments[ $index ])) {
1390
-                $arguments[ $index ] = $this->mirror->getParameterDefaultValue(
1391
-                    $param,
1392
-                    $class_name,
1393
-                    $index
1394
-                );
1395
-            }
1396
-        }
1397
-        return $arguments;
1398
-    }
1399
-
1400
-
1401
-    /**
1402
-     * @param string $class_name
1403
-     * @param string $param_class
1404
-     * @param array  $arguments
1405
-     * @param mixed  $index
1406
-     * @return array
1407
-     * @throws InvalidArgumentException
1408
-     * @throws InvalidInterfaceException
1409
-     * @throws InvalidDataTypeException
1410
-     */
1411
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1412
-    {
1413
-        $dependency = null;
1414
-        // should dependency be loaded from cache ?
1415
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1416
-            $class_name,
1417
-            $param_class
1418
-        );
1419
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1420
-        // we might have a dependency...
1421
-        // let's MAYBE try and find it in our cache if that's what's been requested
1422
-        $cached_class = $cache_on
1423
-            ? $this->_get_cached_class($param_class)
1424
-            : null;
1425
-        // and grab it if it exists
1426
-        if ($cached_class instanceof $param_class) {
1427
-            $dependency = $cached_class;
1428
-        } elseif ($param_class !== $class_name) {
1429
-            // obtain the loader method from the dependency map
1430
-            $loader = $this->_dependency_map->class_loader($param_class);
1431
-            // is loader a custom closure ?
1432
-            if ($loader instanceof Closure) {
1433
-                $dependency = $loader($arguments);
1434
-            } else {
1435
-                // set the cache on property for the recursive loading call
1436
-                $this->_cache_on = $cache_on;
1437
-                // if not, then let's try and load it via the registry
1438
-                if ($loader && method_exists($this, $loader)) {
1439
-                    $dependency = $this->{$loader}($param_class);
1440
-                } else {
1441
-                    $dependency = LoaderFactory::getLoader()->load(
1442
-                        $param_class,
1443
-                        array(),
1444
-                        $cache_on
1445
-                    );
1446
-                }
1447
-            }
1448
-        }
1449
-        // did we successfully find the correct dependency ?
1450
-        if ($dependency instanceof $param_class) {
1451
-            // then let's inject it into the incoming array of arguments at the correct location
1452
-            $arguments[ $index ] = $dependency;
1453
-        }
1454
-        return $arguments;
1455
-    }
1456
-
1457
-
1458
-    /**
1459
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1460
-     *
1461
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1462
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1463
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1464
-     * @param array  $arguments
1465
-     * @return object
1466
-     */
1467
-    public static function factory($classname, $arguments = array())
1468
-    {
1469
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1470
-        if ($loader instanceof Closure) {
1471
-            return $loader($arguments);
1472
-        }
1473
-        if (method_exists(self::instance(), $loader)) {
1474
-            return self::instance()->{$loader}($classname, $arguments);
1475
-        }
1476
-        return null;
1477
-    }
1478
-
1479
-
1480
-    /**
1481
-     * Gets the addon by its class name
1482
-     *
1483
-     * @param string $class_name
1484
-     * @return EE_Addon
1485
-     */
1486
-    public function getAddon($class_name)
1487
-    {
1488
-        $class_name = str_replace('\\', '_', $class_name);
1489
-        if (isset($this->addons->{$class_name})) {
1490
-            return $this->addons->{$class_name};
1491
-        } else {
1492
-            return null;
1493
-        }
1494
-    }
1495
-
1496
-
1497
-    /**
1498
-     * removes the addon from the internal cache
1499
-     *
1500
-     * @param string $class_name
1501
-     * @return void
1502
-     */
1503
-    public function removeAddon($class_name)
1504
-    {
1505
-        $class_name = str_replace('\\', '_', $class_name);
1506
-        unset($this->addons->{$class_name});
1507
-    }
1508
-
1509
-
1510
-    /**
1511
-     * Gets the addon by its name/slug (not classname. For that, just
1512
-     * use the get_addon() method above
1513
-     *
1514
-     * @param string $name
1515
-     * @return EE_Addon
1516
-     */
1517
-    public function get_addon_by_name($name)
1518
-    {
1519
-        foreach ($this->addons as $addon) {
1520
-            if ($addon->name() === $name) {
1521
-                return $addon;
1522
-            }
1523
-        }
1524
-        return null;
1525
-    }
1526
-
1527
-
1528
-    /**
1529
-     * Gets an array of all the registered addons, where the keys are their names.
1530
-     * (ie, what each returns for their name() function)
1531
-     * They're already available on EE_Registry::instance()->addons as properties,
1532
-     * where each property's name is the addon's classname,
1533
-     * So if you just want to get the addon by classname,
1534
-     * OR use the get_addon() method above.
1535
-     * PLEASE  NOTE:
1536
-     * addons with Fully Qualified Class Names
1537
-     * have had the namespace separators converted to underscores,
1538
-     * so a classname like Fully\Qualified\ClassName
1539
-     * would have been converted to Fully_Qualified_ClassName
1540
-     *
1541
-     * @return EE_Addon[] where the KEYS are the addon's name()
1542
-     */
1543
-    public function get_addons_by_name()
1544
-    {
1545
-        $addons = array();
1546
-        foreach ($this->addons as $addon) {
1547
-            $addons[ $addon->name() ] = $addon;
1548
-        }
1549
-        return $addons;
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1555
-     * a stale copy of it around
1556
-     *
1557
-     * @param string $model_name
1558
-     * @return \EEM_Base
1559
-     * @throws \EE_Error
1560
-     */
1561
-    public function reset_model($model_name)
1562
-    {
1563
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1564
-            ? "EEM_{$model_name}"
1565
-            : $model_name;
1566
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1567
-            return null;
1568
-        }
1569
-        // get that model reset it and make sure we nuke the old reference to it
1570
-        if (
1571
-            $this->LIB->{$model_class_name} instanceof $model_class_name
1572
-            && is_callable(
1573
-                array($model_class_name, 'reset')
1574
-            )
1575
-        ) {
1576
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1577
-        } else {
1578
-            throw new EE_Error(
1579
-                sprintf(
1580
-                    esc_html__('Model %s does not have a method "reset"', 'event_espresso'),
1581
-                    $model_name
1582
-                )
1583
-            );
1584
-        }
1585
-        return $this->LIB->{$model_class_name};
1586
-    }
1587
-
1588
-
1589
-    /**
1590
-     * Resets the registry.
1591
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1592
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1593
-     * - $_dependency_map
1594
-     * - $_class_abbreviations
1595
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1596
-     * - $REQ:  Still on the same request so no need to change.
1597
-     * - $CAP: There is no site specific state in the EE_Capability class.
1598
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1599
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1600
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1601
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1602
-     *             switch or on the restore.
1603
-     * - $modules
1604
-     * - $shortcodes
1605
-     * - $widgets
1606
-     *
1607
-     * @param boolean $hard             [deprecated]
1608
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1609
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1610
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1611
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1612
-     *                                  client
1613
-     *                                  code instead can just change the model context to a different blog id if
1614
-     *                                  necessary
1615
-     * @return EE_Registry
1616
-     * @throws InvalidInterfaceException
1617
-     * @throws InvalidDataTypeException
1618
-     * @throws EE_Error
1619
-     * @throws ReflectionException
1620
-     * @throws InvalidArgumentException
1621
-     */
1622
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1623
-    {
1624
-        $instance = self::instance();
1625
-        $instance->_cache_on = true;
1626
-        // reset some "special" classes
1627
-        EEH_Activation::reset();
1628
-        EEH_DTT_Helper::resetDefaultTimezoneString();
1629
-
1630
-        $hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1631
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1632
-        $instance->CART = null;
1633
-        $instance->MRM = null;
1634
-        $instance->AssetsRegistry = LoaderFactory::getLoader()->getShared(
1635
-            'EventEspresso\core\services\assets\Registry'
1636
-        );
1637
-        // messages reset
1638
-        EED_Messages::reset();
1639
-        // handle of objects cached on LIB
1640
-        foreach (array('LIB', 'modules') as $cache) {
1641
-            foreach ($instance->{$cache} as $class_name => $class) {
1642
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1643
-                    unset($instance->{$cache}->{$class_name});
1644
-                }
1645
-            }
1646
-        }
1647
-        return $instance;
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * if passed object implements ResettableInterface, then call it's reset() method
1653
-     * if passed object implements InterminableInterface, then return false,
1654
-     * to indicate that it should NOT be cleared from the Registry cache
1655
-     *
1656
-     * @param      $object
1657
-     * @param bool $reset_models
1658
-     * @return bool returns true if cached object should be unset
1659
-     */
1660
-    private static function _reset_and_unset_object($object, $reset_models)
1661
-    {
1662
-        if (! is_object($object)) {
1663
-            // don't unset anything that's not an object
1664
-            return false;
1665
-        }
1666
-        if ($object instanceof EED_Module) {
1667
-            $object::reset();
1668
-            // don't unset modules
1669
-            return false;
1670
-        }
1671
-        if ($object instanceof ResettableInterface) {
1672
-            if ($object instanceof EEM_Base) {
1673
-                if ($reset_models) {
1674
-                    $object->reset();
1675
-                    return true;
1676
-                }
1677
-                return false;
1678
-            }
1679
-            $object->reset();
1680
-            return true;
1681
-        }
1682
-        if (! $object instanceof InterminableInterface) {
1683
-            return true;
1684
-        }
1685
-        return false;
1686
-    }
1687
-
1688
-
1689
-    /**
1690
-     * Gets all the custom post type models defined
1691
-     *
1692
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1693
-     */
1694
-    public function cpt_models()
1695
-    {
1696
-        $cpt_models = array();
1697
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1698
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1699
-                $cpt_models[ $short_name ] = $classname;
1700
-            }
1701
-        }
1702
-        return $cpt_models;
1703
-    }
1704
-
1705
-
1706
-    /**
1707
-     * @return \EE_Config
1708
-     */
1709
-    public static function CFG()
1710
-    {
1711
-        return self::instance()->CFG;
1712
-    }
1713
-
1714
-
1715
-    /**
1716
-     * @deprecated 4.9.62.p
1717
-     * @param string $class_name
1718
-     * @return ReflectionClass
1719
-     * @throws ReflectionException
1720
-     * @throws InvalidDataTypeException
1721
-     */
1722
-    public function get_ReflectionClass($class_name)
1723
-    {
1724
-        return $this->mirror->getReflectionClass($class_name);
1725
-    }
1379
+				$param_class !== null
1380
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1381
+			) {
1382
+				$arguments = $this->_resolve_dependency(
1383
+					$class_name,
1384
+					$param_class,
1385
+					$arguments,
1386
+					$index
1387
+				);
1388
+			}
1389
+			if (empty($arguments[ $index ])) {
1390
+				$arguments[ $index ] = $this->mirror->getParameterDefaultValue(
1391
+					$param,
1392
+					$class_name,
1393
+					$index
1394
+				);
1395
+			}
1396
+		}
1397
+		return $arguments;
1398
+	}
1399
+
1400
+
1401
+	/**
1402
+	 * @param string $class_name
1403
+	 * @param string $param_class
1404
+	 * @param array  $arguments
1405
+	 * @param mixed  $index
1406
+	 * @return array
1407
+	 * @throws InvalidArgumentException
1408
+	 * @throws InvalidInterfaceException
1409
+	 * @throws InvalidDataTypeException
1410
+	 */
1411
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1412
+	{
1413
+		$dependency = null;
1414
+		// should dependency be loaded from cache ?
1415
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1416
+			$class_name,
1417
+			$param_class
1418
+		);
1419
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1420
+		// we might have a dependency...
1421
+		// let's MAYBE try and find it in our cache if that's what's been requested
1422
+		$cached_class = $cache_on
1423
+			? $this->_get_cached_class($param_class)
1424
+			: null;
1425
+		// and grab it if it exists
1426
+		if ($cached_class instanceof $param_class) {
1427
+			$dependency = $cached_class;
1428
+		} elseif ($param_class !== $class_name) {
1429
+			// obtain the loader method from the dependency map
1430
+			$loader = $this->_dependency_map->class_loader($param_class);
1431
+			// is loader a custom closure ?
1432
+			if ($loader instanceof Closure) {
1433
+				$dependency = $loader($arguments);
1434
+			} else {
1435
+				// set the cache on property for the recursive loading call
1436
+				$this->_cache_on = $cache_on;
1437
+				// if not, then let's try and load it via the registry
1438
+				if ($loader && method_exists($this, $loader)) {
1439
+					$dependency = $this->{$loader}($param_class);
1440
+				} else {
1441
+					$dependency = LoaderFactory::getLoader()->load(
1442
+						$param_class,
1443
+						array(),
1444
+						$cache_on
1445
+					);
1446
+				}
1447
+			}
1448
+		}
1449
+		// did we successfully find the correct dependency ?
1450
+		if ($dependency instanceof $param_class) {
1451
+			// then let's inject it into the incoming array of arguments at the correct location
1452
+			$arguments[ $index ] = $dependency;
1453
+		}
1454
+		return $arguments;
1455
+	}
1456
+
1457
+
1458
+	/**
1459
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1460
+	 *
1461
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1462
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1463
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1464
+	 * @param array  $arguments
1465
+	 * @return object
1466
+	 */
1467
+	public static function factory($classname, $arguments = array())
1468
+	{
1469
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1470
+		if ($loader instanceof Closure) {
1471
+			return $loader($arguments);
1472
+		}
1473
+		if (method_exists(self::instance(), $loader)) {
1474
+			return self::instance()->{$loader}($classname, $arguments);
1475
+		}
1476
+		return null;
1477
+	}
1478
+
1479
+
1480
+	/**
1481
+	 * Gets the addon by its class name
1482
+	 *
1483
+	 * @param string $class_name
1484
+	 * @return EE_Addon
1485
+	 */
1486
+	public function getAddon($class_name)
1487
+	{
1488
+		$class_name = str_replace('\\', '_', $class_name);
1489
+		if (isset($this->addons->{$class_name})) {
1490
+			return $this->addons->{$class_name};
1491
+		} else {
1492
+			return null;
1493
+		}
1494
+	}
1495
+
1496
+
1497
+	/**
1498
+	 * removes the addon from the internal cache
1499
+	 *
1500
+	 * @param string $class_name
1501
+	 * @return void
1502
+	 */
1503
+	public function removeAddon($class_name)
1504
+	{
1505
+		$class_name = str_replace('\\', '_', $class_name);
1506
+		unset($this->addons->{$class_name});
1507
+	}
1508
+
1509
+
1510
+	/**
1511
+	 * Gets the addon by its name/slug (not classname. For that, just
1512
+	 * use the get_addon() method above
1513
+	 *
1514
+	 * @param string $name
1515
+	 * @return EE_Addon
1516
+	 */
1517
+	public function get_addon_by_name($name)
1518
+	{
1519
+		foreach ($this->addons as $addon) {
1520
+			if ($addon->name() === $name) {
1521
+				return $addon;
1522
+			}
1523
+		}
1524
+		return null;
1525
+	}
1526
+
1527
+
1528
+	/**
1529
+	 * Gets an array of all the registered addons, where the keys are their names.
1530
+	 * (ie, what each returns for their name() function)
1531
+	 * They're already available on EE_Registry::instance()->addons as properties,
1532
+	 * where each property's name is the addon's classname,
1533
+	 * So if you just want to get the addon by classname,
1534
+	 * OR use the get_addon() method above.
1535
+	 * PLEASE  NOTE:
1536
+	 * addons with Fully Qualified Class Names
1537
+	 * have had the namespace separators converted to underscores,
1538
+	 * so a classname like Fully\Qualified\ClassName
1539
+	 * would have been converted to Fully_Qualified_ClassName
1540
+	 *
1541
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1542
+	 */
1543
+	public function get_addons_by_name()
1544
+	{
1545
+		$addons = array();
1546
+		foreach ($this->addons as $addon) {
1547
+			$addons[ $addon->name() ] = $addon;
1548
+		}
1549
+		return $addons;
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1555
+	 * a stale copy of it around
1556
+	 *
1557
+	 * @param string $model_name
1558
+	 * @return \EEM_Base
1559
+	 * @throws \EE_Error
1560
+	 */
1561
+	public function reset_model($model_name)
1562
+	{
1563
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1564
+			? "EEM_{$model_name}"
1565
+			: $model_name;
1566
+		if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1567
+			return null;
1568
+		}
1569
+		// get that model reset it and make sure we nuke the old reference to it
1570
+		if (
1571
+			$this->LIB->{$model_class_name} instanceof $model_class_name
1572
+			&& is_callable(
1573
+				array($model_class_name, 'reset')
1574
+			)
1575
+		) {
1576
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1577
+		} else {
1578
+			throw new EE_Error(
1579
+				sprintf(
1580
+					esc_html__('Model %s does not have a method "reset"', 'event_espresso'),
1581
+					$model_name
1582
+				)
1583
+			);
1584
+		}
1585
+		return $this->LIB->{$model_class_name};
1586
+	}
1587
+
1588
+
1589
+	/**
1590
+	 * Resets the registry.
1591
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1592
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1593
+	 * - $_dependency_map
1594
+	 * - $_class_abbreviations
1595
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1596
+	 * - $REQ:  Still on the same request so no need to change.
1597
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1598
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1599
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1600
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1601
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1602
+	 *             switch or on the restore.
1603
+	 * - $modules
1604
+	 * - $shortcodes
1605
+	 * - $widgets
1606
+	 *
1607
+	 * @param boolean $hard             [deprecated]
1608
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1609
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1610
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1611
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1612
+	 *                                  client
1613
+	 *                                  code instead can just change the model context to a different blog id if
1614
+	 *                                  necessary
1615
+	 * @return EE_Registry
1616
+	 * @throws InvalidInterfaceException
1617
+	 * @throws InvalidDataTypeException
1618
+	 * @throws EE_Error
1619
+	 * @throws ReflectionException
1620
+	 * @throws InvalidArgumentException
1621
+	 */
1622
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1623
+	{
1624
+		$instance = self::instance();
1625
+		$instance->_cache_on = true;
1626
+		// reset some "special" classes
1627
+		EEH_Activation::reset();
1628
+		EEH_DTT_Helper::resetDefaultTimezoneString();
1629
+
1630
+		$hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1631
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1632
+		$instance->CART = null;
1633
+		$instance->MRM = null;
1634
+		$instance->AssetsRegistry = LoaderFactory::getLoader()->getShared(
1635
+			'EventEspresso\core\services\assets\Registry'
1636
+		);
1637
+		// messages reset
1638
+		EED_Messages::reset();
1639
+		// handle of objects cached on LIB
1640
+		foreach (array('LIB', 'modules') as $cache) {
1641
+			foreach ($instance->{$cache} as $class_name => $class) {
1642
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1643
+					unset($instance->{$cache}->{$class_name});
1644
+				}
1645
+			}
1646
+		}
1647
+		return $instance;
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * if passed object implements ResettableInterface, then call it's reset() method
1653
+	 * if passed object implements InterminableInterface, then return false,
1654
+	 * to indicate that it should NOT be cleared from the Registry cache
1655
+	 *
1656
+	 * @param      $object
1657
+	 * @param bool $reset_models
1658
+	 * @return bool returns true if cached object should be unset
1659
+	 */
1660
+	private static function _reset_and_unset_object($object, $reset_models)
1661
+	{
1662
+		if (! is_object($object)) {
1663
+			// don't unset anything that's not an object
1664
+			return false;
1665
+		}
1666
+		if ($object instanceof EED_Module) {
1667
+			$object::reset();
1668
+			// don't unset modules
1669
+			return false;
1670
+		}
1671
+		if ($object instanceof ResettableInterface) {
1672
+			if ($object instanceof EEM_Base) {
1673
+				if ($reset_models) {
1674
+					$object->reset();
1675
+					return true;
1676
+				}
1677
+				return false;
1678
+			}
1679
+			$object->reset();
1680
+			return true;
1681
+		}
1682
+		if (! $object instanceof InterminableInterface) {
1683
+			return true;
1684
+		}
1685
+		return false;
1686
+	}
1687
+
1688
+
1689
+	/**
1690
+	 * Gets all the custom post type models defined
1691
+	 *
1692
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1693
+	 */
1694
+	public function cpt_models()
1695
+	{
1696
+		$cpt_models = array();
1697
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1698
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1699
+				$cpt_models[ $short_name ] = $classname;
1700
+			}
1701
+		}
1702
+		return $cpt_models;
1703
+	}
1704
+
1705
+
1706
+	/**
1707
+	 * @return \EE_Config
1708
+	 */
1709
+	public static function CFG()
1710
+	{
1711
+		return self::instance()->CFG;
1712
+	}
1713
+
1714
+
1715
+	/**
1716
+	 * @deprecated 4.9.62.p
1717
+	 * @param string $class_name
1718
+	 * @return ReflectionClass
1719
+	 * @throws ReflectionException
1720
+	 * @throws InvalidDataTypeException
1721
+	 */
1722
+	public function get_ReflectionClass($class_name)
1723
+	{
1724
+		return $this->mirror->getReflectionClass($class_name);
1725
+	}
1726 1726
 }
Please login to merge, or discard this patch.
core/domain/entities/DbSafeDateTime.php 1 patch
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -20,194 +20,194 @@
 block discarded – undo
20 20
 class DbSafeDateTime extends DateTime
21 21
 {
22 22
 
23
-    // phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
24
-    /**
25
-     * @type string db_safe_timestamp_format
26
-     */
27
-    const db_safe_timestamp_format = 'Y-m-d H:i:s O e';
28
-
29
-    // phpcs:enable
30
-
31
-    // phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
32
-    /**
33
-     * DateTime object converted to a string that includes the date, time, UTC offset, and timezone identifier
34
-     *
35
-     * @type string $_datetime_string
36
-     */
37
-    protected $_datetime_string = '';
38
-
39
-    /**
40
-     * where to write the error log to
41
-     *
42
-     * @type string $_error_log_dir
43
-     */
44
-    protected $_error_log_dir = '';
45
-
46
-    // phpcs:enable
47
-
48
-
49
-    /**
50
-     * @param string $error_log_dir
51
-     */
52
-    public function setErrorLogDir($error_log_dir)
53
-    {
54
-        // if the folder path is writable, then except the path + filename, else keep empty
55
-        $this->_error_log_dir = is_writable(str_replace(basename($error_log_dir), '', $error_log_dir))
56
-            ? $error_log_dir
57
-            : '';
58
-    }
59
-
60
-
61
-    /**
62
-     * @return string
63
-     */
64
-    public function __toString()
65
-    {
66
-        return $this->format(DbSafeDateTime::db_safe_timestamp_format);
67
-    }
68
-
69
-
70
-    /**
71
-     * @return array
72
-     */
73
-    public function __sleep()
74
-    {
75
-        $this->_datetime_string = $this->format(DbSafeDateTime::db_safe_timestamp_format);
76
-        $date                   = DateTime::createFromFormat(
77
-            DbSafeDateTime::db_safe_timestamp_format,
78
-            $this->_datetime_string
79
-        );
80
-        if (! $date instanceof DateTime) {
81
-            try {
82
-                // we want a stack trace to determine where the malformed date came from, so...
83
-                throw new DomainException('');
84
-            } catch (DomainException $e) {
85
-                $stack_trace = $e->getTraceAsString();
86
-            }
87
-            $this->writeToErrorLog(
88
-                sprintf(
89
-                    __(
90
-                        'A valid DateTime could not be generated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s %2$s Stack Trace: %5$s',
91
-                        'event_espresso'
92
-                    ),
93
-                    $this->_datetime_string,
94
-                    '<br />',
95
-                    print_r(DateTime::getLastErrors(), true),
96
-                    PHP_VERSION,
97
-                    $stack_trace
98
-                )
99
-            );
100
-        }
101
-        return ['_datetime_string'];
102
-    }
103
-
104
-
105
-    /**
106
-     * if an empty or null value got saved to the db for a datetime,
107
-     * then some servers and/or PHP itself will incorrectly convert that date string
108
-     * resulting in "-0001-11-30" for the year-month-day.
109
-     * see the Notes section
110
-     *
111
-     * @throws Exception
112
-     * @link http://php.net/manual/en/datetime.formats.date.php
113
-     * We'll replace those with "0000-00-00" which will allow a valid DateTime object to be created,
114
-     * but still result in the internal date for that object being set to "-0001-11-30 10:00:00.000000".
115
-     * so we're no better off, but at least things won't go fatal on us.
116
-     */
117
-    public function __wakeup()
118
-    {
119
-        $date = self::createFromFormat(
120
-            DbSafeDateTime::db_safe_timestamp_format,
121
-            $this->_datetime_string
122
-        );
123
-        if (! $date instanceof DateTime) {
124
-            $this->writeToErrorLog(
125
-                sprintf(
126
-                    __(
127
-                        'A valid DateTime could not be recreated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s',
128
-                        'event_espresso'
129
-                    ),
130
-                    $this->_datetime_string,
131
-                    '<br />',
132
-                    print_r(DateTime::getLastErrors(), true),
133
-                    PHP_VERSION
134
-                )
135
-            );
136
-        } else {
137
-            $this->__construct(
138
-                $date->format(EE_Datetime_Field::mysql_timestamp_format),
139
-                new DateTimeZone($date->format('e'))
140
-            );
141
-        }
142
-    }
143
-
144
-
145
-    /**
146
-     * Normalizes incoming date string so that it is a bit more stable for use.
147
-     *
148
-     * @param string $date_string
149
-     * @return string
150
-     */
151
-    public static function normalizeInvalidDate($date_string)
152
-    {
153
-        return str_replace(
154
-            ['-0001-11-29', '-0001-11-30', '0000-00-00'],
155
-            '0000-01-03',
156
-            $date_string
157
-        );
158
-    }
159
-
160
-
161
-    /**
162
-     * Creates a DbSafeDateTime from ye old DateTime
163
-     *
164
-     * @param DateTime $datetime
165
-     * @return DbSafeDateTime
166
-     * @throws Exception
167
-     */
168
-    public static function createFromDateTime(DateTime $datetime)
169
-    {
170
-        return new DbSafeDateTime(
171
-            $datetime->format(EE_Datetime_Field::mysql_timestamp_format),
172
-            new DateTimeZone($datetime->format('e'))
173
-        );
174
-    }
175
-
176
-
177
-    /**
178
-     * Parse a string into a new DateTime object according to the specified format
179
-     *
180
-     * @param string            $format   Format accepted by date().
181
-     * @param string            $time     String representing the time.
182
-     * @param DateTimeZone|null $timezone A DateTimeZone object representing the desired time zone.
183
-     * @return DbSafeDateTime|boolean
184
-     * @throws Exception
185
-     * @link https://php.net/manual/en/datetime.createfromformat.php
186
-     */
187
-    public static function createFromFormat($format, $time, DateTimeZone $timezone = null)
188
-    {
189
-        $time = self::normalizeInvalidDate($time);
190
-        // Various php versions handle the third argument differently.  This conditional accounts for that.
191
-        $DateTime = $timezone instanceof DateTimeZone
192
-            ? parent::createFromFormat($format, $time, $timezone)
193
-            : parent::createFromFormat($format, $time);
194
-        return $DateTime instanceof DateTime
195
-            ? self::createFromDateTime($DateTime)
196
-            : $DateTime;
197
-    }
198
-
199
-
200
-    /**
201
-     * @param string $message
202
-     */
203
-    private function writeToErrorLog($message)
204
-    {
205
-        if (! empty($this->_error_log_dir)) {
206
-            /** @noinspection ForgottenDebugOutputInspection */
207
-            error_log($message, 3, $this->_error_log_dir);
208
-        } else {
209
-            /** @noinspection ForgottenDebugOutputInspection */
210
-            error_log($message);
211
-        }
212
-    }
23
+	// phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
24
+	/**
25
+	 * @type string db_safe_timestamp_format
26
+	 */
27
+	const db_safe_timestamp_format = 'Y-m-d H:i:s O e';
28
+
29
+	// phpcs:enable
30
+
31
+	// phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
32
+	/**
33
+	 * DateTime object converted to a string that includes the date, time, UTC offset, and timezone identifier
34
+	 *
35
+	 * @type string $_datetime_string
36
+	 */
37
+	protected $_datetime_string = '';
38
+
39
+	/**
40
+	 * where to write the error log to
41
+	 *
42
+	 * @type string $_error_log_dir
43
+	 */
44
+	protected $_error_log_dir = '';
45
+
46
+	// phpcs:enable
47
+
48
+
49
+	/**
50
+	 * @param string $error_log_dir
51
+	 */
52
+	public function setErrorLogDir($error_log_dir)
53
+	{
54
+		// if the folder path is writable, then except the path + filename, else keep empty
55
+		$this->_error_log_dir = is_writable(str_replace(basename($error_log_dir), '', $error_log_dir))
56
+			? $error_log_dir
57
+			: '';
58
+	}
59
+
60
+
61
+	/**
62
+	 * @return string
63
+	 */
64
+	public function __toString()
65
+	{
66
+		return $this->format(DbSafeDateTime::db_safe_timestamp_format);
67
+	}
68
+
69
+
70
+	/**
71
+	 * @return array
72
+	 */
73
+	public function __sleep()
74
+	{
75
+		$this->_datetime_string = $this->format(DbSafeDateTime::db_safe_timestamp_format);
76
+		$date                   = DateTime::createFromFormat(
77
+			DbSafeDateTime::db_safe_timestamp_format,
78
+			$this->_datetime_string
79
+		);
80
+		if (! $date instanceof DateTime) {
81
+			try {
82
+				// we want a stack trace to determine where the malformed date came from, so...
83
+				throw new DomainException('');
84
+			} catch (DomainException $e) {
85
+				$stack_trace = $e->getTraceAsString();
86
+			}
87
+			$this->writeToErrorLog(
88
+				sprintf(
89
+					__(
90
+						'A valid DateTime could not be generated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s %2$s Stack Trace: %5$s',
91
+						'event_espresso'
92
+					),
93
+					$this->_datetime_string,
94
+					'<br />',
95
+					print_r(DateTime::getLastErrors(), true),
96
+					PHP_VERSION,
97
+					$stack_trace
98
+				)
99
+			);
100
+		}
101
+		return ['_datetime_string'];
102
+	}
103
+
104
+
105
+	/**
106
+	 * if an empty or null value got saved to the db for a datetime,
107
+	 * then some servers and/or PHP itself will incorrectly convert that date string
108
+	 * resulting in "-0001-11-30" for the year-month-day.
109
+	 * see the Notes section
110
+	 *
111
+	 * @throws Exception
112
+	 * @link http://php.net/manual/en/datetime.formats.date.php
113
+	 * We'll replace those with "0000-00-00" which will allow a valid DateTime object to be created,
114
+	 * but still result in the internal date for that object being set to "-0001-11-30 10:00:00.000000".
115
+	 * so we're no better off, but at least things won't go fatal on us.
116
+	 */
117
+	public function __wakeup()
118
+	{
119
+		$date = self::createFromFormat(
120
+			DbSafeDateTime::db_safe_timestamp_format,
121
+			$this->_datetime_string
122
+		);
123
+		if (! $date instanceof DateTime) {
124
+			$this->writeToErrorLog(
125
+				sprintf(
126
+					__(
127
+						'A valid DateTime could not be recreated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s',
128
+						'event_espresso'
129
+					),
130
+					$this->_datetime_string,
131
+					'<br />',
132
+					print_r(DateTime::getLastErrors(), true),
133
+					PHP_VERSION
134
+				)
135
+			);
136
+		} else {
137
+			$this->__construct(
138
+				$date->format(EE_Datetime_Field::mysql_timestamp_format),
139
+				new DateTimeZone($date->format('e'))
140
+			);
141
+		}
142
+	}
143
+
144
+
145
+	/**
146
+	 * Normalizes incoming date string so that it is a bit more stable for use.
147
+	 *
148
+	 * @param string $date_string
149
+	 * @return string
150
+	 */
151
+	public static function normalizeInvalidDate($date_string)
152
+	{
153
+		return str_replace(
154
+			['-0001-11-29', '-0001-11-30', '0000-00-00'],
155
+			'0000-01-03',
156
+			$date_string
157
+		);
158
+	}
159
+
160
+
161
+	/**
162
+	 * Creates a DbSafeDateTime from ye old DateTime
163
+	 *
164
+	 * @param DateTime $datetime
165
+	 * @return DbSafeDateTime
166
+	 * @throws Exception
167
+	 */
168
+	public static function createFromDateTime(DateTime $datetime)
169
+	{
170
+		return new DbSafeDateTime(
171
+			$datetime->format(EE_Datetime_Field::mysql_timestamp_format),
172
+			new DateTimeZone($datetime->format('e'))
173
+		);
174
+	}
175
+
176
+
177
+	/**
178
+	 * Parse a string into a new DateTime object according to the specified format
179
+	 *
180
+	 * @param string            $format   Format accepted by date().
181
+	 * @param string            $time     String representing the time.
182
+	 * @param DateTimeZone|null $timezone A DateTimeZone object representing the desired time zone.
183
+	 * @return DbSafeDateTime|boolean
184
+	 * @throws Exception
185
+	 * @link https://php.net/manual/en/datetime.createfromformat.php
186
+	 */
187
+	public static function createFromFormat($format, $time, DateTimeZone $timezone = null)
188
+	{
189
+		$time = self::normalizeInvalidDate($time);
190
+		// Various php versions handle the third argument differently.  This conditional accounts for that.
191
+		$DateTime = $timezone instanceof DateTimeZone
192
+			? parent::createFromFormat($format, $time, $timezone)
193
+			: parent::createFromFormat($format, $time);
194
+		return $DateTime instanceof DateTime
195
+			? self::createFromDateTime($DateTime)
196
+			: $DateTime;
197
+	}
198
+
199
+
200
+	/**
201
+	 * @param string $message
202
+	 */
203
+	private function writeToErrorLog($message)
204
+	{
205
+		if (! empty($this->_error_log_dir)) {
206
+			/** @noinspection ForgottenDebugOutputInspection */
207
+			error_log($message, 3, $this->_error_log_dir);
208
+		} else {
209
+			/** @noinspection ForgottenDebugOutputInspection */
210
+			error_log($message);
211
+		}
212
+	}
213 213
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 1 patch
Indentation   +1744 added lines, -1744 removed lines patch added patch discarded remove patch
@@ -14,1748 +14,1748 @@
 block discarded – undo
14 14
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
15 15
 {
16 16
 
17
-    /**
18
-     * for children line items (currently not a normal relation)
19
-     *
20
-     * @type EE_Line_Item[]
21
-     */
22
-    protected $_children = array();
23
-
24
-    /**
25
-     * for the parent line item
26
-     *
27
-     * @var EE_Line_Item
28
-     */
29
-    protected $_parent;
30
-
31
-
32
-    /**
33
-     * @param array  $props_n_values          incoming values
34
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
35
-     *                                        used.)
36
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
37
-     *                                        date_format and the second value is the time format
38
-     * @return EE_Line_Item
39
-     * @throws EE_Error
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     * @throws ReflectionException
44
-     */
45
-    public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
46
-    {
47
-        $has_object = parent::_check_for_object(
48
-            $props_n_values,
49
-            __CLASS__,
50
-            $timezone,
51
-            $date_formats
52
-        );
53
-        return $has_object
54
-            ? $has_object
55
-            : new self($props_n_values, false, $timezone);
56
-    }
57
-
58
-
59
-    /**
60
-     * @param array  $props_n_values  incoming values from the database
61
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
62
-     *                                the website will be used.
63
-     * @return EE_Line_Item
64
-     * @throws EE_Error
65
-     * @throws InvalidArgumentException
66
-     * @throws InvalidDataTypeException
67
-     * @throws InvalidInterfaceException
68
-     * @throws ReflectionException
69
-     */
70
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
71
-    {
72
-        return new self($props_n_values, true, $timezone);
73
-    }
74
-
75
-
76
-    /**
77
-     * Adds some defaults if they're not specified
78
-     *
79
-     * @param array  $fieldValues
80
-     * @param bool   $bydb
81
-     * @param string $timezone
82
-     * @throws EE_Error
83
-     * @throws InvalidArgumentException
84
-     * @throws InvalidDataTypeException
85
-     * @throws InvalidInterfaceException
86
-     * @throws ReflectionException
87
-     */
88
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
89
-    {
90
-        parent::__construct($fieldValues, $bydb, $timezone);
91
-        if (! $this->get('LIN_code')) {
92
-            $this->set_code($this->generate_code());
93
-        }
94
-    }
95
-
96
-
97
-    /**
98
-     * Gets ID
99
-     *
100
-     * @return int
101
-     * @throws EE_Error
102
-     * @throws InvalidArgumentException
103
-     * @throws InvalidDataTypeException
104
-     * @throws InvalidInterfaceException
105
-     * @throws ReflectionException
106
-     */
107
-    public function ID()
108
-    {
109
-        return $this->get('LIN_ID');
110
-    }
111
-
112
-
113
-    /**
114
-     * Gets TXN_ID
115
-     *
116
-     * @return int
117
-     * @throws EE_Error
118
-     * @throws InvalidArgumentException
119
-     * @throws InvalidDataTypeException
120
-     * @throws InvalidInterfaceException
121
-     * @throws ReflectionException
122
-     */
123
-    public function TXN_ID()
124
-    {
125
-        return $this->get('TXN_ID');
126
-    }
127
-
128
-
129
-    /**
130
-     * Sets TXN_ID
131
-     *
132
-     * @param int $TXN_ID
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidDataTypeException
136
-     * @throws InvalidInterfaceException
137
-     * @throws ReflectionException
138
-     */
139
-    public function set_TXN_ID($TXN_ID)
140
-    {
141
-        $this->set('TXN_ID', $TXN_ID);
142
-    }
143
-
144
-
145
-    /**
146
-     * Gets name
147
-     *
148
-     * @return string
149
-     * @throws EE_Error
150
-     * @throws InvalidArgumentException
151
-     * @throws InvalidDataTypeException
152
-     * @throws InvalidInterfaceException
153
-     * @throws ReflectionException
154
-     */
155
-    public function name()
156
-    {
157
-        $name = $this->get('LIN_name');
158
-        if (! $name) {
159
-            $name = ucwords(str_replace('-', ' ', $this->type()));
160
-        }
161
-        return $name;
162
-    }
163
-
164
-
165
-    /**
166
-     * Sets name
167
-     *
168
-     * @param string $name
169
-     * @throws EE_Error
170
-     * @throws InvalidArgumentException
171
-     * @throws InvalidDataTypeException
172
-     * @throws InvalidInterfaceException
173
-     * @throws ReflectionException
174
-     */
175
-    public function set_name($name)
176
-    {
177
-        $this->set('LIN_name', $name);
178
-    }
179
-
180
-
181
-    /**
182
-     * Gets desc
183
-     *
184
-     * @return string
185
-     * @throws EE_Error
186
-     * @throws InvalidArgumentException
187
-     * @throws InvalidDataTypeException
188
-     * @throws InvalidInterfaceException
189
-     * @throws ReflectionException
190
-     */
191
-    public function desc()
192
-    {
193
-        return $this->get('LIN_desc');
194
-    }
195
-
196
-
197
-    /**
198
-     * Sets desc
199
-     *
200
-     * @param string $desc
201
-     * @throws EE_Error
202
-     * @throws InvalidArgumentException
203
-     * @throws InvalidDataTypeException
204
-     * @throws InvalidInterfaceException
205
-     * @throws ReflectionException
206
-     */
207
-    public function set_desc($desc)
208
-    {
209
-        $this->set('LIN_desc', $desc);
210
-    }
211
-
212
-
213
-    /**
214
-     * Gets quantity
215
-     *
216
-     * @return int
217
-     * @throws EE_Error
218
-     * @throws InvalidArgumentException
219
-     * @throws InvalidDataTypeException
220
-     * @throws InvalidInterfaceException
221
-     * @throws ReflectionException
222
-     */
223
-    public function quantity()
224
-    {
225
-        return $this->get('LIN_quantity');
226
-    }
227
-
228
-
229
-    /**
230
-     * Sets quantity
231
-     *
232
-     * @param int $quantity
233
-     * @throws EE_Error
234
-     * @throws InvalidArgumentException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidInterfaceException
237
-     * @throws ReflectionException
238
-     */
239
-    public function set_quantity($quantity)
240
-    {
241
-        $this->set('LIN_quantity', max($quantity, 0));
242
-    }
243
-
244
-
245
-    /**
246
-     * Gets item_id
247
-     *
248
-     * @return string
249
-     * @throws EE_Error
250
-     * @throws InvalidArgumentException
251
-     * @throws InvalidDataTypeException
252
-     * @throws InvalidInterfaceException
253
-     * @throws ReflectionException
254
-     */
255
-    public function OBJ_ID()
256
-    {
257
-        return $this->get('OBJ_ID');
258
-    }
259
-
260
-
261
-    /**
262
-     * Sets item_id
263
-     *
264
-     * @param string $item_id
265
-     * @throws EE_Error
266
-     * @throws InvalidArgumentException
267
-     * @throws InvalidDataTypeException
268
-     * @throws InvalidInterfaceException
269
-     * @throws ReflectionException
270
-     */
271
-    public function set_OBJ_ID($item_id)
272
-    {
273
-        $this->set('OBJ_ID', $item_id);
274
-    }
275
-
276
-
277
-    /**
278
-     * Gets item_type
279
-     *
280
-     * @return string
281
-     * @throws EE_Error
282
-     * @throws InvalidArgumentException
283
-     * @throws InvalidDataTypeException
284
-     * @throws InvalidInterfaceException
285
-     * @throws ReflectionException
286
-     */
287
-    public function OBJ_type()
288
-    {
289
-        return $this->get('OBJ_type');
290
-    }
291
-
292
-
293
-    /**
294
-     * Gets item_type
295
-     *
296
-     * @return string
297
-     * @throws EE_Error
298
-     * @throws InvalidArgumentException
299
-     * @throws InvalidDataTypeException
300
-     * @throws InvalidInterfaceException
301
-     * @throws ReflectionException
302
-     */
303
-    public function OBJ_type_i18n()
304
-    {
305
-        $obj_type = $this->OBJ_type();
306
-        switch ($obj_type) {
307
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
308
-                $obj_type = esc_html__('Event', 'event_espresso');
309
-                break;
310
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
311
-                $obj_type = esc_html__('Price', 'event_espresso');
312
-                break;
313
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
314
-                $obj_type = esc_html__('Promotion', 'event_espresso');
315
-                break;
316
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
317
-                $obj_type = esc_html__('Ticket', 'event_espresso');
318
-                break;
319
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
320
-                $obj_type = esc_html__('Transaction', 'event_espresso');
321
-                break;
322
-        }
323
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
324
-    }
325
-
326
-
327
-    /**
328
-     * Sets item_type
329
-     *
330
-     * @param string $OBJ_type
331
-     * @throws EE_Error
332
-     * @throws InvalidArgumentException
333
-     * @throws InvalidDataTypeException
334
-     * @throws InvalidInterfaceException
335
-     * @throws ReflectionException
336
-     */
337
-    public function set_OBJ_type($OBJ_type)
338
-    {
339
-        $this->set('OBJ_type', $OBJ_type);
340
-    }
341
-
342
-
343
-    /**
344
-     * Gets unit_price
345
-     *
346
-     * @return float
347
-     * @throws EE_Error
348
-     * @throws InvalidArgumentException
349
-     * @throws InvalidDataTypeException
350
-     * @throws InvalidInterfaceException
351
-     * @throws ReflectionException
352
-     */
353
-    public function unit_price()
354
-    {
355
-        return $this->get('LIN_unit_price');
356
-    }
357
-
358
-
359
-    /**
360
-     * Sets unit_price
361
-     *
362
-     * @param float $unit_price
363
-     * @throws EE_Error
364
-     * @throws InvalidArgumentException
365
-     * @throws InvalidDataTypeException
366
-     * @throws InvalidInterfaceException
367
-     * @throws ReflectionException
368
-     */
369
-    public function set_unit_price($unit_price)
370
-    {
371
-        $this->set('LIN_unit_price', $unit_price);
372
-    }
373
-
374
-
375
-    /**
376
-     * Checks if this item is a percentage modifier or not
377
-     *
378
-     * @return boolean
379
-     * @throws EE_Error
380
-     * @throws InvalidArgumentException
381
-     * @throws InvalidDataTypeException
382
-     * @throws InvalidInterfaceException
383
-     * @throws ReflectionException
384
-     */
385
-    public function is_percent()
386
-    {
387
-        if ($this->is_tax_sub_total()) {
388
-            // tax subtotals HAVE a percent on them, that percentage only applies
389
-            // to taxable items, so its' an exception. Treat it like a flat line item
390
-            return false;
391
-        }
392
-        $unit_price = abs($this->get('LIN_unit_price'));
393
-        $percent = abs($this->get('LIN_percent'));
394
-        if ($unit_price < .001 && $percent) {
395
-            return true;
396
-        }
397
-        if ($unit_price >= .001 && ! $percent) {
398
-            return false;
399
-        }
400
-        if ($unit_price >= .001 && $percent) {
401
-            throw new EE_Error(
402
-                sprintf(
403
-                    esc_html__(
404
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
405
-                        'event_espresso'
406
-                    ),
407
-                    $unit_price,
408
-                    $percent
409
-                )
410
-            );
411
-        }
412
-        // if they're both 0, assume its not a percent item
413
-        return false;
414
-    }
415
-
416
-
417
-    /**
418
-     * Gets percent (between 100-.001)
419
-     *
420
-     * @return float
421
-     * @throws EE_Error
422
-     * @throws InvalidArgumentException
423
-     * @throws InvalidDataTypeException
424
-     * @throws InvalidInterfaceException
425
-     * @throws ReflectionException
426
-     */
427
-    public function percent()
428
-    {
429
-        return $this->get('LIN_percent');
430
-    }
431
-
432
-
433
-    /**
434
-     * Sets percent (between 100-0.01)
435
-     *
436
-     * @param float $percent
437
-     * @throws EE_Error
438
-     * @throws InvalidArgumentException
439
-     * @throws InvalidDataTypeException
440
-     * @throws InvalidInterfaceException
441
-     * @throws ReflectionException
442
-     */
443
-    public function set_percent($percent)
444
-    {
445
-        $this->set('LIN_percent', $percent);
446
-    }
447
-
448
-
449
-    /**
450
-     * Gets total
451
-     *
452
-     * @return float
453
-     * @throws EE_Error
454
-     * @throws InvalidArgumentException
455
-     * @throws InvalidDataTypeException
456
-     * @throws InvalidInterfaceException
457
-     * @throws ReflectionException
458
-     */
459
-    public function total()
460
-    {
461
-        return $this->get('LIN_total');
462
-    }
463
-
464
-
465
-    /**
466
-     * Sets total
467
-     *
468
-     * @param float $total
469
-     * @throws EE_Error
470
-     * @throws InvalidArgumentException
471
-     * @throws InvalidDataTypeException
472
-     * @throws InvalidInterfaceException
473
-     * @throws ReflectionException
474
-     */
475
-    public function set_total($total)
476
-    {
477
-        $this->set('LIN_total', $total);
478
-    }
479
-
480
-
481
-    /**
482
-     * Gets order
483
-     *
484
-     * @return int
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     * @throws ReflectionException
490
-     */
491
-    public function order()
492
-    {
493
-        return $this->get('LIN_order');
494
-    }
495
-
496
-
497
-    /**
498
-     * Sets order
499
-     *
500
-     * @param int $order
501
-     * @throws EE_Error
502
-     * @throws InvalidArgumentException
503
-     * @throws InvalidDataTypeException
504
-     * @throws InvalidInterfaceException
505
-     * @throws ReflectionException
506
-     */
507
-    public function set_order($order)
508
-    {
509
-        $this->set('LIN_order', $order);
510
-    }
511
-
512
-
513
-    /**
514
-     * Gets parent
515
-     *
516
-     * @return int
517
-     * @throws EE_Error
518
-     * @throws InvalidArgumentException
519
-     * @throws InvalidDataTypeException
520
-     * @throws InvalidInterfaceException
521
-     * @throws ReflectionException
522
-     */
523
-    public function parent_ID()
524
-    {
525
-        return $this->get('LIN_parent');
526
-    }
527
-
528
-
529
-    /**
530
-     * Sets parent
531
-     *
532
-     * @param int $parent
533
-     * @throws EE_Error
534
-     * @throws InvalidArgumentException
535
-     * @throws InvalidDataTypeException
536
-     * @throws InvalidInterfaceException
537
-     * @throws ReflectionException
538
-     */
539
-    public function set_parent_ID($parent)
540
-    {
541
-        $this->set('LIN_parent', $parent);
542
-    }
543
-
544
-
545
-    /**
546
-     * Gets type
547
-     *
548
-     * @return string
549
-     * @throws EE_Error
550
-     * @throws InvalidArgumentException
551
-     * @throws InvalidDataTypeException
552
-     * @throws InvalidInterfaceException
553
-     * @throws ReflectionException
554
-     */
555
-    public function type()
556
-    {
557
-        return $this->get('LIN_type');
558
-    }
559
-
560
-
561
-    /**
562
-     * Sets type
563
-     *
564
-     * @param string $type
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     * @throws ReflectionException
570
-     */
571
-    public function set_type($type)
572
-    {
573
-        $this->set('LIN_type', $type);
574
-    }
575
-
576
-
577
-    /**
578
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
579
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
580
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
581
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
582
-     *
583
-     * @return EE_Base_Class|EE_Line_Item
584
-     * @throws EE_Error
585
-     * @throws InvalidArgumentException
586
-     * @throws InvalidDataTypeException
587
-     * @throws InvalidInterfaceException
588
-     * @throws ReflectionException
589
-     */
590
-    public function parent()
591
-    {
592
-        return $this->ID()
593
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
594
-            : $this->_parent;
595
-    }
596
-
597
-
598
-    /**
599
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
600
-     *
601
-     * @return EE_Base_Class[]|EE_Line_Item[]
602
-     * @throws EE_Error
603
-     * @throws InvalidArgumentException
604
-     * @throws InvalidDataTypeException
605
-     * @throws InvalidInterfaceException
606
-     * @throws ReflectionException
607
-     */
608
-    public function children()
609
-    {
610
-        if ($this->ID()) {
611
-            return $this->get_model()->get_all(
612
-                array(
613
-                    array('LIN_parent' => $this->ID()),
614
-                    'order_by' => array('LIN_order' => 'ASC'),
615
-                )
616
-            );
617
-        }
618
-        if (! is_array($this->_children)) {
619
-            $this->_children = array();
620
-        }
621
-        return $this->_children;
622
-    }
623
-
624
-
625
-    /**
626
-     * Gets code
627
-     *
628
-     * @return string
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    public function code()
636
-    {
637
-        return $this->get('LIN_code');
638
-    }
639
-
640
-
641
-    /**
642
-     * Sets code
643
-     *
644
-     * @param string $code
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function set_code($code)
652
-    {
653
-        $this->set('LIN_code', $code);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets is_taxable
659
-     *
660
-     * @return boolean
661
-     * @throws EE_Error
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidDataTypeException
664
-     * @throws InvalidInterfaceException
665
-     * @throws ReflectionException
666
-     */
667
-    public function is_taxable()
668
-    {
669
-        return $this->get('LIN_is_taxable');
670
-    }
671
-
672
-
673
-    /**
674
-     * Sets is_taxable
675
-     *
676
-     * @param boolean $is_taxable
677
-     * @throws EE_Error
678
-     * @throws InvalidArgumentException
679
-     * @throws InvalidDataTypeException
680
-     * @throws InvalidInterfaceException
681
-     * @throws ReflectionException
682
-     */
683
-    public function set_is_taxable($is_taxable)
684
-    {
685
-        $this->set('LIN_is_taxable', $is_taxable);
686
-    }
687
-
688
-
689
-    /**
690
-     * Gets the object that this model-joins-to.
691
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
692
-     * EEM_Promotion_Object
693
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
694
-     *
695
-     * @return EE_Base_Class | NULL
696
-     * @throws EE_Error
697
-     * @throws InvalidArgumentException
698
-     * @throws InvalidDataTypeException
699
-     * @throws InvalidInterfaceException
700
-     * @throws ReflectionException
701
-     */
702
-    public function get_object()
703
-    {
704
-        $model_name_of_related_obj = $this->OBJ_type();
705
-        return $this->get_model()->has_relation($model_name_of_related_obj)
706
-            ? $this->get_first_related($model_name_of_related_obj)
707
-            : null;
708
-    }
709
-
710
-
711
-    /**
712
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
713
-     * (IE, if this line item is for a price or something else, will return NULL)
714
-     *
715
-     * @param array $query_params
716
-     * @return EE_Base_Class|EE_Ticket
717
-     * @throws EE_Error
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidDataTypeException
720
-     * @throws InvalidInterfaceException
721
-     * @throws ReflectionException
722
-     */
723
-    public function ticket($query_params = array())
724
-    {
725
-        // we're going to assume that when this method is called
726
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
727
-        // This can be overridden via the incoming $query_params argument
728
-        $remove_defaults = array('default_where_conditions' => 'none');
729
-        $query_params = array_merge($remove_defaults, $query_params);
730
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
731
-    }
732
-
733
-
734
-    /**
735
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
736
-     *
737
-     * @return EE_Datetime | NULL
738
-     * @throws EE_Error
739
-     * @throws InvalidArgumentException
740
-     * @throws InvalidDataTypeException
741
-     * @throws InvalidInterfaceException
742
-     * @throws ReflectionException
743
-     */
744
-    public function get_ticket_datetime()
745
-    {
746
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
747
-            $ticket = $this->ticket();
748
-            if ($ticket instanceof EE_Ticket) {
749
-                $datetime = $ticket->first_datetime();
750
-                if ($datetime instanceof EE_Datetime) {
751
-                    return $datetime;
752
-                }
753
-            }
754
-        }
755
-        return null;
756
-    }
757
-
758
-
759
-    /**
760
-     * Gets the event's name that's related to the ticket, if this is for
761
-     * a ticket
762
-     *
763
-     * @return string
764
-     * @throws EE_Error
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     * @throws ReflectionException
769
-     */
770
-    public function ticket_event_name()
771
-    {
772
-        $event_name = esc_html__('Unknown', 'event_espresso');
773
-        $event = $this->ticket_event();
774
-        if ($event instanceof EE_Event) {
775
-            $event_name = $event->name();
776
-        }
777
-        return $event_name;
778
-    }
779
-
780
-
781
-    /**
782
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
783
-     *
784
-     * @return EE_Event|null
785
-     * @throws EE_Error
786
-     * @throws InvalidArgumentException
787
-     * @throws InvalidDataTypeException
788
-     * @throws InvalidInterfaceException
789
-     * @throws ReflectionException
790
-     */
791
-    public function ticket_event()
792
-    {
793
-        $event = null;
794
-        $ticket = $this->ticket();
795
-        if ($ticket instanceof EE_Ticket) {
796
-            $datetime = $ticket->first_datetime();
797
-            if ($datetime instanceof EE_Datetime) {
798
-                $event = $datetime->event();
799
-            }
800
-        }
801
-        return $event;
802
-    }
803
-
804
-
805
-    /**
806
-     * Gets the first datetime for this lien item, assuming it's for a ticket
807
-     *
808
-     * @param string $date_format
809
-     * @param string $time_format
810
-     * @return string
811
-     * @throws EE_Error
812
-     * @throws InvalidArgumentException
813
-     * @throws InvalidDataTypeException
814
-     * @throws InvalidInterfaceException
815
-     * @throws ReflectionException
816
-     */
817
-    public function ticket_datetime_start($date_format = '', $time_format = '')
818
-    {
819
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
820
-        $datetime = $this->get_ticket_datetime();
821
-        if ($datetime) {
822
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
823
-        }
824
-        return $first_datetime_string;
825
-    }
826
-
827
-
828
-    /**
829
-     * Adds the line item as a child to this line item. If there is another child line
830
-     * item with the same LIN_code, it is overwritten by this new one
831
-     *
832
-     * @param EEI_Line_Item $line_item
833
-     * @param bool          $set_order
834
-     * @return bool success
835
-     * @throws EE_Error
836
-     * @throws InvalidArgumentException
837
-     * @throws InvalidDataTypeException
838
-     * @throws InvalidInterfaceException
839
-     * @throws ReflectionException
840
-     */
841
-    public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
842
-    {
843
-        // should we calculate the LIN_order for this line item ?
844
-        if ($set_order || $line_item->order() === null) {
845
-            $line_item->set_order(count($this->children()));
846
-        }
847
-        if ($this->ID()) {
848
-            // check for any duplicate line items (with the same code), if so, this replaces it
849
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
850
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
851
-                $this->delete_child_line_item($line_item_with_same_code->code());
852
-            }
853
-            $line_item->set_parent_ID($this->ID());
854
-            if ($this->TXN_ID()) {
855
-                $line_item->set_TXN_ID($this->TXN_ID());
856
-            }
857
-            return $line_item->save();
858
-        }
859
-        $this->_children[ $line_item->code() ] = $line_item;
860
-        if ($line_item->parent() !== $this) {
861
-            $line_item->set_parent($this);
862
-        }
863
-        return true;
864
-    }
865
-
866
-
867
-    /**
868
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
869
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
870
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
871
-     * the EE_Line_Item::_parent property.
872
-     *
873
-     * @param EE_Line_Item $line_item
874
-     * @throws EE_Error
875
-     * @throws InvalidArgumentException
876
-     * @throws InvalidDataTypeException
877
-     * @throws InvalidInterfaceException
878
-     * @throws ReflectionException
879
-     */
880
-    public function set_parent($line_item)
881
-    {
882
-        if ($this->ID()) {
883
-            if (! $line_item->ID()) {
884
-                $line_item->save();
885
-            }
886
-            $this->set_parent_ID($line_item->ID());
887
-            $this->save();
888
-        } else {
889
-            $this->_parent = $line_item;
890
-            $this->set_parent_ID($line_item->ID());
891
-        }
892
-    }
893
-
894
-
895
-    /**
896
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
897
-     * you can modify this child line item and the parent (this object) can know about them
898
-     * because it also has a reference to that line item
899
-     *
900
-     * @param string $code
901
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
902
-     * @throws EE_Error
903
-     * @throws InvalidArgumentException
904
-     * @throws InvalidDataTypeException
905
-     * @throws InvalidInterfaceException
906
-     * @throws ReflectionException
907
-     */
908
-    public function get_child_line_item($code)
909
-    {
910
-        if ($this->ID()) {
911
-            return $this->get_model()->get_one(
912
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
913
-            );
914
-        }
915
-        return isset($this->_children[ $code ])
916
-            ? $this->_children[ $code ]
917
-            : null;
918
-    }
919
-
920
-
921
-    /**
922
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
923
-     * cached on it)
924
-     *
925
-     * @return int
926
-     * @throws EE_Error
927
-     * @throws InvalidArgumentException
928
-     * @throws InvalidDataTypeException
929
-     * @throws InvalidInterfaceException
930
-     * @throws ReflectionException
931
-     */
932
-    public function delete_children_line_items()
933
-    {
934
-        if ($this->ID()) {
935
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
936
-        }
937
-        $count = count($this->_children);
938
-        $this->_children = array();
939
-        return $count;
940
-    }
941
-
942
-
943
-    /**
944
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
945
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
946
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
947
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
948
-     * deleted)
949
-     *
950
-     * @param string $code
951
-     * @param bool   $stop_search_once_found
952
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
953
-     *             the DB yet)
954
-     * @throws EE_Error
955
-     * @throws InvalidArgumentException
956
-     * @throws InvalidDataTypeException
957
-     * @throws InvalidInterfaceException
958
-     * @throws ReflectionException
959
-     */
960
-    public function delete_child_line_item($code, $stop_search_once_found = true)
961
-    {
962
-        if ($this->ID()) {
963
-            $items_deleted = 0;
964
-            if ($this->code() === $code) {
965
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
966
-                $items_deleted += (int) $this->delete();
967
-                if ($stop_search_once_found) {
968
-                    return $items_deleted;
969
-                }
970
-            }
971
-            foreach ($this->children() as $child_line_item) {
972
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
973
-            }
974
-            return $items_deleted;
975
-        }
976
-        if (isset($this->_children[ $code ])) {
977
-            unset($this->_children[ $code ]);
978
-            return 1;
979
-        }
980
-        return 0;
981
-    }
982
-
983
-
984
-    /**
985
-     * If this line item is in the database, is of the type subtotal, and
986
-     * has no children, why do we have it? It should be deleted so this function
987
-     * does that
988
-     *
989
-     * @return boolean
990
-     * @throws EE_Error
991
-     * @throws InvalidArgumentException
992
-     * @throws InvalidDataTypeException
993
-     * @throws InvalidInterfaceException
994
-     * @throws ReflectionException
995
-     */
996
-    public function delete_if_childless_subtotal()
997
-    {
998
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
999
-            return $this->delete();
1000
-        }
1001
-        return false;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Creates a code and returns a string. doesn't assign the code to this model object
1007
-     *
1008
-     * @return string
1009
-     * @throws EE_Error
1010
-     * @throws InvalidArgumentException
1011
-     * @throws InvalidDataTypeException
1012
-     * @throws InvalidInterfaceException
1013
-     * @throws ReflectionException
1014
-     */
1015
-    public function generate_code()
1016
-    {
1017
-        // each line item in the cart requires a unique identifier
1018
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * @return bool
1024
-     * @throws EE_Error
1025
-     * @throws InvalidArgumentException
1026
-     * @throws InvalidDataTypeException
1027
-     * @throws InvalidInterfaceException
1028
-     * @throws ReflectionException
1029
-     */
1030
-    public function is_tax()
1031
-    {
1032
-        return $this->type() === EEM_Line_Item::type_tax;
1033
-    }
1034
-
1035
-
1036
-    /**
1037
-     * @return bool
1038
-     * @throws EE_Error
1039
-     * @throws InvalidArgumentException
1040
-     * @throws InvalidDataTypeException
1041
-     * @throws InvalidInterfaceException
1042
-     * @throws ReflectionException
1043
-     */
1044
-    public function is_tax_sub_total()
1045
-    {
1046
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1047
-    }
1048
-
1049
-
1050
-    /**
1051
-     * @return bool
1052
-     * @throws EE_Error
1053
-     * @throws InvalidArgumentException
1054
-     * @throws InvalidDataTypeException
1055
-     * @throws InvalidInterfaceException
1056
-     * @throws ReflectionException
1057
-     */
1058
-    public function is_line_item()
1059
-    {
1060
-        return $this->type() === EEM_Line_Item::type_line_item;
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * @return bool
1066
-     * @throws EE_Error
1067
-     * @throws InvalidArgumentException
1068
-     * @throws InvalidDataTypeException
1069
-     * @throws InvalidInterfaceException
1070
-     * @throws ReflectionException
1071
-     */
1072
-    public function is_sub_line_item()
1073
-    {
1074
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1075
-    }
1076
-
1077
-
1078
-    /**
1079
-     * @return bool
1080
-     * @throws EE_Error
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws InvalidInterfaceException
1084
-     * @throws ReflectionException
1085
-     */
1086
-    public function is_sub_total()
1087
-    {
1088
-        return $this->type() === EEM_Line_Item::type_sub_total;
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * Whether or not this line item is a cancellation line item
1094
-     *
1095
-     * @return boolean
1096
-     * @throws EE_Error
1097
-     * @throws InvalidArgumentException
1098
-     * @throws InvalidDataTypeException
1099
-     * @throws InvalidInterfaceException
1100
-     * @throws ReflectionException
1101
-     */
1102
-    public function is_cancellation()
1103
-    {
1104
-        return EEM_Line_Item::type_cancellation === $this->type();
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * @return bool
1110
-     * @throws EE_Error
1111
-     * @throws InvalidArgumentException
1112
-     * @throws InvalidDataTypeException
1113
-     * @throws InvalidInterfaceException
1114
-     * @throws ReflectionException
1115
-     */
1116
-    public function is_total()
1117
-    {
1118
-        return $this->type() === EEM_Line_Item::type_total;
1119
-    }
1120
-
1121
-
1122
-    /**
1123
-     * @return bool
1124
-     * @throws EE_Error
1125
-     * @throws InvalidArgumentException
1126
-     * @throws InvalidDataTypeException
1127
-     * @throws InvalidInterfaceException
1128
-     * @throws ReflectionException
1129
-     */
1130
-    public function is_cancelled()
1131
-    {
1132
-        return $this->type() === EEM_Line_Item::type_cancellation;
1133
-    }
1134
-
1135
-
1136
-    /**
1137
-     * @return string like '2, 004.00', formatted according to the localized currency
1138
-     * @throws EE_Error
1139
-     * @throws InvalidArgumentException
1140
-     * @throws InvalidDataTypeException
1141
-     * @throws InvalidInterfaceException
1142
-     * @throws ReflectionException
1143
-     */
1144
-    public function unit_price_no_code()
1145
-    {
1146
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1147
-    }
1148
-
1149
-
1150
-    /**
1151
-     * @return string like '2, 004.00', formatted according to the localized currency
1152
-     * @throws EE_Error
1153
-     * @throws InvalidArgumentException
1154
-     * @throws InvalidDataTypeException
1155
-     * @throws InvalidInterfaceException
1156
-     * @throws ReflectionException
1157
-     */
1158
-    public function total_no_code()
1159
-    {
1160
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1161
-    }
1162
-
1163
-
1164
-    /**
1165
-     * Gets the final total on this item, taking taxes into account.
1166
-     * Has the side-effect of setting the sub-total as it was just calculated.
1167
-     * If this is used on a grand-total line item, also updates the transaction's
1168
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1169
-     * want to change a persistable transaction with info from a non-persistent line item)
1170
-     *
1171
-     * @param bool $update_txn_status
1172
-     * @return float
1173
-     * @throws EE_Error
1174
-     * @throws InvalidArgumentException
1175
-     * @throws InvalidDataTypeException
1176
-     * @throws InvalidInterfaceException
1177
-     * @throws ReflectionException
1178
-     * @throws RuntimeException
1179
-     */
1180
-    public function recalculate_total_including_taxes($update_txn_status = false)
1181
-    {
1182
-        $pre_tax_total = $this->recalculate_pre_tax_total();
1183
-        $tax_total = $this->recalculate_taxes_and_tax_total();
1184
-        $total = $pre_tax_total + $tax_total;
1185
-        // no negative totals plz
1186
-        $total = max($total, 0);
1187
-        $this->set_total($total);
1188
-        // only update the related transaction's total
1189
-        // if we intend to save this line item and its a grand total
1190
-        if (
1191
-            $this->allow_persist() && $this->type() === EEM_Line_Item::type_total
1192
-            && $this->transaction()
1193
-               instanceof
1194
-               EE_Transaction
1195
-        ) {
1196
-            $this->transaction()->set_total($total);
1197
-            if ($update_txn_status) {
1198
-                // don't save the TXN because that will be done below
1199
-                // and the following method only saves if the status changes
1200
-                $this->transaction()->update_status_based_on_total_paid(false);
1201
-            }
1202
-            if ($this->transaction()->ID()) {
1203
-                $this->transaction()->save();
1204
-            }
1205
-        }
1206
-        $this->maybe_save();
1207
-        return $total;
1208
-    }
1209
-
1210
-
1211
-    /**
1212
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1213
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1214
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1215
-     * when this is called on the grand total
1216
-     *
1217
-     * @return float
1218
-     * @throws EE_Error
1219
-     * @throws InvalidArgumentException
1220
-     * @throws InvalidDataTypeException
1221
-     * @throws InvalidInterfaceException
1222
-     * @throws ReflectionException
1223
-     */
1224
-    public function recalculate_pre_tax_total()
1225
-    {
1226
-        $total = 0;
1227
-        $my_children = $this->children();
1228
-        $has_children = ! empty($my_children);
1229
-        if ($has_children && $this->is_line_item()) {
1230
-            $total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1231
-        } elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1232
-            $total = $this->unit_price() * $this->quantity();
1233
-        } elseif ($this->is_sub_total() || $this->is_total()) {
1234
-            $total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
1235
-        } elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
1236
-            // completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
1237
-            return 0;
1238
-        }
1239
-        // ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
1240
-        if (! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()) {
1241
-            if ($this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_EVENT) {
1242
-                $this->set_quantity(1);
1243
-            }
1244
-            if (! $this->is_percent()) {
1245
-                $this->set_unit_price($total);
1246
-            }
1247
-        }
1248
-        // we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1249
-        // so it ought to be
1250
-        if (! $this->is_total()) {
1251
-            $this->set_total($total);
1252
-            // if not a percent line item, make sure we keep the unit price in sync
1253
-            if (
1254
-                $has_children
1255
-                && $this->is_line_item()
1256
-                && ! $this->is_percent()
1257
-            ) {
1258
-                if ($this->quantity() === 0) {
1259
-                    $new_unit_price = 0;
1260
-                } else {
1261
-                    $new_unit_price = $this->total() / $this->quantity();
1262
-                }
1263
-                $this->set_unit_price($new_unit_price);
1264
-            }
1265
-            $this->maybe_save();
1266
-        }
1267
-        return $total;
1268
-    }
1269
-
1270
-
1271
-    /**
1272
-     * Calculates the pretax total when this line item is a subtotal or total line item.
1273
-     * Basically does a sum-then-round approach (ie, any percent line item that are children
1274
-     * will calculate their total based on the un-rounded total we're working with so far, and
1275
-     * THEN round the result; instead of rounding as we go like with sub-line-items)
1276
-     *
1277
-     * @param float          $calculated_total_so_far
1278
-     * @param EE_Line_Item[] $my_children
1279
-     * @return float
1280
-     * @throws EE_Error
1281
-     * @throws InvalidArgumentException
1282
-     * @throws InvalidDataTypeException
1283
-     * @throws InvalidInterfaceException
1284
-     * @throws ReflectionException
1285
-     */
1286
-    protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1287
-    {
1288
-        if ($my_children === null) {
1289
-            $my_children = $this->children();
1290
-        }
1291
-        $subtotal_quantity = 0;
1292
-        // get the total of all its children
1293
-        foreach ($my_children as $child_line_item) {
1294
-            if ($child_line_item instanceof EE_Line_Item) {
1295
-                // skip line item if it is cancelled or is a tax
1296
-                if ($child_line_item->is_cancellation() || $child_line_item->is_tax()) {
1297
-                    continue;
1298
-                }
1299
-                // percentage line items are based on total so far
1300
-                if ($child_line_item->is_percent()) {
1301
-                    // round as we go so that the line items add up ok
1302
-                    $percent_total = round(
1303
-                        $calculated_total_so_far * $child_line_item->percent() / 100,
1304
-                        EE_Registry::instance()->CFG->currency->dec_plc
1305
-                    );
1306
-                    $child_line_item->set_total($percent_total);
1307
-                    // so far all percent line items should have a quantity of 1
1308
-                    // (ie, no double percent discounts. Although that might be requested someday)
1309
-                    $child_line_item->set_quantity(1);
1310
-                    $child_line_item->maybe_save();
1311
-                    $calculated_total_so_far += $percent_total;
1312
-                } else {
1313
-                    // verify flat sub-line-item quantities match their parent
1314
-                    if ($child_line_item->is_sub_line_item()) {
1315
-                        $child_line_item->set_quantity($this->quantity());
1316
-                    }
1317
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1318
-                    $subtotal_quantity += $child_line_item->quantity();
1319
-                }
1320
-            }
1321
-        }
1322
-        if ($this->is_sub_total()) {
1323
-            // no negative totals plz
1324
-            $calculated_total_so_far = max($calculated_total_so_far, 0);
1325
-            $subtotal_quantity = $subtotal_quantity > 0 ? 1 : 0;
1326
-            $this->set_quantity($subtotal_quantity);
1327
-            $this->maybe_save();
1328
-        }
1329
-        return $calculated_total_so_far;
1330
-    }
1331
-
1332
-
1333
-    /**
1334
-     * Calculates the pretax total for a normal line item, in a round-then-sum approach
1335
-     * (where each sub-line-item is applied to the base price for the line item
1336
-     * and the result is immediately rounded, rather than summing all the sub-line-items
1337
-     * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1338
-     *
1339
-     * @param float          $calculated_total_so_far
1340
-     * @param EE_Line_Item[] $my_children
1341
-     * @return float
1342
-     * @throws EE_Error
1343
-     * @throws InvalidArgumentException
1344
-     * @throws InvalidDataTypeException
1345
-     * @throws InvalidInterfaceException
1346
-     * @throws ReflectionException
1347
-     */
1348
-    protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1349
-    {
1350
-        if ($my_children === null) {
1351
-            $my_children = $this->children();
1352
-        }
1353
-        // we need to keep track of the running total for a single item,
1354
-        // because we need to round as we go
1355
-        $unit_price_for_total = 0;
1356
-        $quantity_for_total = 1;
1357
-        // get the total of all its children
1358
-        foreach ($my_children as $child_line_item) {
1359
-            if ($child_line_item instanceof EE_Line_Item) {
1360
-                // skip line item if it is cancelled or is a tax
1361
-                if ($child_line_item->is_cancellation() || $child_line_item->is_tax()) {
1362
-                    continue;
1363
-                }
1364
-                if ($child_line_item->is_percent()) {
1365
-                    // it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1366
-                    // not total multiplied by percent, because that ignores rounding along-the-way
1367
-                    $percent_unit_price = round(
1368
-                        $unit_price_for_total * $child_line_item->percent() / 100,
1369
-                        EE_Registry::instance()->CFG->currency->dec_plc
1370
-                    );
1371
-                    $percent_total = $percent_unit_price * $quantity_for_total;
1372
-                    $child_line_item->set_total($percent_total);
1373
-                    // so far all percent line items should have a quantity of 1
1374
-                    // (ie, no double percent discounts. Although that might be requested someday)
1375
-                    $child_line_item->set_quantity(1);
1376
-                    $child_line_item->maybe_save();
1377
-                    $calculated_total_so_far += $percent_total;
1378
-                    $unit_price_for_total += $percent_unit_price;
1379
-                } else {
1380
-                    // verify flat sub-line-item quantities match their parent
1381
-                    if ($child_line_item->is_sub_line_item()) {
1382
-                        $child_line_item->set_quantity($this->quantity());
1383
-                    }
1384
-                    $quantity_for_total = $child_line_item->quantity();
1385
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1386
-                    $unit_price_for_total += $child_line_item->unit_price();
1387
-                }
1388
-            }
1389
-        }
1390
-        return $calculated_total_so_far;
1391
-    }
1392
-
1393
-
1394
-    /**
1395
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1396
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1397
-     * and tax sub-total if already in the DB
1398
-     *
1399
-     * @return float
1400
-     * @throws EE_Error
1401
-     * @throws InvalidArgumentException
1402
-     * @throws InvalidDataTypeException
1403
-     * @throws InvalidInterfaceException
1404
-     * @throws ReflectionException
1405
-     */
1406
-    public function recalculate_taxes_and_tax_total()
1407
-    {
1408
-        // get all taxes
1409
-        $taxes = $this->tax_descendants();
1410
-        // calculate the pretax total
1411
-        $taxable_total = $this->taxable_total();
1412
-        $tax_total = 0;
1413
-        foreach ($taxes as $tax) {
1414
-            $total_on_this_tax = $taxable_total * $tax->percent() / 100;
1415
-            // remember the total on this line item
1416
-            $tax->set_total($total_on_this_tax);
1417
-            $tax->maybe_save();
1418
-            $tax_total += $tax->total();
1419
-        }
1420
-        $this->_recalculate_tax_sub_total();
1421
-        return $tax_total;
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1427
-     *
1428
-     * @return void
1429
-     * @throws EE_Error
1430
-     * @throws InvalidArgumentException
1431
-     * @throws InvalidDataTypeException
1432
-     * @throws InvalidInterfaceException
1433
-     * @throws ReflectionException
1434
-     */
1435
-    private function _recalculate_tax_sub_total()
1436
-    {
1437
-        if ($this->is_tax_sub_total()) {
1438
-            $total = 0;
1439
-            $total_percent = 0;
1440
-            // simply loop through all its children (which should be taxes) and sum their total
1441
-            foreach ($this->children() as $child_tax) {
1442
-                if ($child_tax instanceof EE_Line_Item) {
1443
-                    $total += $child_tax->total();
1444
-                    $total_percent += $child_tax->percent();
1445
-                }
1446
-            }
1447
-            $this->set_total($total);
1448
-            $this->set_percent($total_percent);
1449
-            $this->maybe_save();
1450
-        } elseif ($this->is_total()) {
1451
-            foreach ($this->children() as $maybe_tax_subtotal) {
1452
-                if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1453
-                    $maybe_tax_subtotal->_recalculate_tax_sub_total();
1454
-                }
1455
-            }
1456
-        }
1457
-    }
1458
-
1459
-
1460
-    /**
1461
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1462
-     * recalculate_taxes_and_total
1463
-     *
1464
-     * @return float
1465
-     * @throws EE_Error
1466
-     * @throws InvalidArgumentException
1467
-     * @throws InvalidDataTypeException
1468
-     * @throws InvalidInterfaceException
1469
-     * @throws ReflectionException
1470
-     */
1471
-    public function get_total_tax()
1472
-    {
1473
-        $this->_recalculate_tax_sub_total();
1474
-        $total = 0;
1475
-        foreach ($this->tax_descendants() as $tax_line_item) {
1476
-            if ($tax_line_item instanceof EE_Line_Item) {
1477
-                $total += $tax_line_item->total();
1478
-            }
1479
-        }
1480
-        return $total;
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * Gets the total for all the items purchased only
1486
-     *
1487
-     * @return float
1488
-     * @throws EE_Error
1489
-     * @throws InvalidArgumentException
1490
-     * @throws InvalidDataTypeException
1491
-     * @throws InvalidInterfaceException
1492
-     * @throws ReflectionException
1493
-     */
1494
-    public function get_items_total()
1495
-    {
1496
-        // by default, let's make sure we're consistent with the existing line item
1497
-        if ($this->is_total()) {
1498
-            $pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1499
-            if ($pretax_subtotal_li instanceof EE_Line_Item) {
1500
-                return $pretax_subtotal_li->total();
1501
-            }
1502
-        }
1503
-        $total = 0;
1504
-        foreach ($this->get_items() as $item) {
1505
-            if ($item instanceof EE_Line_Item) {
1506
-                $total += $item->total();
1507
-            }
1508
-        }
1509
-        return $total;
1510
-    }
1511
-
1512
-
1513
-    /**
1514
-     * Gets all the descendants (ie, children or children of children etc) that
1515
-     * are of the type 'tax'
1516
-     *
1517
-     * @return EE_Line_Item[]
1518
-     * @throws EE_Error
1519
-     */
1520
-    public function tax_descendants()
1521
-    {
1522
-        return EEH_Line_Item::get_tax_descendants($this);
1523
-    }
1524
-
1525
-
1526
-    /**
1527
-     * Gets all the real items purchased which are children of this item
1528
-     *
1529
-     * @return EE_Line_Item[]
1530
-     * @throws EE_Error
1531
-     */
1532
-    public function get_items()
1533
-    {
1534
-        return EEH_Line_Item::get_line_item_descendants($this);
1535
-    }
1536
-
1537
-
1538
-    /**
1539
-     * Returns the amount taxable among this line item's children (or if it has no children,
1540
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1541
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1542
-     * but there is a "Taxable" discount), returns 0.
1543
-     *
1544
-     * @return float
1545
-     * @throws EE_Error
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidDataTypeException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws ReflectionException
1550
-     */
1551
-    public function taxable_total()
1552
-    {
1553
-        $total = 0;
1554
-        if ($this->children()) {
1555
-            foreach ($this->children() as $child_line_item) {
1556
-                if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1557
-                    // if it's a percent item, only take into account the percent
1558
-                    // that's taxable too (the taxable total so far)
1559
-                    if ($child_line_item->is_percent()) {
1560
-                        $total += ($total * $child_line_item->percent() / 100);
1561
-                    } else {
1562
-                        $total += $child_line_item->total();
1563
-                    }
1564
-                } elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1565
-                    $total += $child_line_item->taxable_total();
1566
-                }
1567
-            }
1568
-        }
1569
-        return max($total, 0);
1570
-    }
1571
-
1572
-
1573
-    /**
1574
-     * Gets the transaction for this line item
1575
-     *
1576
-     * @return EE_Base_Class|EE_Transaction
1577
-     * @throws EE_Error
1578
-     * @throws InvalidArgumentException
1579
-     * @throws InvalidDataTypeException
1580
-     * @throws InvalidInterfaceException
1581
-     * @throws ReflectionException
1582
-     */
1583
-    public function transaction()
1584
-    {
1585
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1586
-    }
1587
-
1588
-
1589
-    /**
1590
-     * Saves this line item to the DB, and recursively saves its descendants.
1591
-     * Because there currently is no proper parent-child relation on the model,
1592
-     * save_this_and_cached() will NOT save the descendants.
1593
-     * Also sets the transaction on this line item and all its descendants before saving
1594
-     *
1595
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1596
-     * @return int count of items saved
1597
-     * @throws EE_Error
1598
-     * @throws InvalidArgumentException
1599
-     * @throws InvalidDataTypeException
1600
-     * @throws InvalidInterfaceException
1601
-     * @throws ReflectionException
1602
-     */
1603
-    public function save_this_and_descendants_to_txn($txn_id = null)
1604
-    {
1605
-        $count = 0;
1606
-        if (! $txn_id) {
1607
-            $txn_id = $this->TXN_ID();
1608
-        }
1609
-        $this->set_TXN_ID($txn_id);
1610
-        $children = $this->children();
1611
-        $count += $this->save()
1612
-            ? 1
1613
-            : 0;
1614
-        foreach ($children as $child_line_item) {
1615
-            if ($child_line_item instanceof EE_Line_Item) {
1616
-                $child_line_item->set_parent_ID($this->ID());
1617
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1618
-            }
1619
-        }
1620
-        return $count;
1621
-    }
1622
-
1623
-
1624
-    /**
1625
-     * Saves this line item to the DB, and recursively saves its descendants.
1626
-     *
1627
-     * @return int count of items saved
1628
-     * @throws EE_Error
1629
-     * @throws InvalidArgumentException
1630
-     * @throws InvalidDataTypeException
1631
-     * @throws InvalidInterfaceException
1632
-     * @throws ReflectionException
1633
-     */
1634
-    public function save_this_and_descendants()
1635
-    {
1636
-        $count = 0;
1637
-        $children = $this->children();
1638
-        $count += $this->save()
1639
-            ? 1
1640
-            : 0;
1641
-        foreach ($children as $child_line_item) {
1642
-            if ($child_line_item instanceof EE_Line_Item) {
1643
-                $child_line_item->set_parent_ID($this->ID());
1644
-                $count += $child_line_item->save_this_and_descendants();
1645
-            }
1646
-        }
1647
-        return $count;
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * returns the cancellation line item if this item was cancelled
1653
-     *
1654
-     * @return EE_Line_Item[]
1655
-     * @throws InvalidArgumentException
1656
-     * @throws InvalidInterfaceException
1657
-     * @throws InvalidDataTypeException
1658
-     * @throws ReflectionException
1659
-     * @throws EE_Error
1660
-     */
1661
-    public function get_cancellations()
1662
-    {
1663
-        EE_Registry::instance()->load_helper('Line_Item');
1664
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1665
-    }
1666
-
1667
-
1668
-    /**
1669
-     * If this item has an ID, then this saves it again to update the db
1670
-     *
1671
-     * @return int count of items saved
1672
-     * @throws EE_Error
1673
-     * @throws InvalidArgumentException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws InvalidInterfaceException
1676
-     * @throws ReflectionException
1677
-     */
1678
-    public function maybe_save()
1679
-    {
1680
-        if ($this->ID()) {
1681
-            return $this->save();
1682
-        }
1683
-        return false;
1684
-    }
1685
-
1686
-
1687
-    /**
1688
-     * clears the cached children and parent from the line item
1689
-     *
1690
-     * @return void
1691
-     */
1692
-    public function clear_related_line_item_cache()
1693
-    {
1694
-        $this->_children = array();
1695
-        $this->_parent = null;
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * @param bool $raw
1701
-     * @return int
1702
-     * @throws EE_Error
1703
-     * @throws InvalidArgumentException
1704
-     * @throws InvalidDataTypeException
1705
-     * @throws InvalidInterfaceException
1706
-     * @throws ReflectionException
1707
-     */
1708
-    public function timestamp($raw = false)
1709
-    {
1710
-        return $raw
1711
-            ? $this->get_raw('LIN_timestamp')
1712
-            : $this->get('LIN_timestamp');
1713
-    }
1714
-
1715
-
1716
-
1717
-
1718
-    /************************* DEPRECATED *************************/
1719
-    /**
1720
-     * @deprecated 4.6.0
1721
-     * @param string $type one of the constants on EEM_Line_Item
1722
-     * @return EE_Line_Item[]
1723
-     * @throws EE_Error
1724
-     */
1725
-    protected function _get_descendants_of_type($type)
1726
-    {
1727
-        EE_Error::doing_it_wrong(
1728
-            'EE_Line_Item::_get_descendants_of_type()',
1729
-            sprintf(
1730
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1731
-                'EEH_Line_Item::get_descendants_of_type()'
1732
-            ),
1733
-            '4.6.0'
1734
-        );
1735
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1736
-    }
1737
-
1738
-
1739
-    /**
1740
-     * @deprecated 4.6.0
1741
-     * @param string $type like one of the EEM_Line_Item::type_*
1742
-     * @return EE_Line_Item
1743
-     * @throws EE_Error
1744
-     * @throws InvalidArgumentException
1745
-     * @throws InvalidDataTypeException
1746
-     * @throws InvalidInterfaceException
1747
-     * @throws ReflectionException
1748
-     */
1749
-    public function get_nearest_descendant_of_type($type)
1750
-    {
1751
-        EE_Error::doing_it_wrong(
1752
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1753
-            sprintf(
1754
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1755
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1756
-            ),
1757
-            '4.6.0'
1758
-        );
1759
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1760
-    }
17
+	/**
18
+	 * for children line items (currently not a normal relation)
19
+	 *
20
+	 * @type EE_Line_Item[]
21
+	 */
22
+	protected $_children = array();
23
+
24
+	/**
25
+	 * for the parent line item
26
+	 *
27
+	 * @var EE_Line_Item
28
+	 */
29
+	protected $_parent;
30
+
31
+
32
+	/**
33
+	 * @param array  $props_n_values          incoming values
34
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
35
+	 *                                        used.)
36
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
37
+	 *                                        date_format and the second value is the time format
38
+	 * @return EE_Line_Item
39
+	 * @throws EE_Error
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 * @throws ReflectionException
44
+	 */
45
+	public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
46
+	{
47
+		$has_object = parent::_check_for_object(
48
+			$props_n_values,
49
+			__CLASS__,
50
+			$timezone,
51
+			$date_formats
52
+		);
53
+		return $has_object
54
+			? $has_object
55
+			: new self($props_n_values, false, $timezone);
56
+	}
57
+
58
+
59
+	/**
60
+	 * @param array  $props_n_values  incoming values from the database
61
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
62
+	 *                                the website will be used.
63
+	 * @return EE_Line_Item
64
+	 * @throws EE_Error
65
+	 * @throws InvalidArgumentException
66
+	 * @throws InvalidDataTypeException
67
+	 * @throws InvalidInterfaceException
68
+	 * @throws ReflectionException
69
+	 */
70
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
71
+	{
72
+		return new self($props_n_values, true, $timezone);
73
+	}
74
+
75
+
76
+	/**
77
+	 * Adds some defaults if they're not specified
78
+	 *
79
+	 * @param array  $fieldValues
80
+	 * @param bool   $bydb
81
+	 * @param string $timezone
82
+	 * @throws EE_Error
83
+	 * @throws InvalidArgumentException
84
+	 * @throws InvalidDataTypeException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws ReflectionException
87
+	 */
88
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
89
+	{
90
+		parent::__construct($fieldValues, $bydb, $timezone);
91
+		if (! $this->get('LIN_code')) {
92
+			$this->set_code($this->generate_code());
93
+		}
94
+	}
95
+
96
+
97
+	/**
98
+	 * Gets ID
99
+	 *
100
+	 * @return int
101
+	 * @throws EE_Error
102
+	 * @throws InvalidArgumentException
103
+	 * @throws InvalidDataTypeException
104
+	 * @throws InvalidInterfaceException
105
+	 * @throws ReflectionException
106
+	 */
107
+	public function ID()
108
+	{
109
+		return $this->get('LIN_ID');
110
+	}
111
+
112
+
113
+	/**
114
+	 * Gets TXN_ID
115
+	 *
116
+	 * @return int
117
+	 * @throws EE_Error
118
+	 * @throws InvalidArgumentException
119
+	 * @throws InvalidDataTypeException
120
+	 * @throws InvalidInterfaceException
121
+	 * @throws ReflectionException
122
+	 */
123
+	public function TXN_ID()
124
+	{
125
+		return $this->get('TXN_ID');
126
+	}
127
+
128
+
129
+	/**
130
+	 * Sets TXN_ID
131
+	 *
132
+	 * @param int $TXN_ID
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws ReflectionException
138
+	 */
139
+	public function set_TXN_ID($TXN_ID)
140
+	{
141
+		$this->set('TXN_ID', $TXN_ID);
142
+	}
143
+
144
+
145
+	/**
146
+	 * Gets name
147
+	 *
148
+	 * @return string
149
+	 * @throws EE_Error
150
+	 * @throws InvalidArgumentException
151
+	 * @throws InvalidDataTypeException
152
+	 * @throws InvalidInterfaceException
153
+	 * @throws ReflectionException
154
+	 */
155
+	public function name()
156
+	{
157
+		$name = $this->get('LIN_name');
158
+		if (! $name) {
159
+			$name = ucwords(str_replace('-', ' ', $this->type()));
160
+		}
161
+		return $name;
162
+	}
163
+
164
+
165
+	/**
166
+	 * Sets name
167
+	 *
168
+	 * @param string $name
169
+	 * @throws EE_Error
170
+	 * @throws InvalidArgumentException
171
+	 * @throws InvalidDataTypeException
172
+	 * @throws InvalidInterfaceException
173
+	 * @throws ReflectionException
174
+	 */
175
+	public function set_name($name)
176
+	{
177
+		$this->set('LIN_name', $name);
178
+	}
179
+
180
+
181
+	/**
182
+	 * Gets desc
183
+	 *
184
+	 * @return string
185
+	 * @throws EE_Error
186
+	 * @throws InvalidArgumentException
187
+	 * @throws InvalidDataTypeException
188
+	 * @throws InvalidInterfaceException
189
+	 * @throws ReflectionException
190
+	 */
191
+	public function desc()
192
+	{
193
+		return $this->get('LIN_desc');
194
+	}
195
+
196
+
197
+	/**
198
+	 * Sets desc
199
+	 *
200
+	 * @param string $desc
201
+	 * @throws EE_Error
202
+	 * @throws InvalidArgumentException
203
+	 * @throws InvalidDataTypeException
204
+	 * @throws InvalidInterfaceException
205
+	 * @throws ReflectionException
206
+	 */
207
+	public function set_desc($desc)
208
+	{
209
+		$this->set('LIN_desc', $desc);
210
+	}
211
+
212
+
213
+	/**
214
+	 * Gets quantity
215
+	 *
216
+	 * @return int
217
+	 * @throws EE_Error
218
+	 * @throws InvalidArgumentException
219
+	 * @throws InvalidDataTypeException
220
+	 * @throws InvalidInterfaceException
221
+	 * @throws ReflectionException
222
+	 */
223
+	public function quantity()
224
+	{
225
+		return $this->get('LIN_quantity');
226
+	}
227
+
228
+
229
+	/**
230
+	 * Sets quantity
231
+	 *
232
+	 * @param int $quantity
233
+	 * @throws EE_Error
234
+	 * @throws InvalidArgumentException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidInterfaceException
237
+	 * @throws ReflectionException
238
+	 */
239
+	public function set_quantity($quantity)
240
+	{
241
+		$this->set('LIN_quantity', max($quantity, 0));
242
+	}
243
+
244
+
245
+	/**
246
+	 * Gets item_id
247
+	 *
248
+	 * @return string
249
+	 * @throws EE_Error
250
+	 * @throws InvalidArgumentException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws InvalidInterfaceException
253
+	 * @throws ReflectionException
254
+	 */
255
+	public function OBJ_ID()
256
+	{
257
+		return $this->get('OBJ_ID');
258
+	}
259
+
260
+
261
+	/**
262
+	 * Sets item_id
263
+	 *
264
+	 * @param string $item_id
265
+	 * @throws EE_Error
266
+	 * @throws InvalidArgumentException
267
+	 * @throws InvalidDataTypeException
268
+	 * @throws InvalidInterfaceException
269
+	 * @throws ReflectionException
270
+	 */
271
+	public function set_OBJ_ID($item_id)
272
+	{
273
+		$this->set('OBJ_ID', $item_id);
274
+	}
275
+
276
+
277
+	/**
278
+	 * Gets item_type
279
+	 *
280
+	 * @return string
281
+	 * @throws EE_Error
282
+	 * @throws InvalidArgumentException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws InvalidInterfaceException
285
+	 * @throws ReflectionException
286
+	 */
287
+	public function OBJ_type()
288
+	{
289
+		return $this->get('OBJ_type');
290
+	}
291
+
292
+
293
+	/**
294
+	 * Gets item_type
295
+	 *
296
+	 * @return string
297
+	 * @throws EE_Error
298
+	 * @throws InvalidArgumentException
299
+	 * @throws InvalidDataTypeException
300
+	 * @throws InvalidInterfaceException
301
+	 * @throws ReflectionException
302
+	 */
303
+	public function OBJ_type_i18n()
304
+	{
305
+		$obj_type = $this->OBJ_type();
306
+		switch ($obj_type) {
307
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
308
+				$obj_type = esc_html__('Event', 'event_espresso');
309
+				break;
310
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
311
+				$obj_type = esc_html__('Price', 'event_espresso');
312
+				break;
313
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
314
+				$obj_type = esc_html__('Promotion', 'event_espresso');
315
+				break;
316
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
317
+				$obj_type = esc_html__('Ticket', 'event_espresso');
318
+				break;
319
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
320
+				$obj_type = esc_html__('Transaction', 'event_espresso');
321
+				break;
322
+		}
323
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
324
+	}
325
+
326
+
327
+	/**
328
+	 * Sets item_type
329
+	 *
330
+	 * @param string $OBJ_type
331
+	 * @throws EE_Error
332
+	 * @throws InvalidArgumentException
333
+	 * @throws InvalidDataTypeException
334
+	 * @throws InvalidInterfaceException
335
+	 * @throws ReflectionException
336
+	 */
337
+	public function set_OBJ_type($OBJ_type)
338
+	{
339
+		$this->set('OBJ_type', $OBJ_type);
340
+	}
341
+
342
+
343
+	/**
344
+	 * Gets unit_price
345
+	 *
346
+	 * @return float
347
+	 * @throws EE_Error
348
+	 * @throws InvalidArgumentException
349
+	 * @throws InvalidDataTypeException
350
+	 * @throws InvalidInterfaceException
351
+	 * @throws ReflectionException
352
+	 */
353
+	public function unit_price()
354
+	{
355
+		return $this->get('LIN_unit_price');
356
+	}
357
+
358
+
359
+	/**
360
+	 * Sets unit_price
361
+	 *
362
+	 * @param float $unit_price
363
+	 * @throws EE_Error
364
+	 * @throws InvalidArgumentException
365
+	 * @throws InvalidDataTypeException
366
+	 * @throws InvalidInterfaceException
367
+	 * @throws ReflectionException
368
+	 */
369
+	public function set_unit_price($unit_price)
370
+	{
371
+		$this->set('LIN_unit_price', $unit_price);
372
+	}
373
+
374
+
375
+	/**
376
+	 * Checks if this item is a percentage modifier or not
377
+	 *
378
+	 * @return boolean
379
+	 * @throws EE_Error
380
+	 * @throws InvalidArgumentException
381
+	 * @throws InvalidDataTypeException
382
+	 * @throws InvalidInterfaceException
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function is_percent()
386
+	{
387
+		if ($this->is_tax_sub_total()) {
388
+			// tax subtotals HAVE a percent on them, that percentage only applies
389
+			// to taxable items, so its' an exception. Treat it like a flat line item
390
+			return false;
391
+		}
392
+		$unit_price = abs($this->get('LIN_unit_price'));
393
+		$percent = abs($this->get('LIN_percent'));
394
+		if ($unit_price < .001 && $percent) {
395
+			return true;
396
+		}
397
+		if ($unit_price >= .001 && ! $percent) {
398
+			return false;
399
+		}
400
+		if ($unit_price >= .001 && $percent) {
401
+			throw new EE_Error(
402
+				sprintf(
403
+					esc_html__(
404
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
405
+						'event_espresso'
406
+					),
407
+					$unit_price,
408
+					$percent
409
+				)
410
+			);
411
+		}
412
+		// if they're both 0, assume its not a percent item
413
+		return false;
414
+	}
415
+
416
+
417
+	/**
418
+	 * Gets percent (between 100-.001)
419
+	 *
420
+	 * @return float
421
+	 * @throws EE_Error
422
+	 * @throws InvalidArgumentException
423
+	 * @throws InvalidDataTypeException
424
+	 * @throws InvalidInterfaceException
425
+	 * @throws ReflectionException
426
+	 */
427
+	public function percent()
428
+	{
429
+		return $this->get('LIN_percent');
430
+	}
431
+
432
+
433
+	/**
434
+	 * Sets percent (between 100-0.01)
435
+	 *
436
+	 * @param float $percent
437
+	 * @throws EE_Error
438
+	 * @throws InvalidArgumentException
439
+	 * @throws InvalidDataTypeException
440
+	 * @throws InvalidInterfaceException
441
+	 * @throws ReflectionException
442
+	 */
443
+	public function set_percent($percent)
444
+	{
445
+		$this->set('LIN_percent', $percent);
446
+	}
447
+
448
+
449
+	/**
450
+	 * Gets total
451
+	 *
452
+	 * @return float
453
+	 * @throws EE_Error
454
+	 * @throws InvalidArgumentException
455
+	 * @throws InvalidDataTypeException
456
+	 * @throws InvalidInterfaceException
457
+	 * @throws ReflectionException
458
+	 */
459
+	public function total()
460
+	{
461
+		return $this->get('LIN_total');
462
+	}
463
+
464
+
465
+	/**
466
+	 * Sets total
467
+	 *
468
+	 * @param float $total
469
+	 * @throws EE_Error
470
+	 * @throws InvalidArgumentException
471
+	 * @throws InvalidDataTypeException
472
+	 * @throws InvalidInterfaceException
473
+	 * @throws ReflectionException
474
+	 */
475
+	public function set_total($total)
476
+	{
477
+		$this->set('LIN_total', $total);
478
+	}
479
+
480
+
481
+	/**
482
+	 * Gets order
483
+	 *
484
+	 * @return int
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 * @throws ReflectionException
490
+	 */
491
+	public function order()
492
+	{
493
+		return $this->get('LIN_order');
494
+	}
495
+
496
+
497
+	/**
498
+	 * Sets order
499
+	 *
500
+	 * @param int $order
501
+	 * @throws EE_Error
502
+	 * @throws InvalidArgumentException
503
+	 * @throws InvalidDataTypeException
504
+	 * @throws InvalidInterfaceException
505
+	 * @throws ReflectionException
506
+	 */
507
+	public function set_order($order)
508
+	{
509
+		$this->set('LIN_order', $order);
510
+	}
511
+
512
+
513
+	/**
514
+	 * Gets parent
515
+	 *
516
+	 * @return int
517
+	 * @throws EE_Error
518
+	 * @throws InvalidArgumentException
519
+	 * @throws InvalidDataTypeException
520
+	 * @throws InvalidInterfaceException
521
+	 * @throws ReflectionException
522
+	 */
523
+	public function parent_ID()
524
+	{
525
+		return $this->get('LIN_parent');
526
+	}
527
+
528
+
529
+	/**
530
+	 * Sets parent
531
+	 *
532
+	 * @param int $parent
533
+	 * @throws EE_Error
534
+	 * @throws InvalidArgumentException
535
+	 * @throws InvalidDataTypeException
536
+	 * @throws InvalidInterfaceException
537
+	 * @throws ReflectionException
538
+	 */
539
+	public function set_parent_ID($parent)
540
+	{
541
+		$this->set('LIN_parent', $parent);
542
+	}
543
+
544
+
545
+	/**
546
+	 * Gets type
547
+	 *
548
+	 * @return string
549
+	 * @throws EE_Error
550
+	 * @throws InvalidArgumentException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws InvalidInterfaceException
553
+	 * @throws ReflectionException
554
+	 */
555
+	public function type()
556
+	{
557
+		return $this->get('LIN_type');
558
+	}
559
+
560
+
561
+	/**
562
+	 * Sets type
563
+	 *
564
+	 * @param string $type
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 * @throws ReflectionException
570
+	 */
571
+	public function set_type($type)
572
+	{
573
+		$this->set('LIN_type', $type);
574
+	}
575
+
576
+
577
+	/**
578
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
579
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
580
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
581
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
582
+	 *
583
+	 * @return EE_Base_Class|EE_Line_Item
584
+	 * @throws EE_Error
585
+	 * @throws InvalidArgumentException
586
+	 * @throws InvalidDataTypeException
587
+	 * @throws InvalidInterfaceException
588
+	 * @throws ReflectionException
589
+	 */
590
+	public function parent()
591
+	{
592
+		return $this->ID()
593
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
594
+			: $this->_parent;
595
+	}
596
+
597
+
598
+	/**
599
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
600
+	 *
601
+	 * @return EE_Base_Class[]|EE_Line_Item[]
602
+	 * @throws EE_Error
603
+	 * @throws InvalidArgumentException
604
+	 * @throws InvalidDataTypeException
605
+	 * @throws InvalidInterfaceException
606
+	 * @throws ReflectionException
607
+	 */
608
+	public function children()
609
+	{
610
+		if ($this->ID()) {
611
+			return $this->get_model()->get_all(
612
+				array(
613
+					array('LIN_parent' => $this->ID()),
614
+					'order_by' => array('LIN_order' => 'ASC'),
615
+				)
616
+			);
617
+		}
618
+		if (! is_array($this->_children)) {
619
+			$this->_children = array();
620
+		}
621
+		return $this->_children;
622
+	}
623
+
624
+
625
+	/**
626
+	 * Gets code
627
+	 *
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function code()
636
+	{
637
+		return $this->get('LIN_code');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Sets code
643
+	 *
644
+	 * @param string $code
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function set_code($code)
652
+	{
653
+		$this->set('LIN_code', $code);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets is_taxable
659
+	 *
660
+	 * @return boolean
661
+	 * @throws EE_Error
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidDataTypeException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws ReflectionException
666
+	 */
667
+	public function is_taxable()
668
+	{
669
+		return $this->get('LIN_is_taxable');
670
+	}
671
+
672
+
673
+	/**
674
+	 * Sets is_taxable
675
+	 *
676
+	 * @param boolean $is_taxable
677
+	 * @throws EE_Error
678
+	 * @throws InvalidArgumentException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws InvalidInterfaceException
681
+	 * @throws ReflectionException
682
+	 */
683
+	public function set_is_taxable($is_taxable)
684
+	{
685
+		$this->set('LIN_is_taxable', $is_taxable);
686
+	}
687
+
688
+
689
+	/**
690
+	 * Gets the object that this model-joins-to.
691
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
692
+	 * EEM_Promotion_Object
693
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
694
+	 *
695
+	 * @return EE_Base_Class | NULL
696
+	 * @throws EE_Error
697
+	 * @throws InvalidArgumentException
698
+	 * @throws InvalidDataTypeException
699
+	 * @throws InvalidInterfaceException
700
+	 * @throws ReflectionException
701
+	 */
702
+	public function get_object()
703
+	{
704
+		$model_name_of_related_obj = $this->OBJ_type();
705
+		return $this->get_model()->has_relation($model_name_of_related_obj)
706
+			? $this->get_first_related($model_name_of_related_obj)
707
+			: null;
708
+	}
709
+
710
+
711
+	/**
712
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
713
+	 * (IE, if this line item is for a price or something else, will return NULL)
714
+	 *
715
+	 * @param array $query_params
716
+	 * @return EE_Base_Class|EE_Ticket
717
+	 * @throws EE_Error
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidDataTypeException
720
+	 * @throws InvalidInterfaceException
721
+	 * @throws ReflectionException
722
+	 */
723
+	public function ticket($query_params = array())
724
+	{
725
+		// we're going to assume that when this method is called
726
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
727
+		// This can be overridden via the incoming $query_params argument
728
+		$remove_defaults = array('default_where_conditions' => 'none');
729
+		$query_params = array_merge($remove_defaults, $query_params);
730
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
731
+	}
732
+
733
+
734
+	/**
735
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
736
+	 *
737
+	 * @return EE_Datetime | NULL
738
+	 * @throws EE_Error
739
+	 * @throws InvalidArgumentException
740
+	 * @throws InvalidDataTypeException
741
+	 * @throws InvalidInterfaceException
742
+	 * @throws ReflectionException
743
+	 */
744
+	public function get_ticket_datetime()
745
+	{
746
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
747
+			$ticket = $this->ticket();
748
+			if ($ticket instanceof EE_Ticket) {
749
+				$datetime = $ticket->first_datetime();
750
+				if ($datetime instanceof EE_Datetime) {
751
+					return $datetime;
752
+				}
753
+			}
754
+		}
755
+		return null;
756
+	}
757
+
758
+
759
+	/**
760
+	 * Gets the event's name that's related to the ticket, if this is for
761
+	 * a ticket
762
+	 *
763
+	 * @return string
764
+	 * @throws EE_Error
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 * @throws ReflectionException
769
+	 */
770
+	public function ticket_event_name()
771
+	{
772
+		$event_name = esc_html__('Unknown', 'event_espresso');
773
+		$event = $this->ticket_event();
774
+		if ($event instanceof EE_Event) {
775
+			$event_name = $event->name();
776
+		}
777
+		return $event_name;
778
+	}
779
+
780
+
781
+	/**
782
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
783
+	 *
784
+	 * @return EE_Event|null
785
+	 * @throws EE_Error
786
+	 * @throws InvalidArgumentException
787
+	 * @throws InvalidDataTypeException
788
+	 * @throws InvalidInterfaceException
789
+	 * @throws ReflectionException
790
+	 */
791
+	public function ticket_event()
792
+	{
793
+		$event = null;
794
+		$ticket = $this->ticket();
795
+		if ($ticket instanceof EE_Ticket) {
796
+			$datetime = $ticket->first_datetime();
797
+			if ($datetime instanceof EE_Datetime) {
798
+				$event = $datetime->event();
799
+			}
800
+		}
801
+		return $event;
802
+	}
803
+
804
+
805
+	/**
806
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
807
+	 *
808
+	 * @param string $date_format
809
+	 * @param string $time_format
810
+	 * @return string
811
+	 * @throws EE_Error
812
+	 * @throws InvalidArgumentException
813
+	 * @throws InvalidDataTypeException
814
+	 * @throws InvalidInterfaceException
815
+	 * @throws ReflectionException
816
+	 */
817
+	public function ticket_datetime_start($date_format = '', $time_format = '')
818
+	{
819
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
820
+		$datetime = $this->get_ticket_datetime();
821
+		if ($datetime) {
822
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
823
+		}
824
+		return $first_datetime_string;
825
+	}
826
+
827
+
828
+	/**
829
+	 * Adds the line item as a child to this line item. If there is another child line
830
+	 * item with the same LIN_code, it is overwritten by this new one
831
+	 *
832
+	 * @param EEI_Line_Item $line_item
833
+	 * @param bool          $set_order
834
+	 * @return bool success
835
+	 * @throws EE_Error
836
+	 * @throws InvalidArgumentException
837
+	 * @throws InvalidDataTypeException
838
+	 * @throws InvalidInterfaceException
839
+	 * @throws ReflectionException
840
+	 */
841
+	public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
842
+	{
843
+		// should we calculate the LIN_order for this line item ?
844
+		if ($set_order || $line_item->order() === null) {
845
+			$line_item->set_order(count($this->children()));
846
+		}
847
+		if ($this->ID()) {
848
+			// check for any duplicate line items (with the same code), if so, this replaces it
849
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
850
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
851
+				$this->delete_child_line_item($line_item_with_same_code->code());
852
+			}
853
+			$line_item->set_parent_ID($this->ID());
854
+			if ($this->TXN_ID()) {
855
+				$line_item->set_TXN_ID($this->TXN_ID());
856
+			}
857
+			return $line_item->save();
858
+		}
859
+		$this->_children[ $line_item->code() ] = $line_item;
860
+		if ($line_item->parent() !== $this) {
861
+			$line_item->set_parent($this);
862
+		}
863
+		return true;
864
+	}
865
+
866
+
867
+	/**
868
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
869
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
870
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
871
+	 * the EE_Line_Item::_parent property.
872
+	 *
873
+	 * @param EE_Line_Item $line_item
874
+	 * @throws EE_Error
875
+	 * @throws InvalidArgumentException
876
+	 * @throws InvalidDataTypeException
877
+	 * @throws InvalidInterfaceException
878
+	 * @throws ReflectionException
879
+	 */
880
+	public function set_parent($line_item)
881
+	{
882
+		if ($this->ID()) {
883
+			if (! $line_item->ID()) {
884
+				$line_item->save();
885
+			}
886
+			$this->set_parent_ID($line_item->ID());
887
+			$this->save();
888
+		} else {
889
+			$this->_parent = $line_item;
890
+			$this->set_parent_ID($line_item->ID());
891
+		}
892
+	}
893
+
894
+
895
+	/**
896
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
897
+	 * you can modify this child line item and the parent (this object) can know about them
898
+	 * because it also has a reference to that line item
899
+	 *
900
+	 * @param string $code
901
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
902
+	 * @throws EE_Error
903
+	 * @throws InvalidArgumentException
904
+	 * @throws InvalidDataTypeException
905
+	 * @throws InvalidInterfaceException
906
+	 * @throws ReflectionException
907
+	 */
908
+	public function get_child_line_item($code)
909
+	{
910
+		if ($this->ID()) {
911
+			return $this->get_model()->get_one(
912
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
913
+			);
914
+		}
915
+		return isset($this->_children[ $code ])
916
+			? $this->_children[ $code ]
917
+			: null;
918
+	}
919
+
920
+
921
+	/**
922
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
923
+	 * cached on it)
924
+	 *
925
+	 * @return int
926
+	 * @throws EE_Error
927
+	 * @throws InvalidArgumentException
928
+	 * @throws InvalidDataTypeException
929
+	 * @throws InvalidInterfaceException
930
+	 * @throws ReflectionException
931
+	 */
932
+	public function delete_children_line_items()
933
+	{
934
+		if ($this->ID()) {
935
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
936
+		}
937
+		$count = count($this->_children);
938
+		$this->_children = array();
939
+		return $count;
940
+	}
941
+
942
+
943
+	/**
944
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
945
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
946
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
947
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
948
+	 * deleted)
949
+	 *
950
+	 * @param string $code
951
+	 * @param bool   $stop_search_once_found
952
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
953
+	 *             the DB yet)
954
+	 * @throws EE_Error
955
+	 * @throws InvalidArgumentException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws InvalidInterfaceException
958
+	 * @throws ReflectionException
959
+	 */
960
+	public function delete_child_line_item($code, $stop_search_once_found = true)
961
+	{
962
+		if ($this->ID()) {
963
+			$items_deleted = 0;
964
+			if ($this->code() === $code) {
965
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
966
+				$items_deleted += (int) $this->delete();
967
+				if ($stop_search_once_found) {
968
+					return $items_deleted;
969
+				}
970
+			}
971
+			foreach ($this->children() as $child_line_item) {
972
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
973
+			}
974
+			return $items_deleted;
975
+		}
976
+		if (isset($this->_children[ $code ])) {
977
+			unset($this->_children[ $code ]);
978
+			return 1;
979
+		}
980
+		return 0;
981
+	}
982
+
983
+
984
+	/**
985
+	 * If this line item is in the database, is of the type subtotal, and
986
+	 * has no children, why do we have it? It should be deleted so this function
987
+	 * does that
988
+	 *
989
+	 * @return boolean
990
+	 * @throws EE_Error
991
+	 * @throws InvalidArgumentException
992
+	 * @throws InvalidDataTypeException
993
+	 * @throws InvalidInterfaceException
994
+	 * @throws ReflectionException
995
+	 */
996
+	public function delete_if_childless_subtotal()
997
+	{
998
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
999
+			return $this->delete();
1000
+		}
1001
+		return false;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1007
+	 *
1008
+	 * @return string
1009
+	 * @throws EE_Error
1010
+	 * @throws InvalidArgumentException
1011
+	 * @throws InvalidDataTypeException
1012
+	 * @throws InvalidInterfaceException
1013
+	 * @throws ReflectionException
1014
+	 */
1015
+	public function generate_code()
1016
+	{
1017
+		// each line item in the cart requires a unique identifier
1018
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * @return bool
1024
+	 * @throws EE_Error
1025
+	 * @throws InvalidArgumentException
1026
+	 * @throws InvalidDataTypeException
1027
+	 * @throws InvalidInterfaceException
1028
+	 * @throws ReflectionException
1029
+	 */
1030
+	public function is_tax()
1031
+	{
1032
+		return $this->type() === EEM_Line_Item::type_tax;
1033
+	}
1034
+
1035
+
1036
+	/**
1037
+	 * @return bool
1038
+	 * @throws EE_Error
1039
+	 * @throws InvalidArgumentException
1040
+	 * @throws InvalidDataTypeException
1041
+	 * @throws InvalidInterfaceException
1042
+	 * @throws ReflectionException
1043
+	 */
1044
+	public function is_tax_sub_total()
1045
+	{
1046
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1047
+	}
1048
+
1049
+
1050
+	/**
1051
+	 * @return bool
1052
+	 * @throws EE_Error
1053
+	 * @throws InvalidArgumentException
1054
+	 * @throws InvalidDataTypeException
1055
+	 * @throws InvalidInterfaceException
1056
+	 * @throws ReflectionException
1057
+	 */
1058
+	public function is_line_item()
1059
+	{
1060
+		return $this->type() === EEM_Line_Item::type_line_item;
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * @return bool
1066
+	 * @throws EE_Error
1067
+	 * @throws InvalidArgumentException
1068
+	 * @throws InvalidDataTypeException
1069
+	 * @throws InvalidInterfaceException
1070
+	 * @throws ReflectionException
1071
+	 */
1072
+	public function is_sub_line_item()
1073
+	{
1074
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1075
+	}
1076
+
1077
+
1078
+	/**
1079
+	 * @return bool
1080
+	 * @throws EE_Error
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws InvalidInterfaceException
1084
+	 * @throws ReflectionException
1085
+	 */
1086
+	public function is_sub_total()
1087
+	{
1088
+		return $this->type() === EEM_Line_Item::type_sub_total;
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * Whether or not this line item is a cancellation line item
1094
+	 *
1095
+	 * @return boolean
1096
+	 * @throws EE_Error
1097
+	 * @throws InvalidArgumentException
1098
+	 * @throws InvalidDataTypeException
1099
+	 * @throws InvalidInterfaceException
1100
+	 * @throws ReflectionException
1101
+	 */
1102
+	public function is_cancellation()
1103
+	{
1104
+		return EEM_Line_Item::type_cancellation === $this->type();
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * @return bool
1110
+	 * @throws EE_Error
1111
+	 * @throws InvalidArgumentException
1112
+	 * @throws InvalidDataTypeException
1113
+	 * @throws InvalidInterfaceException
1114
+	 * @throws ReflectionException
1115
+	 */
1116
+	public function is_total()
1117
+	{
1118
+		return $this->type() === EEM_Line_Item::type_total;
1119
+	}
1120
+
1121
+
1122
+	/**
1123
+	 * @return bool
1124
+	 * @throws EE_Error
1125
+	 * @throws InvalidArgumentException
1126
+	 * @throws InvalidDataTypeException
1127
+	 * @throws InvalidInterfaceException
1128
+	 * @throws ReflectionException
1129
+	 */
1130
+	public function is_cancelled()
1131
+	{
1132
+		return $this->type() === EEM_Line_Item::type_cancellation;
1133
+	}
1134
+
1135
+
1136
+	/**
1137
+	 * @return string like '2, 004.00', formatted according to the localized currency
1138
+	 * @throws EE_Error
1139
+	 * @throws InvalidArgumentException
1140
+	 * @throws InvalidDataTypeException
1141
+	 * @throws InvalidInterfaceException
1142
+	 * @throws ReflectionException
1143
+	 */
1144
+	public function unit_price_no_code()
1145
+	{
1146
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1147
+	}
1148
+
1149
+
1150
+	/**
1151
+	 * @return string like '2, 004.00', formatted according to the localized currency
1152
+	 * @throws EE_Error
1153
+	 * @throws InvalidArgumentException
1154
+	 * @throws InvalidDataTypeException
1155
+	 * @throws InvalidInterfaceException
1156
+	 * @throws ReflectionException
1157
+	 */
1158
+	public function total_no_code()
1159
+	{
1160
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1161
+	}
1162
+
1163
+
1164
+	/**
1165
+	 * Gets the final total on this item, taking taxes into account.
1166
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1167
+	 * If this is used on a grand-total line item, also updates the transaction's
1168
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1169
+	 * want to change a persistable transaction with info from a non-persistent line item)
1170
+	 *
1171
+	 * @param bool $update_txn_status
1172
+	 * @return float
1173
+	 * @throws EE_Error
1174
+	 * @throws InvalidArgumentException
1175
+	 * @throws InvalidDataTypeException
1176
+	 * @throws InvalidInterfaceException
1177
+	 * @throws ReflectionException
1178
+	 * @throws RuntimeException
1179
+	 */
1180
+	public function recalculate_total_including_taxes($update_txn_status = false)
1181
+	{
1182
+		$pre_tax_total = $this->recalculate_pre_tax_total();
1183
+		$tax_total = $this->recalculate_taxes_and_tax_total();
1184
+		$total = $pre_tax_total + $tax_total;
1185
+		// no negative totals plz
1186
+		$total = max($total, 0);
1187
+		$this->set_total($total);
1188
+		// only update the related transaction's total
1189
+		// if we intend to save this line item and its a grand total
1190
+		if (
1191
+			$this->allow_persist() && $this->type() === EEM_Line_Item::type_total
1192
+			&& $this->transaction()
1193
+			   instanceof
1194
+			   EE_Transaction
1195
+		) {
1196
+			$this->transaction()->set_total($total);
1197
+			if ($update_txn_status) {
1198
+				// don't save the TXN because that will be done below
1199
+				// and the following method only saves if the status changes
1200
+				$this->transaction()->update_status_based_on_total_paid(false);
1201
+			}
1202
+			if ($this->transaction()->ID()) {
1203
+				$this->transaction()->save();
1204
+			}
1205
+		}
1206
+		$this->maybe_save();
1207
+		return $total;
1208
+	}
1209
+
1210
+
1211
+	/**
1212
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1213
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1214
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1215
+	 * when this is called on the grand total
1216
+	 *
1217
+	 * @return float
1218
+	 * @throws EE_Error
1219
+	 * @throws InvalidArgumentException
1220
+	 * @throws InvalidDataTypeException
1221
+	 * @throws InvalidInterfaceException
1222
+	 * @throws ReflectionException
1223
+	 */
1224
+	public function recalculate_pre_tax_total()
1225
+	{
1226
+		$total = 0;
1227
+		$my_children = $this->children();
1228
+		$has_children = ! empty($my_children);
1229
+		if ($has_children && $this->is_line_item()) {
1230
+			$total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1231
+		} elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1232
+			$total = $this->unit_price() * $this->quantity();
1233
+		} elseif ($this->is_sub_total() || $this->is_total()) {
1234
+			$total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
1235
+		} elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
1236
+			// completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
1237
+			return 0;
1238
+		}
1239
+		// ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
1240
+		if (! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()) {
1241
+			if ($this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_EVENT) {
1242
+				$this->set_quantity(1);
1243
+			}
1244
+			if (! $this->is_percent()) {
1245
+				$this->set_unit_price($total);
1246
+			}
1247
+		}
1248
+		// we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1249
+		// so it ought to be
1250
+		if (! $this->is_total()) {
1251
+			$this->set_total($total);
1252
+			// if not a percent line item, make sure we keep the unit price in sync
1253
+			if (
1254
+				$has_children
1255
+				&& $this->is_line_item()
1256
+				&& ! $this->is_percent()
1257
+			) {
1258
+				if ($this->quantity() === 0) {
1259
+					$new_unit_price = 0;
1260
+				} else {
1261
+					$new_unit_price = $this->total() / $this->quantity();
1262
+				}
1263
+				$this->set_unit_price($new_unit_price);
1264
+			}
1265
+			$this->maybe_save();
1266
+		}
1267
+		return $total;
1268
+	}
1269
+
1270
+
1271
+	/**
1272
+	 * Calculates the pretax total when this line item is a subtotal or total line item.
1273
+	 * Basically does a sum-then-round approach (ie, any percent line item that are children
1274
+	 * will calculate their total based on the un-rounded total we're working with so far, and
1275
+	 * THEN round the result; instead of rounding as we go like with sub-line-items)
1276
+	 *
1277
+	 * @param float          $calculated_total_so_far
1278
+	 * @param EE_Line_Item[] $my_children
1279
+	 * @return float
1280
+	 * @throws EE_Error
1281
+	 * @throws InvalidArgumentException
1282
+	 * @throws InvalidDataTypeException
1283
+	 * @throws InvalidInterfaceException
1284
+	 * @throws ReflectionException
1285
+	 */
1286
+	protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1287
+	{
1288
+		if ($my_children === null) {
1289
+			$my_children = $this->children();
1290
+		}
1291
+		$subtotal_quantity = 0;
1292
+		// get the total of all its children
1293
+		foreach ($my_children as $child_line_item) {
1294
+			if ($child_line_item instanceof EE_Line_Item) {
1295
+				// skip line item if it is cancelled or is a tax
1296
+				if ($child_line_item->is_cancellation() || $child_line_item->is_tax()) {
1297
+					continue;
1298
+				}
1299
+				// percentage line items are based on total so far
1300
+				if ($child_line_item->is_percent()) {
1301
+					// round as we go so that the line items add up ok
1302
+					$percent_total = round(
1303
+						$calculated_total_so_far * $child_line_item->percent() / 100,
1304
+						EE_Registry::instance()->CFG->currency->dec_plc
1305
+					);
1306
+					$child_line_item->set_total($percent_total);
1307
+					// so far all percent line items should have a quantity of 1
1308
+					// (ie, no double percent discounts. Although that might be requested someday)
1309
+					$child_line_item->set_quantity(1);
1310
+					$child_line_item->maybe_save();
1311
+					$calculated_total_so_far += $percent_total;
1312
+				} else {
1313
+					// verify flat sub-line-item quantities match their parent
1314
+					if ($child_line_item->is_sub_line_item()) {
1315
+						$child_line_item->set_quantity($this->quantity());
1316
+					}
1317
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1318
+					$subtotal_quantity += $child_line_item->quantity();
1319
+				}
1320
+			}
1321
+		}
1322
+		if ($this->is_sub_total()) {
1323
+			// no negative totals plz
1324
+			$calculated_total_so_far = max($calculated_total_so_far, 0);
1325
+			$subtotal_quantity = $subtotal_quantity > 0 ? 1 : 0;
1326
+			$this->set_quantity($subtotal_quantity);
1327
+			$this->maybe_save();
1328
+		}
1329
+		return $calculated_total_so_far;
1330
+	}
1331
+
1332
+
1333
+	/**
1334
+	 * Calculates the pretax total for a normal line item, in a round-then-sum approach
1335
+	 * (where each sub-line-item is applied to the base price for the line item
1336
+	 * and the result is immediately rounded, rather than summing all the sub-line-items
1337
+	 * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1338
+	 *
1339
+	 * @param float          $calculated_total_so_far
1340
+	 * @param EE_Line_Item[] $my_children
1341
+	 * @return float
1342
+	 * @throws EE_Error
1343
+	 * @throws InvalidArgumentException
1344
+	 * @throws InvalidDataTypeException
1345
+	 * @throws InvalidInterfaceException
1346
+	 * @throws ReflectionException
1347
+	 */
1348
+	protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1349
+	{
1350
+		if ($my_children === null) {
1351
+			$my_children = $this->children();
1352
+		}
1353
+		// we need to keep track of the running total for a single item,
1354
+		// because we need to round as we go
1355
+		$unit_price_for_total = 0;
1356
+		$quantity_for_total = 1;
1357
+		// get the total of all its children
1358
+		foreach ($my_children as $child_line_item) {
1359
+			if ($child_line_item instanceof EE_Line_Item) {
1360
+				// skip line item if it is cancelled or is a tax
1361
+				if ($child_line_item->is_cancellation() || $child_line_item->is_tax()) {
1362
+					continue;
1363
+				}
1364
+				if ($child_line_item->is_percent()) {
1365
+					// it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1366
+					// not total multiplied by percent, because that ignores rounding along-the-way
1367
+					$percent_unit_price = round(
1368
+						$unit_price_for_total * $child_line_item->percent() / 100,
1369
+						EE_Registry::instance()->CFG->currency->dec_plc
1370
+					);
1371
+					$percent_total = $percent_unit_price * $quantity_for_total;
1372
+					$child_line_item->set_total($percent_total);
1373
+					// so far all percent line items should have a quantity of 1
1374
+					// (ie, no double percent discounts. Although that might be requested someday)
1375
+					$child_line_item->set_quantity(1);
1376
+					$child_line_item->maybe_save();
1377
+					$calculated_total_so_far += $percent_total;
1378
+					$unit_price_for_total += $percent_unit_price;
1379
+				} else {
1380
+					// verify flat sub-line-item quantities match their parent
1381
+					if ($child_line_item->is_sub_line_item()) {
1382
+						$child_line_item->set_quantity($this->quantity());
1383
+					}
1384
+					$quantity_for_total = $child_line_item->quantity();
1385
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1386
+					$unit_price_for_total += $child_line_item->unit_price();
1387
+				}
1388
+			}
1389
+		}
1390
+		return $calculated_total_so_far;
1391
+	}
1392
+
1393
+
1394
+	/**
1395
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1396
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1397
+	 * and tax sub-total if already in the DB
1398
+	 *
1399
+	 * @return float
1400
+	 * @throws EE_Error
1401
+	 * @throws InvalidArgumentException
1402
+	 * @throws InvalidDataTypeException
1403
+	 * @throws InvalidInterfaceException
1404
+	 * @throws ReflectionException
1405
+	 */
1406
+	public function recalculate_taxes_and_tax_total()
1407
+	{
1408
+		// get all taxes
1409
+		$taxes = $this->tax_descendants();
1410
+		// calculate the pretax total
1411
+		$taxable_total = $this->taxable_total();
1412
+		$tax_total = 0;
1413
+		foreach ($taxes as $tax) {
1414
+			$total_on_this_tax = $taxable_total * $tax->percent() / 100;
1415
+			// remember the total on this line item
1416
+			$tax->set_total($total_on_this_tax);
1417
+			$tax->maybe_save();
1418
+			$tax_total += $tax->total();
1419
+		}
1420
+		$this->_recalculate_tax_sub_total();
1421
+		return $tax_total;
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1427
+	 *
1428
+	 * @return void
1429
+	 * @throws EE_Error
1430
+	 * @throws InvalidArgumentException
1431
+	 * @throws InvalidDataTypeException
1432
+	 * @throws InvalidInterfaceException
1433
+	 * @throws ReflectionException
1434
+	 */
1435
+	private function _recalculate_tax_sub_total()
1436
+	{
1437
+		if ($this->is_tax_sub_total()) {
1438
+			$total = 0;
1439
+			$total_percent = 0;
1440
+			// simply loop through all its children (which should be taxes) and sum their total
1441
+			foreach ($this->children() as $child_tax) {
1442
+				if ($child_tax instanceof EE_Line_Item) {
1443
+					$total += $child_tax->total();
1444
+					$total_percent += $child_tax->percent();
1445
+				}
1446
+			}
1447
+			$this->set_total($total);
1448
+			$this->set_percent($total_percent);
1449
+			$this->maybe_save();
1450
+		} elseif ($this->is_total()) {
1451
+			foreach ($this->children() as $maybe_tax_subtotal) {
1452
+				if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1453
+					$maybe_tax_subtotal->_recalculate_tax_sub_total();
1454
+				}
1455
+			}
1456
+		}
1457
+	}
1458
+
1459
+
1460
+	/**
1461
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1462
+	 * recalculate_taxes_and_total
1463
+	 *
1464
+	 * @return float
1465
+	 * @throws EE_Error
1466
+	 * @throws InvalidArgumentException
1467
+	 * @throws InvalidDataTypeException
1468
+	 * @throws InvalidInterfaceException
1469
+	 * @throws ReflectionException
1470
+	 */
1471
+	public function get_total_tax()
1472
+	{
1473
+		$this->_recalculate_tax_sub_total();
1474
+		$total = 0;
1475
+		foreach ($this->tax_descendants() as $tax_line_item) {
1476
+			if ($tax_line_item instanceof EE_Line_Item) {
1477
+				$total += $tax_line_item->total();
1478
+			}
1479
+		}
1480
+		return $total;
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * Gets the total for all the items purchased only
1486
+	 *
1487
+	 * @return float
1488
+	 * @throws EE_Error
1489
+	 * @throws InvalidArgumentException
1490
+	 * @throws InvalidDataTypeException
1491
+	 * @throws InvalidInterfaceException
1492
+	 * @throws ReflectionException
1493
+	 */
1494
+	public function get_items_total()
1495
+	{
1496
+		// by default, let's make sure we're consistent with the existing line item
1497
+		if ($this->is_total()) {
1498
+			$pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1499
+			if ($pretax_subtotal_li instanceof EE_Line_Item) {
1500
+				return $pretax_subtotal_li->total();
1501
+			}
1502
+		}
1503
+		$total = 0;
1504
+		foreach ($this->get_items() as $item) {
1505
+			if ($item instanceof EE_Line_Item) {
1506
+				$total += $item->total();
1507
+			}
1508
+		}
1509
+		return $total;
1510
+	}
1511
+
1512
+
1513
+	/**
1514
+	 * Gets all the descendants (ie, children or children of children etc) that
1515
+	 * are of the type 'tax'
1516
+	 *
1517
+	 * @return EE_Line_Item[]
1518
+	 * @throws EE_Error
1519
+	 */
1520
+	public function tax_descendants()
1521
+	{
1522
+		return EEH_Line_Item::get_tax_descendants($this);
1523
+	}
1524
+
1525
+
1526
+	/**
1527
+	 * Gets all the real items purchased which are children of this item
1528
+	 *
1529
+	 * @return EE_Line_Item[]
1530
+	 * @throws EE_Error
1531
+	 */
1532
+	public function get_items()
1533
+	{
1534
+		return EEH_Line_Item::get_line_item_descendants($this);
1535
+	}
1536
+
1537
+
1538
+	/**
1539
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1540
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1541
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1542
+	 * but there is a "Taxable" discount), returns 0.
1543
+	 *
1544
+	 * @return float
1545
+	 * @throws EE_Error
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidDataTypeException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws ReflectionException
1550
+	 */
1551
+	public function taxable_total()
1552
+	{
1553
+		$total = 0;
1554
+		if ($this->children()) {
1555
+			foreach ($this->children() as $child_line_item) {
1556
+				if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1557
+					// if it's a percent item, only take into account the percent
1558
+					// that's taxable too (the taxable total so far)
1559
+					if ($child_line_item->is_percent()) {
1560
+						$total += ($total * $child_line_item->percent() / 100);
1561
+					} else {
1562
+						$total += $child_line_item->total();
1563
+					}
1564
+				} elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1565
+					$total += $child_line_item->taxable_total();
1566
+				}
1567
+			}
1568
+		}
1569
+		return max($total, 0);
1570
+	}
1571
+
1572
+
1573
+	/**
1574
+	 * Gets the transaction for this line item
1575
+	 *
1576
+	 * @return EE_Base_Class|EE_Transaction
1577
+	 * @throws EE_Error
1578
+	 * @throws InvalidArgumentException
1579
+	 * @throws InvalidDataTypeException
1580
+	 * @throws InvalidInterfaceException
1581
+	 * @throws ReflectionException
1582
+	 */
1583
+	public function transaction()
1584
+	{
1585
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1586
+	}
1587
+
1588
+
1589
+	/**
1590
+	 * Saves this line item to the DB, and recursively saves its descendants.
1591
+	 * Because there currently is no proper parent-child relation on the model,
1592
+	 * save_this_and_cached() will NOT save the descendants.
1593
+	 * Also sets the transaction on this line item and all its descendants before saving
1594
+	 *
1595
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1596
+	 * @return int count of items saved
1597
+	 * @throws EE_Error
1598
+	 * @throws InvalidArgumentException
1599
+	 * @throws InvalidDataTypeException
1600
+	 * @throws InvalidInterfaceException
1601
+	 * @throws ReflectionException
1602
+	 */
1603
+	public function save_this_and_descendants_to_txn($txn_id = null)
1604
+	{
1605
+		$count = 0;
1606
+		if (! $txn_id) {
1607
+			$txn_id = $this->TXN_ID();
1608
+		}
1609
+		$this->set_TXN_ID($txn_id);
1610
+		$children = $this->children();
1611
+		$count += $this->save()
1612
+			? 1
1613
+			: 0;
1614
+		foreach ($children as $child_line_item) {
1615
+			if ($child_line_item instanceof EE_Line_Item) {
1616
+				$child_line_item->set_parent_ID($this->ID());
1617
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1618
+			}
1619
+		}
1620
+		return $count;
1621
+	}
1622
+
1623
+
1624
+	/**
1625
+	 * Saves this line item to the DB, and recursively saves its descendants.
1626
+	 *
1627
+	 * @return int count of items saved
1628
+	 * @throws EE_Error
1629
+	 * @throws InvalidArgumentException
1630
+	 * @throws InvalidDataTypeException
1631
+	 * @throws InvalidInterfaceException
1632
+	 * @throws ReflectionException
1633
+	 */
1634
+	public function save_this_and_descendants()
1635
+	{
1636
+		$count = 0;
1637
+		$children = $this->children();
1638
+		$count += $this->save()
1639
+			? 1
1640
+			: 0;
1641
+		foreach ($children as $child_line_item) {
1642
+			if ($child_line_item instanceof EE_Line_Item) {
1643
+				$child_line_item->set_parent_ID($this->ID());
1644
+				$count += $child_line_item->save_this_and_descendants();
1645
+			}
1646
+		}
1647
+		return $count;
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * returns the cancellation line item if this item was cancelled
1653
+	 *
1654
+	 * @return EE_Line_Item[]
1655
+	 * @throws InvalidArgumentException
1656
+	 * @throws InvalidInterfaceException
1657
+	 * @throws InvalidDataTypeException
1658
+	 * @throws ReflectionException
1659
+	 * @throws EE_Error
1660
+	 */
1661
+	public function get_cancellations()
1662
+	{
1663
+		EE_Registry::instance()->load_helper('Line_Item');
1664
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1665
+	}
1666
+
1667
+
1668
+	/**
1669
+	 * If this item has an ID, then this saves it again to update the db
1670
+	 *
1671
+	 * @return int count of items saved
1672
+	 * @throws EE_Error
1673
+	 * @throws InvalidArgumentException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws InvalidInterfaceException
1676
+	 * @throws ReflectionException
1677
+	 */
1678
+	public function maybe_save()
1679
+	{
1680
+		if ($this->ID()) {
1681
+			return $this->save();
1682
+		}
1683
+		return false;
1684
+	}
1685
+
1686
+
1687
+	/**
1688
+	 * clears the cached children and parent from the line item
1689
+	 *
1690
+	 * @return void
1691
+	 */
1692
+	public function clear_related_line_item_cache()
1693
+	{
1694
+		$this->_children = array();
1695
+		$this->_parent = null;
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * @param bool $raw
1701
+	 * @return int
1702
+	 * @throws EE_Error
1703
+	 * @throws InvalidArgumentException
1704
+	 * @throws InvalidDataTypeException
1705
+	 * @throws InvalidInterfaceException
1706
+	 * @throws ReflectionException
1707
+	 */
1708
+	public function timestamp($raw = false)
1709
+	{
1710
+		return $raw
1711
+			? $this->get_raw('LIN_timestamp')
1712
+			: $this->get('LIN_timestamp');
1713
+	}
1714
+
1715
+
1716
+
1717
+
1718
+	/************************* DEPRECATED *************************/
1719
+	/**
1720
+	 * @deprecated 4.6.0
1721
+	 * @param string $type one of the constants on EEM_Line_Item
1722
+	 * @return EE_Line_Item[]
1723
+	 * @throws EE_Error
1724
+	 */
1725
+	protected function _get_descendants_of_type($type)
1726
+	{
1727
+		EE_Error::doing_it_wrong(
1728
+			'EE_Line_Item::_get_descendants_of_type()',
1729
+			sprintf(
1730
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1731
+				'EEH_Line_Item::get_descendants_of_type()'
1732
+			),
1733
+			'4.6.0'
1734
+		);
1735
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1736
+	}
1737
+
1738
+
1739
+	/**
1740
+	 * @deprecated 4.6.0
1741
+	 * @param string $type like one of the EEM_Line_Item::type_*
1742
+	 * @return EE_Line_Item
1743
+	 * @throws EE_Error
1744
+	 * @throws InvalidArgumentException
1745
+	 * @throws InvalidDataTypeException
1746
+	 * @throws InvalidInterfaceException
1747
+	 * @throws ReflectionException
1748
+	 */
1749
+	public function get_nearest_descendant_of_type($type)
1750
+	{
1751
+		EE_Error::doing_it_wrong(
1752
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1753
+			sprintf(
1754
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1755
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1756
+			),
1757
+			'4.6.0'
1758
+		);
1759
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1760
+	}
1761 1761
 }
Please login to merge, or discard this patch.